query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
ReplaceSend replaces the ssa.Send with the Send implemented in this package
func ReplaceSend(pkgs []*ssa.Package) { chToFuncs := findChannels(pkgs) for _, pkg := range pkgs { for name, memb := range pkg.Members { if memb.Token() == token.FUNC { f := pkg.Func(name) for _, b := range f.Blocks { for n, i := range b.Instrs { val, ok := i.(*ssa.Send) if ok { replace := &Send{&send{val, chToFuncs[val.Chan]}} b.Instrs[n] = replace } } } } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r ReplaceRouteRequest) Send(ctx context.Context) (*ReplaceRouteResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &ReplaceRouteResponse{\n\t\tReplaceRouteOutput: r.Request.Data.(*ReplaceRouteOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func transformSend(n *ir.SendStmt) {\n\tn.Value = assignconvfn(n.Value, n.Chan.Type().Elem())\n}", "func (m *TestFixClient) Send(msg fix.Messagable) error {\n\terr := fix.SendToTarget(msg, m.last.ID)\n\tsoh := byte(0x1)\n\tstr := strings.Replace(msg.ToMessage().String(), string([]byte{soh}), \"|\", -1)\n\tlog.Printf(\"[-> %s]: %s\", m.last.ID.String(), str)\n\treturn err\n}", "func newSend(name string, channel string) *Instruction {\n\treturn &Instruction{\n\t\tType: SendInst,\n\t\tName: name,\n\t\tChannel: channel,\n\t}\n}", "func (net *netService) send(session *session.Session, data []byte) {\n\tsession.Entity.Send(data)\n}", "func (s *Skeleton) RawSend(dst ServiceID, msgType MsgType, cmd CmdType, data ...interface{}) {\n\tsendNoEnc(s.s.getId(), dst, msgType, 0, cmd, data...)\n}", "func (tr *Transport) Send(ctx context.Context, msg *common.Message) error {\n\treturn ErrNotImplemented\n}", "func (s *Spock) Send(rf, send string, e *sherlock.Entity) {\n\t// we should do something, like notify!\n\te.D(\"last_notified\").Reset()\n\t// reset all send errors\n\te.B(rf + \".error\").Set(false)\n\tfor _, sendTo := range strings.Split(send, \" \") {\n\t\tif sendTo == \"\" {\n\t\t\t// no need to jump through hoops if the dev didn't anything for notify\n\t\t\tcontinue\n\t\t}\n\t\t// verify we have the appropriate channels\n\t\tif channel, exists := s.GetChannel(sendTo); exists {\n\t\t\t// set our template to be passed along\n\t\t\te.S(\"template\").Set(channel.Template)\n\t\t\t// json encode our entity, so we can then use it later on for templating stuff\n\t\t\tj, _ := json.Marshal(e)\n\t\t\t// take whatever we have currently in our entity and json encode it\n\t\t\tnotifyResults, notifyE := s.Lambda.Execute(sendTo, strings.NewReader(string(j)), strings.Split(channel.Params, \" \"))\n\t\t\tif notifyE != nil {\n\t\t\t\tlog.WithFields(log.Fields{\"name\": e.S(\"name\").String(), \"channel\": sendTo, \"type\": rf + \".error\"}).Error(notifyE.Error())\n\t\t\t\t// try again next check(if it fails)\n\t\t\t\te.B(rf + \".error\").Set(true)\n\t\t\t} else {\n\t\t\t\tlog.WithFields(log.Fields{\"name\": e.S(\"name\").String(), \"channel\": sendTo, \"type\": rf + \".success\"}).Info(notifyResults)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.WithFields(log.Fields{\"name\": e.S(\"name\").String(), \"channel\": sendTo, \"type\": rf + \".error\"}).Error(\"Channel does not exist\")\n\t\t\t// try again next check(if it fails)\n\t\t\te.B(rf + \".error\").Set(true)\n\t\t}\n\t}\n}", "func (packet *PlayerCraftingPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (packet *DefensaPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (r ReplaceIamInstanceProfileAssociationRequest) Send(ctx context.Context) (*ReplaceIamInstanceProfileAssociationResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &ReplaceIamInstanceProfileAssociationResponse{\n\t\tReplaceIamInstanceProfileAssociationOutput: r.Request.Data.(*ReplaceIamInstanceProfileAssociationOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (m *wasiSnapshotPreview1Impl) sockSend(pfd wasiFd, psiData list, psiFlags wasiSiflags) (rv wasiSize, err wasiErrno) {\n\terr = wasiErrnoNotsup\n\treturn\n}", "func Send(address string, req *pb.SaluteRequest, ctx context.Context) (*pb.SaluteResponse, error) {\n\t//implement here!\n\t//Don't forget to close the connection on exit!\n\n}", "func (s *Skeleton) Send(dst ServiceID, msgType MsgType, encType EncType, cmd CmdType, data ...interface{}) {\n\tsend(s.s.getId(), dst, msgType, encType, 0, cmd, data...)\n}", "func (packet *UpdateResourcePacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (s *Session) Send(msg fix.Messagable) error {\n\treturn fix.SendToTarget(msg, s.ID)\n}", "func (packet *RequestUseCharPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (f *Frontend) Send(msg FrontendMessage) error {\n\t_, err := f.w.Write(msg.Encode(nil))\n\treturn err\n}", "func (packet *ChoicePacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func Send(n *notify.Notify) error {\n\tif prov, ok := providers[n.Type]; ok {\n\t\terr := prov(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn errors.New(\"no provider for type \" + n.Type)\n\t}\n\n\treturn nil\n}", "func (packet *MapDataPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (packet *PlayerGameDataPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (_m *mockTransportChannel) Send(_a0 *contracts.Envelope) {\n\t_m.Called(_a0)\n}", "func (connection *SSEConnection) Send(payload []byte) {\n\tconnection.messageSendChannel <- payload\n}", "func (packet *BanditPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (session *CDPSession) BlockingSend(method string, send interface{}) ([]byte, error) {\n\treturn session.blockingSend(method, send)\n}", "func (packet *DemoValuePacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (packet *TrainStatPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func Send(content, status, expire string) {\n\t// avoid repeat sent\n\tuser := DefaultReceiver\n\tif d, found := cache.Get(user, content, status); found {\n\t\te := fmt.Sprintf(\"user: %v, content: %v not expired in %v, skip send\\n\",\n\t\t\tuser, content, d.Format(\"15:04:05\"))\n\t\tlog.Debug.Printf(e)\n\t\treturn\n\t}\n\n\t// set cache\n\tlog.Printf(\"user %v, %v, status: %v, expire set to %v\\n\", user, content, status, expire)\n\tcache.Set(user, content, status, expire)\n\n\treply, err := notice.Send(user, content, status, expire)\n\tif err != nil {\n\t\tlog.Printf(\"send alertall err: %v, resp: %v\\n\", err, reply)\n\t} else {\n\t\tlog.Printf(\"send alertall ok, resp: %v\\n\", reply)\n\t}\n\n}", "func (packet *NPCProjectilPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (s *Session) Send(data []byte) error {\n\treturn s.Entity.Send(data)\n}", "func (r *player) Send(ctx context.Context, msg core.Message) (core.Reply, error) {\n\tvar (\n\t\trep core.Reply\n\t\terr error\n\t)\n\n\tparcel, err := r.CreateParcel(ctx, msg)\n\tid := GetMessageHash(r.scheme, parcel)\n\n\t// Value from storageTape.\n\trep, err = r.tape.GetReply(ctx, id)\n\tif err == nil {\n\t\treturn rep, nil\n\t}\n\tif err == localstorage.ErrNotFound {\n\t\treturn nil, ErrNoReply\n\t} else {\n\t\treturn nil, err\n\t}\n\n\treturn rep, nil\n}", "func (s *GossipSender) Send(data GossipData) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tif s.empty() {\n\t\tdefer s.prod()\n\t}\n\tif s.gossip == nil {\n\t\ts.gossip = data\n\t} else {\n\t\ts.gossip = s.gossip.Merge(data)\n\t}\n}", "func (_m *Socket) Send(_a0 *packet.Writer) {\n\t_m.Called(_a0)\n}", "func (s *SocketModeAdapter) Send(ctx context.Context, channelID string, elements templates.OutputElements) error {\n\treturn Send(ctx, s.client, s, channelID, elements)\n}", "func (s *NullEventSpool) Send() {\n}", "func (transporter *Transporter) Send(channel string, data interface{}) {\n\ttransporter.SendJson(Message{\n\t\tChannel: channel,\n\t\tPayload: PayLoad{\n\t\t\tAt: time.Now().UnixNano() / int64(time.Millisecond),\n\t\t\tProcess: structures.Process{\n\t\t\t\tPmID: 0,\n\t\t\t\tName: transporter.Config.Name,\n\t\t\t\tServer: transporter.Config.ServerName, // WARN: maybe error here\n\t\t\t},\n\t\t\tData: data,\n\t\t\tActive: true,\n\t\t\tServerName: transporter.Config.ServerName,\n\t\t\tProtected: false,\n\t\t\tRevCon: true,\n\t\t\tInternalIP: metrics.LocalIP(),\n\t\t},\n\t})\n}", "func (cs *ClientSocket) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {\n\tircmsg := ircmsg.MakeMessage(tags, prefix, command, params...)\n\tline, err := ircmsg.Line()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcs.SendLines <- line\n\treturn nil\n}", "func Send(ctx context.Context, activateTransmitter func(bool), transmitSymbol func(Symbol), transmission Transmission) bool {\n\tdefer activateTransmitter(false)\n\tif !waitForTransmitStart(ctx) {\n\t\treturn false\n\t}\n\n\tlog.Print(\"transmission start\")\n\n\tfor i, symbol := range transmission {\n\t\tfmt.Print(\".\")\n\n\t\ttransmitSymbol(symbol)\n\t\tif i == 0 {\n\t\t\tactivateTransmitter(true)\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(SymbolDuration):\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfmt.Println()\n\tlog.Print(\"transmission end\")\n\treturn true\n}", "func (e *Escpos) gSend(m byte, fn byte, data []byte) {\n\tl := len(data) + 2\n\n\te.Write(\"\\x1b(L\")\n\te.WriteRaw([]byte{byte(l % 256), byte(l / 256), m, fn})\n\te.WriteRaw(data)\n}", "func (mr *MockAgentSecure_TaggerStreamEntitiesServerMockRecorder) Send(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Send\", reflect.TypeOf((*MockAgentSecure_TaggerStreamEntitiesServer)(nil).Send), arg0)\n}", "func (s *system) Send(wr io.Writer) {\n\ttpl, err := template.\n\t\tNew(\"system\").\n\t\tFuncs(template.FuncMap{\n\t\t\t\"strContains\": func(src string, tgt string) bool {\n\t\t\t\tres := strings.EqualFold(src, tgt)\n\t\t\t\treturn res\n\t\t\t},\n\t\t}).\n\t\tParse(templateSystem)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = tpl.Execute(wr, s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (r *Request) Send(text string) {\n\tr.robot.adapter.Send(r.Message, text)\n}", "func (b *base) Send(callback ResponseCallback) {\n\tid := b.Id\n\n\tif callback != nil {\n\t\tb.proc.callbacks.set(id, callback)\n\t\tgo b.proc.removeCallback(id)\n\t}\n\n\tif b.port == b.proc.GetPort() {\n\t\tgo b.proc.baseHandler(b)\n\t\treturn\n\t}\n\n\tb.Id = 0\n\tb.proc.ipc.Send(id, b.Marshal(), b.GetPort())\n}", "func (h *middlewareHarness) sendAccept(msgID uint64,\n\tresponseReplacement proto.Message) {\n\n\tvar replacementBytes []byte\n\tif responseReplacement != nil {\n\t\tvar err error\n\t\treplacementBytes, err = proto.Marshal(responseReplacement)\n\t\trequire.NoError(h.t, err)\n\t}\n\n\terr := h.stream.Send(&lnrpc.RPCMiddlewareResponse{\n\t\tMiddlewareMessage: &lnrpc.RPCMiddlewareResponse_Feedback{\n\t\t\tFeedback: &lnrpc.InterceptFeedback{\n\t\t\t\tReplaceResponse: len(replacementBytes) > 0,\n\t\t\t\tReplacementSerialized: replacementBytes,\n\t\t\t},\n\t\t},\n\t\tRefMsgId: msgID,\n\t})\n\trequire.NoError(h.t, err)\n}", "func (s *session) scheduleSending(schedulerSendData SchedulerSendData) {\n\tselect {\n\tcase s.sendingScheduled <- schedulerSendData:\n\tdefault:\n\t}\n}", "func (s *Skeleton) SendClose(dst ServiceID, isForce bool) {\n\tsendNoEnc(s.s.getId(), dst, MSG_TYPE_CLOSE, 0, Cmd_None, isForce)\n}", "func (packet *GlobalMessagePacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (net *MockNetwork) Send(msg []byte, to string) error {\n\tnet.Connexions[to] <- msg\n\treturn nil\n}", "func (r UpdateBrokerStorageRequest) Send(ctx context.Context) (*UpdateBrokerStorageResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &UpdateBrokerStorageResponse{\n\t\tUpdateBrokerStorageOutput: r.Request.Data.(*UpdateBrokerStorageOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (packet *PlayerDataTypePacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (packet *BlockListPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (_Erc777 *Erc777Transactor) Send(opts *bind.TransactOpts, recipient common.Address, amount *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _Erc777.contract.Transact(opts, \"send\", recipient, amount, data)\n}", "func (s *Slave) send(pp *BinaryPacket) (err error) {\n\tif _, err = pp.WriteTo(s.cw); err != nil {\n\t\treturn\n\t}\n\treturn s.cw.Flush()\n}", "func (a *HipchatAdapter) Send(res *Response, strings ...string) error {\n\treturn nil\n}", "func (c *Client) Send(message dhcpv6.DHCPv6, modifiers ...dhcpv6.Modifier) *promise.Future {\n\tfor _, mod := range modifiers {\n\t\tmod(message)\n\t}\n\n\ttransactionID, err := dhcpv6.GetTransactionID(message)\n\tif err != nil {\n\t\treturn promise.Wrap(err)\n\t}\n\n\tp := promise.NewPromise()\n\tc.packetsLock.Lock()\n\tc.packets[transactionID] = p\n\tc.packetsLock.Unlock()\n\tc.sendQueue <- message\n\treturn p.Future\n}", "func (m *TransportMutation) ResetSend() {\n\tm.send = nil\n\tm.clearedsend = false\n}", "func (r UpdateSignalingChannelRequest) Send(ctx context.Context) (*UpdateSignalingChannelResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &UpdateSignalingChannelResponse{\n\t\tUpdateSignalingChannelOutput: r.Request.Data.(*UpdateSignalingChannelOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (b *Broadcaster) Send(v interface{}) { b.Sendc <- v }", "func (mr *MockAgentSecure_TaggerStreamEntitiesClientMockRecorder) CloseSend() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CloseSend\", reflect.TypeOf((*MockAgentSecure_TaggerStreamEntitiesClient)(nil).CloseSend))\n}", "func (packet *PlayerConnectedPacket) SetSend(value bool) {\n\tpacket.Send = value\n}", "func (pipe *PipeWS) Send(msg *mangos.Message) error {\n\t// if msg.Expired() {\n\t// \tmsg.Free()\n\t// \treturn nil\n\t// }\n\tvar buf []byte\n\tif len(msg.Header) > 0 {\n\t\tbuf = make([]byte, 0, len(msg.Header)+len(msg.Body))\n\t\tbuf = append(buf, msg.Header...)\n\t\tbuf = append(buf, msg.Body...)\n\t} else {\n\t\tbuf = msg.Body\n\t}\n\n\t_, err := (*pipe.conn).Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmsg.Free()\n\treturn nil\n}", "func (dsl *PutDSL) Send() vpp_clientv1.Reply {\n\treturn dsl.parent.Send()\n}", "func (dsl *PutDSL) Send() vpp_clientv1.Reply {\n\treturn dsl.parent.Send()\n}", "func (sg *SGClient) Send() ([]string, error) {\n\tfmt.Println(\"SendGrid Client for future enhancement\")\n\treturn nil, nil\n}", "func (a *Agent) Send(cmd protocol.Command, data []byte) error {\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.Write(a.ID)\n\tbuf.Write(protocol.NullChar)\n\tbuf.WriteByte(byte(cmd))\n\tif data != nil {\n\t\tbuf.Write(protocol.NullChar)\n\t\tbuf.Write(data)\n\t}\n\treturn a.conn.Send(buf.Bytes())\n}", "func (ctx *Context) Send(smsg *SendMessage) (int, error) {\n\tmsgid, err := ctx.Bot.SendMessage(ctx.Chat.ID, smsg)\n\tif err != nil {\n\t\treturn msgid, err\n\t}\n\n\tctx.chat.setEditMessageID(msgid)\n\n\treturn msgid, err\n}", "func (s *ClientStream) CloseSend() error {\n\treturn s.writeMessage(nil, true)\n}", "func (tp *Transport) Send(msg *sip.Msg) error {\n\tPopulateMessage(tp.Via, tp.Contact, msg)\n\thost, port, err := RouteMessage(tp.Via, tp.Contact, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\taddr, err := net.ResolveUDPAddr(\"udp\", net.JoinHostPort(host, util.Portstr(port)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif msg.MaxForwards > 0 {\n\t\tmsg.MaxForwards--\n\t}\n\tts := time.Now()\n\taddTimestamp(msg, ts)\n\tvar b bytes.Buffer\n\tmsg.Append(&b)\n\tif *tracing {\n\t\ttrace(\"send\", b.Bytes(), addr)\n\t}\n\t_, err = tp.Sock.WriteTo(b.Bytes(), addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func notifySend(notif *Notification) {\n\t// Decide on the correct urgency string for notify-send\n\turgency := \"critical\"\n\tif notif.Priority < NORMAL {\n\t\turgency = \"low\"\n\t} else if notif.Priority < IMPORTANT {\n\t\turgency = \"normal\"\n\t}\n\n\t// Override the notification icon with an urgency-based one if it's not set\n\ticon := notif.Icon\n\tif icon == \"\" {\n\t\ticon = fmt.Sprintf(\"%s.png\", urgency)\n\t}\n\n\t// Patch for a bug in notify-send which causes it to not show messages\n\t// See www.archivum.info/ubuntu-bugs: Bug 1424243\n\tmsg := strings.Replace(notif.Message, \"&\", \"and\", -1)\n\n\tcmd := exec.Command(\n\t\t\"/usr/bin/env\",\n\t\t\"notify-send\",\n\t\t\"-i\", filepath.Join(config.Static.IconPath, icon),\n\t\t\"-t\", fmt.Sprintf(\"%d\", config.Notifications.NotifySend.Duration/time.Millisecond),\n\t\t\"-u\", urgency,\n\t\tnotif.Title,\n\t\tmsg,\n\t)\n\n\tlog.Debug(\"Command: %s %s\", cmd.Path, cmd.Args)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Critical(\"notify-send failed: `%s %s` (%v)\", cmd.Path, cmd.Args, err)\n\t\treturn\n\t}\n\tnotif.MarkComplete()\n}", "func (b *bot) Send(conn Connector, kind Kind, args ...any) (string, error) {\n\tif b.quiet {\n\t\treturn \"\", nil\n\t}\n\treturn conn.Send(kind, args...)\n}", "func (mr *MockAgentSecure_WorkloadmetaStreamEntitiesServerMockRecorder) Send(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Send\", reflect.TypeOf((*MockAgentSecure_WorkloadmetaStreamEntitiesServer)(nil).Send), arg0)\n}", "func (pp *PacketParser) send(sentence []byte, received time.Time) {\n\tcurrent := uint32(len(pp.async))\n\tif current > pp.maxInChan {\n\t\tpp.maxInChan = current\n\t}\n\tpp.async <- sendSentence{\n\t\treceived: received,\n\t\ttext: sentence,\n\t}\n}", "func (service *Service) Send(message string, paramsPtr *types.Params) error {\n\tconfig := *service.config\n\n\tvar params types.Params\n\tif paramsPtr == nil {\n\t\tparams = types.Params{}\n\t} else {\n\t\tparams = *paramsPtr\n\t}\n\n\tif err := service.pkr.UpdateConfigFromParams(&config, &params); err != nil {\n\t\tservice.Logf(\"Failed to update params: %v\", err)\n\t}\n\n\t// Create a mutable copy of the passed params\n\tsendParams := createSendParams(&config, params, message)\n\n\tif err := service.doSend(&config, sendParams); err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while sending notification to generic webhook: %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func (r UpdateGatewayGroupRequest) Send(ctx context.Context) (*UpdateGatewayGroupResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &UpdateGatewayGroupResponse{\n\t\tUpdateGatewayGroupOutput: r.Request.Data.(*UpdateGatewayGroupOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func NewSend(u Name) *Send {\n\treturn &Send{Chan: u}\n}", "func (r DisableEbsEncryptionByDefaultRequest) Send(ctx context.Context) (*DisableEbsEncryptionByDefaultResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DisableEbsEncryptionByDefaultResponse{\n\t\tDisableEbsEncryptionByDefaultOutput: r.Request.Data.(*DisableEbsEncryptionByDefaultOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (ctx *ChannelContext) Send(module string, message interface{}) {\n\t// avoid exception because of channel colsing\n\t// TODO: need reconstruction\n\tdefer func() {\n\t\tif exception := recover(); exception != nil {\n\t\t\tklog.Warningf(\"Recover when send message, exception: %+v\", exception)\n\t\t}\n\t}()\n\n\tif channel := ctx.getChannel(module); channel != nil {\n\t\tchannel <- message\n\t\treturn\n\t}\n\tklog.Warningf(\"Get bad module name :%s when send message, do nothing\", module)\n}", "func (gs *GRPCClient) Send(uid string, d []byte) error {\n\treturn constants.ErrNotImplemented\n}", "func (mr *MockAgentSecure_WorkloadmetaStreamEntitiesClientMockRecorder) CloseSend() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CloseSend\", reflect.TypeOf((*MockAgentSecure_WorkloadmetaStreamEntitiesClient)(nil).CloseSend))\n}", "func (sock *Server) Send(message string) {\n\tgo func() {\n\t\tselect {\n\t\tcase <-sock.kill:\n\t\tcase sock.sendqueue <- message + \"\\n\":\n\t\t}\n\t}()\n}", "func SimpleSend(c *Connection, payload interface{}) {\n\theader := new(ParcelHeader).Init(TestNet) //.(*ParcelHeader)\n\tparcel := new(Parcel).Init(*header) //.(*Parcel)\n\tparcel.Payload = payload\n\tc.SendChannel <- *parcel\n}", "func (s Broker) Send(datum interface{}) {\n\tselect {\n\tcase s <- datum:\n\tdefault:\n\t}\n}", "func (n *NSCAServer) Send(message *Message) error {\n\tmsg := newDataPacket(n.serverTimestamp, message.State, message.Host, message.Service, message.Message)\n\terr := msg.write(n.conn, n.encryption)\n\treturn err\n}", "func (dtm *DirectToMessage) Replace(db XODB) error {\n\tvar err error\n\n\t// sql query\n\n\tconst sqlstr = `REPLACE INTO ms.direct_to_message (` +\n\t\t`Id, ChatKey, MessageId, SourceEnumId` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, dtm.Id, dtm.ChatKey, dtm.MessageId, dtm.SourceEnumId)\n\t_, err = db.Exec(sqlstr, dtm.Id, dtm.ChatKey, dtm.MessageId, dtm.SourceEnumId)\n\tif err != nil {\n\t\tXOLogErr(err)\n\t\treturn err\n\t}\n\n\tdtm._exists = true\n\n\tOnDirectToMessage_AfterInsert(dtm)\n\n\treturn nil\n}", "func Send(self, value Object) (Object, error) {\n\tif I, ok := self.(I_send); ok {\n\t\treturn I.Send(value)\n\t} else if res, ok, err := TypeCall1(self, \"send\", value); ok {\n\t\treturn res, err\n\t}\n\treturn nil, ExceptionNewf(TypeError, \"'%s' object doesn't have send method\", self.Type().Name)\n}", "func (spi *SPIDevice) Send(bytes_to_send []byte) ([]byte, error) {\n\twBuffer := bytes_to_send\n\trBuffer := [3]byte{}\n\n\t// generates message\n\ttransfer := SpiIocTransfert{}\n\ttransfer.txBuf = uint64(uintptr(unsafe.Pointer(&wBuffer[0])))\n\ttransfer.rxBuf = uint64(uintptr(unsafe.Pointer(&rBuffer[0])))\n\ttransfer.length = uint32(len(wBuffer))\n\ttransfer.delayUsecs = SPI_DELAY\n\ttransfer.csChange = 1\n\ttransfer.bitsPerWord = spi.bpw\n\ttransfer.speedHz = spi.speed\n\n\t// sends message over SPI\n\terr := ioctl.IOCTL(spi.file.Fd(), SPI_IOC_MESSAGE(1), uintptr(unsafe.Pointer(&transfer)))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error on sending: %s\\n\", err)\n\t}\n\n\t// generates a valid response\n\tret := make([]byte, unsafe.Sizeof(rBuffer))\n\tfor i := range ret {\n\t\tret[i] = rBuffer[i]\n\t}\n\n\treturn ret, nil\n}", "func (m *HospitalMutation) ResetSend() {\n\tm.send = nil\n\tm.removedsend = nil\n}", "func (r *Radio) Send(data []byte) {\n}", "func Send(s Stream, data []byte) error {\n\tselect {\n\tcase <-s.Done():\n\t\treturn WriteClosedErr\n\tdefault:\n\t}\n\tselect {\n\tcase s.Outgoing() <- data:\n\tcase <-s.Done():\n\t\treturn WriteClosedErr\n\t}\n\treturn nil\n}", "func (t *Test) Send(time.Time, []byte) {}", "func FlushSend(q Queue) {\n\tif flusher, ok := q.(Flusher); ok {\n\t\tflusher.FlushSend()\n\t}\n}", "func (_Transfer *TransferTransactor) Send(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Transfer.contract.Transact(opts, \"send\")\n}", "func (a *BotAdapter) Send(text, channelID string) error {\n\n\tcid, ok := a.idFromName[channelID]\n\tif !ok {\n\t\treturn errors.New(fmt.Sprintf(\"could not find channel name: '%s'\", channelID))\n\t}\n\tch := a.roomByID(cid)\n\n\tmsg := a.newMessage(&ch, text)\n\n\ta.logger.Info(\"Sending message to channel\",\n\t\tzap.String(\"channelID\", channelID),\n\t\t// do not leak actual message content since it might be sensitive\n\t)\n\t_, err := a.rocket.SendMessage(msg)\n\n\treturn err\n}", "func (ns *KaveNegar) Send(message sachet.Message) error {\n\turl := \"https://api.kavenegar.com/v1/\" + ns.APIToken + \"/sms/send.json\"\n\trequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest.Header.Set(\"User-Agent\", \"Sachet\")\n\tparams := request.URL.Query()\n\tparams.Add(\"receptor\", strings.Join(message.To, \",\"))\n\t// \"params.Add(\"sender\", message.From)\" retrieves the sender number using \"from\" under receivers section,\n\t// if you leave that empty, KaveNegar will use default sender SMS number to send the message.\n\tparams.Add(\"sender\", message.From)\n\tparams.Add(\"message\", message.Text)\n\trequest.URL.RawQuery = params.Encode()\n\tresponse, err := ns.HTTPClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusOK {\n\t\tbody, _ := ioutil.ReadAll(response.Body)\n\t\treturn fmt.Errorf(\n\t\t\t\"SMS sending failed. HTTP status code: %d, Response body: %s\",\n\t\t\tresponse.StatusCode,\n\t\t\tbody,\n\t\t)\n\t}\n\tfmt.Println(\"Message sent: \", message.Text)\n\treturn nil\n}", "func (mr *MockProvisioner_ProvisionResourceClientMockRecorder) CloseSend() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CloseSend\", reflect.TypeOf((*MockProvisioner_ProvisionResourceClient)(nil).CloseSend))\n}", "func (self *netmgrT) Send2GS(message msg.Message) {\n\tcnnGS := self.cnnGS\n\tif cnnGS != nil {\n\t\tcnnGS.SendMsg(message)\n\t}\n}", "func send(h p2p.Host, peer p2p.Peer, message []byte, lostPeer chan p2p.Peer) {\n\t// Add attack code here.\n\t//attack.GetInstance().Run()\n\tbackoff := p2p.NewExpBackoff(250*time.Millisecond, 5*time.Second, 2)\n\n\tfor trial := 0; trial < 3; trial++ {\n\t\terr := h.SendMessage(peer, message)\n\t\t// No need to retry if new stream error or no error\n\t\tif err == nil || err == p2p.ErrNewStream {\n\t\t\tif trial > 0 {\n\t\t\t\tlog.Warn(\"retry send\", \"rety\", trial)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tlog.Info(\"sleeping before trying to send again\",\n\t\t\t\"duration\", backoff.Cur, \"addr\", net.JoinHostPort(peer.IP, peer.Port))\n\t\tbackoff.Sleep()\n\t}\n\tlog.Error(\"gave up sending a message\", \"addr\", net.JoinHostPort(peer.IP, peer.Port))\n\n\tif lostPeer != nil {\n\t\t// Notify lostPeer channel\n\t\tlostPeer <- peer\n\t}\n}", "func (d *DataPacket) replace(startIndex int, replacement []byte) {\n\td.data = append(d.data[:startIndex],\n\t\tappend(replacement, d.data[len(replacement)+startIndex:]...)...)\n}", "func (mr *MockPdfService_InternalRasterizePdfClientMockRecorder) CloseSend() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CloseSend\", reflect.TypeOf((*MockPdfService_InternalRasterizePdfClient)(nil).CloseSend))\n}" ]
[ "0.6314108", "0.5838266", "0.5631321", "0.5519704", "0.5514851", "0.54718554", "0.54669833", "0.546213", "0.5422835", "0.5415282", "0.53728646", "0.53687954", "0.53408754", "0.53067815", "0.5303356", "0.52740926", "0.52599657", "0.52368826", "0.52344894", "0.52235734", "0.52166", "0.5216359", "0.5207495", "0.5196195", "0.5169478", "0.5141385", "0.51363224", "0.512414", "0.50949216", "0.50940114", "0.5093756", "0.5084959", "0.50687814", "0.5066064", "0.50659883", "0.50655603", "0.5055577", "0.50537294", "0.5049298", "0.50491226", "0.5024639", "0.5022604", "0.5020883", "0.5016631", "0.50163025", "0.5013516", "0.501224", "0.5009087", "0.5005586", "0.5005419", "0.49848375", "0.49834615", "0.4980454", "0.4977031", "0.49703407", "0.49630228", "0.49579367", "0.49573368", "0.49536318", "0.4948176", "0.49473232", "0.49457902", "0.49389148", "0.49389148", "0.49329242", "0.4926073", "0.49144393", "0.4912977", "0.49102378", "0.49097827", "0.4908833", "0.490402", "0.49026087", "0.48956603", "0.48918444", "0.48832056", "0.48810363", "0.4880347", "0.48739505", "0.4872654", "0.48695785", "0.4861514", "0.48609734", "0.48580408", "0.4853441", "0.48510504", "0.48502746", "0.4847253", "0.48462653", "0.4843716", "0.4840879", "0.48398817", "0.4833972", "0.48305425", "0.48244077", "0.4820582", "0.48073605", "0.48025975", "0.48011205", "0.4799549" ]
0.75851923
0
fincChannels finds for all channels the corresponding call instructions
func findChannels(mains []*ssa.Package) map[ssa.Value][]ssa.CallInstruction { var callCom *ssa.CallCommon chfuncs := make(map[ssa.Value][]ssa.CallInstruction, 0) for _, pkg := range mains { for name, memb := range pkg.Members { if memb.Token() == token.FUNC { f := pkg.Func(name) for _, b := range f.Blocks { for _, i := range b.Instrs { callCom = nil switch it := i.(type) { case *ssa.Go: callCom = it.Common() case *ssa.Defer: callCom = it.Common() case *ssa.Call: callCom = it.Common() } if callCom != nil { args: for _, v := range callCom.Args { mc, ok := v.(*ssa.MakeChan) i, _ := i.(ssa.CallInstruction) if ok { calls := chfuncs[mc] if calls == nil { calls = make([]ssa.CallInstruction, 0) } chfuncs[mc] = append(calls, i) continue args } // TODO: find better solution underly := v.Type().Underlying() isChan := strings.Contains(underly.String(), "chan") if isChan { calls := chfuncs[v] if calls == nil { calls = make([]ssa.CallInstruction, 0) } chfuncs[v] = append(calls, i) } } } } } } } } return chfuncs }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Dao) Channels(c context.Context, arg *model.ArgChannels) (res []*model.Channel, err error) {\n\trows, err := d.db.Query(c, _channelsSQL, arg.LastID, arg.Size)\n\tif err != nil {\n\t\tlog.Error(\"d.dao.Channels(%v) error(%v)\", arg, err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tres = make([]*model.Channel, 0, arg.Size)\n\tfor rows.Next() {\n\t\tt := &model.Channel{}\n\t\tif err = rows.Scan(&t.ID, &t.Rank, &t.TopRank, &t.Type, &t.Operator, &t.State, &t.Attr, &t.CTime, &t.MTime); err != nil {\n\t\t\tlog.Error(\"d.dao.Channels(%v) rows.Scan() error(%v)\", arg, err)\n\t\t\treturn\n\t\t}\n\t\tres = append(res, t)\n\t}\n\treturn\n}", "func (_TokensNetwork *TokensNetworkCallerSession) Channels(arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\treturn _TokensNetwork.Contract.Channels(&_TokensNetwork.CallOpts, arg0)\n}", "func (_TokensNetwork *TokensNetworkCaller) Channels(opts *bind.CallOpts, arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\tret := new(struct {\n\t\tSettleTimeout uint64\n\t\tSettleBlockNumber uint64\n\t\tOpenBlockNumber uint64\n\t\tState uint8\n\t})\n\tout := ret\n\terr := _TokensNetwork.contract.Call(opts, out, \"channels\", arg0)\n\treturn *ret, err\n}", "func (_TokensNetwork *TokensNetworkSession) Channels(arg0 [32]byte) (struct {\n\tSettleTimeout uint64\n\tSettleBlockNumber uint64\n\tOpenBlockNumber uint64\n\tState uint8\n}, error) {\n\treturn _TokensNetwork.Contract.Channels(&_TokensNetwork.CallOpts, arg0)\n}", "func (l *loopInSwapSuggestion) channels() []lnwire.ShortChannelID {\n\treturn nil\n}", "func (c *Client) Channels(ctx context.Context, r ChannelsRequest) (*ChannelsReply, error) {\r\n\treq, err := http.NewRequestWithContext(\r\n\t\tctx,\r\n\t\thttp.MethodGet,\r\n\t\tfmt.Sprintf(\"%s/%s/channel/list\", c.getChanelBaseEndpoint(), r.AccountID),\r\n\t\tnil,\r\n\t)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tres := ChannelsReply{}\r\n\tif err := c.sendRequest(req, &res); err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &res, nil\r\n}", "func (t Track) Channels() int {\n\tpanic(\"implement me\")\n}", "func (cm *ConnectionManager) receivingChannels() (chs []*channeltype.Serialization) {\n\tfor _, c := range cm.openChannels() {\n\t\tif c.PartnerBalanceProof != nil && c.PartnerBalanceProof.Nonce > 0 {\n\t\t\tchs = append(chs, c)\n\t\t}\n\t}\n\treturn\n}", "func (c *ConnectionMock) Channels() []string {\n\targs := c.Called()\n\treturn args.Get(0).([]string)\n}", "func unaryExprReadChannels(unaryExpr *ast.UnaryExpr) []*ast.Ident {\n\tswitch x := unaryExpr.X.(type) {\n\tcase *ast.Ident:\n\t\t// e.g: `<-channel`\n\t\treturn []*ast.Ident{x}\n\tcase *ast.CallExpr:\n\t\t// e.g: `<-fn()`\n\t\t// todo: handle\n\t}\n\treturn nil\n}", "func (c *ChanDirectionChecker) funcsChanParamsUsage(fn ast.Node, params []*ast.Field) map[*ast.Field]ast.ChanDir {\n\tm := make(map[*ast.Field]ast.ChanDir)\n\n\twalkFunc := func(node ast.Node) bool {\n\t\t// Mark any channel parameter used in function call as bidirectional\n\t\tif callExpr, ok := node.(*ast.CallExpr); ok {\n\t\t\tfor _, field := range paramsUsedInArgs(params, callExpr.Args) {\n\t\t\t\tif fieldInParams(field, params) {\n\t\t\t\t\tm[field] = m[field] | biDirectionalChan\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Send to channel\n\t\tif sendStmt, ok := node.(*ast.SendStmt); ok {\n\t\t\tif id, ok := sendStmt.Chan.(*ast.Ident); ok && objInParams(id.Obj, params) { // We only care when the channel is an identifier\n\t\t\t\tfield := id.Obj.Decl.(*ast.Field)\n\t\t\t\tm[field] = m[field] | ast.SEND\n\t\t\t}\n\t\t}\n\n\t\t// Read from channel\n\t\tif unaryExpr, ok := node.(*ast.UnaryExpr); ok {\n\t\t\top := unaryExpr.Op.String()\n\t\t\tif op == \"<-\" {\n\t\t\t\tfor _, id := range unaryExprReadChannels(unaryExpr) {\n\t\t\t\t\tif objInParams(id.Obj, params) {\n\t\t\t\t\t\tfield := id.Obj.Decl.(*ast.Field)\n\t\t\t\t\t\tm[field] = m[field] | ast.RECV\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Range over a channel\n\t\tif rngStmt, ok := node.(*ast.RangeStmt); ok {\n\t\t\tif ident, ok := rngStmt.X.(*ast.Ident); ok && objInParams(ident.Obj, params) {\n\t\t\t\tfield := ident.Obj.Decl.(*ast.Field)\n\t\t\t\tm[field] = m[field] | ast.RECV\n\t\t\t}\n\t\t}\n\n\t\t// Close of a channel\n\t\tif callExpr, ok := node.(*ast.CallExpr); ok && isBuiltinCloseCall(callExpr) {\n\t\t\tif ident, ok := callExpr.Args[0].(*ast.Ident); ok && objInParams(ident.Obj, params) {\n\t\t\t\tfield := ident.Obj.Decl.(*ast.Field)\n\t\t\t\tm[field] = m[field] | biDirectionalChan\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\tfnBody := fn.(*ast.FuncDecl).Body\n\tast.Inspect(fnBody, walkFunc)\n\n\treturn m\n}", "func (_obj *Apichannels) Channels_getInactiveChannels(params *TLchannels_getInactiveChannels, _opt ...map[string]string) (ret Messages_InactiveChats, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getInactiveChannels\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func DiscoverChannels(conn *NetworkConnection, options ...DiscoverOptionFunc) map[string]string {\n\t// map[channelID]endpointURL\n\tchannelIDMap := make(map[string]string)\n\n\t//opt := generateOption(options...)\n\t// Get all channels.\n\t// The network peers are corresponding to the config in yaml organizations/<org>/peers.\n\t// They will be blank if no peers defined. But acutally all the peers can be found by discover service.\n\t// TODO if the endpoint config is nil, that means the identity is not found, the error should be return.\n\tif conn.Client.EndpointConfig() != nil {\n\t\tfor _, endpoint := range conn.Client.EndpointConfig().NetworkPeers() {\n\t\t\t// It doesn't work now, since we still need to retrieve channels from the endpoint configured.\n\t\t\t// if !opt.isTarget(endpoint.URL) {\n\t\t\t// \tcontinue\n\t\t\t// }\n\n\t\t\t//if endpoint.MSPID == conn.Participant.MSPID\n\t\t\tchannels, err := GetJoinedChannels(conn, endpoint.URL, options...)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"Getting joined channels got failed for endpoint %s: %s\", endpoint.URL, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only the first endpoint will be processed if they are duplicated.\n\t\t\t// TODO to get and use all peers of the channel.\n\t\t\tfor _, channel := range channels {\n\t\t\t\tif _, ok := channelIDMap[channel.GetChannelId()]; !ok {\n\t\t\t\t\tchannelIDMap[channel.GetChannelId()] = endpoint.URL\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger.Infof(\"Found channels and only corresponding endpoints %v.\", channelIDMap)\n\treturn channelIDMap\n}", "func (l *loopOutSwapSuggestion) channels() []lnwire.ShortChannelID {\n\tchannels := make(\n\t\t[]lnwire.ShortChannelID, len(l.OutRequest.OutgoingChanSet),\n\t)\n\n\tfor i, id := range l.OutRequest.OutgoingChanSet {\n\t\tchannels[i] = lnwire.NewShortChanIDFromInt(id)\n\t}\n\n\treturn channels\n}", "func (rs *ReactorShim) GetChannels() []*ChannelDescriptor {\n\tsortedChIDs := make([]ChannelID, 0, len(rs.Channels))\n\tfor cID := range rs.Channels {\n\t\tsortedChIDs = append(sortedChIDs, cID)\n\t}\n\n\tsort.Slice(sortedChIDs, func(i, j int) bool { return sortedChIDs[i] < sortedChIDs[j] })\n\n\tdescriptors := make([]*ChannelDescriptor, len(rs.Channels))\n\tfor i, cID := range sortedChIDs {\n\t\tdescriptors[i] = rs.Channels[cID].Descriptor\n\t}\n\n\treturn descriptors\n}", "func (_obj *Apichannels) Channels_getChannels(params *TLchannels_getChannels, _opt ...map[string]string) (ret Messages_Chats, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getChannels\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (f *Format) Channels() int {\n\treturn f.channels\n}", "func (h *Handler) channelRoutine(channel string) {\n\tif c, ok := h.channels[channel]; ok {\n\t\tfor {\n\t\t\tmsg := <-c.send\n\t\t\tfor _, listener := range c.listeners {\n\t\t\t\terr := h.writeToClient(listener, msg.command, msg.content)\n\t\t\t\tif err != nil {\n\t\t\t\t\th.unregisterAsListener(listener, channel) // nolint: errcheck\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *sessionManager) manageChannels() {\n\tfor {\n\t\tselect {\n\t\tcase cID := <-s.exit:\n\t\t\ts.doExit(cID)\n\t\t\tcontinue\n\t\tcase u := <-s.requeue:\n\t\t\ts.manageUpdate(u)\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase cID := <-s.exit:\n\t\t\ts.doExit(cID)\n\t\t\tcontinue\n\t\tcase u := <-s.requeue:\n\t\t\ts.manageUpdate(u)\n\t\tcase u := <-s.update:\n\t\t\ts.manageUpdate(u)\n\t\t}\n\t}\n}", "func (fcg *FuncCallGraph) FuncsInSCC(scc SCC) []*ir.Func {\n\tfcg.updateSCCs()\n\treturn fcg.sccToFuncs[scc]\n}", "func FanIn(CerChannel, DwrChannel, CcrChannel <-chan Sig) <-chan Sig {\n\tchannel := make(chan Sig)\n\tgo func() {\n\t\tfor {\n\t\t\tchannel <- <-CerChannel\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor {\n\t\t\tchannel <- <-DwrChannel\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor {\n\t\t\tchannel <- <-CcrChannel\n\t\t}\n\t}()\n\treturn channel\n}", "func (c *Consumer) UpdateOnChannel(ctx context.Context, fns ...OnChannel) error {\n\tfor _, fn := range fns {\n\t\terrCh := make(chan error)\n\t\tclosure := func(ch *amqp.Channel) error {\n\t\t\tvar err error\n\n\t\t\tdefer func() {\n\t\t\t\tc.onChan = fn\n\t\t\t\terrCh <- err\n\t\t\t}()\n\n\t\t\terr = fn(ch)\n\t\t\treturn err\n\t\t}\n\n\t\tselect {\n\t\tcase c.funcCh <- closure:\n\t\tcase <-ctx.Done():\n\t\t}\n\n\t\terr := <-errCh\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func initChannels(icmpPackets chan gopacket.Packet, ipsecESP chan gopacket.Packet) {\n\tipSecChannel = ipsecESP\n\ticmpChannel = icmpPackets\n}", "func (cm *ConnectionManager) closeAll(onlyReceiving bool) (chs []*channeltype.Serialization, err error) {\n\tcm.lock.Lock()\n\tdefer cm.lock.Unlock()\n\tcm.initChannelTarget = 0\n\tif onlyReceiving {\n\t\tchs = cm.receivingChannels()\n\t} else {\n\t\tchs = cm.openChannels()\n\t}\n\tfor _, c := range chs {\n\t\t_, err = cm.api.Close(cm.tokenAddress, c.PartnerAddress())\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"close channel %s error:%s\", c.ChannelIdentifier, err))\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (p *decoded) Channels() int {\n\treturn 2\n}", "func (h *clientHub) Channels() []string {\n\th.RLock()\n\tdefer h.RUnlock()\n\tchannels := make([]string, len(h.subs))\n\ti := 0\n\tfor ch := range h.subs {\n\t\tchannels[i] = ch\n\t\ti++\n\t}\n\treturn channels\n}", "func (s *Server) NewChannels(c map[string]ChannelInterface) {\n for k, v := range c {\n v.SetGM(s.GM)\n v.Open()\n s.Channels.Store(k, v)\n }\n}", "func (client *Client) Channels() []*Channel {\n\ttargets := client.Targets(\"channel\")\n\tchannels := make([]*Channel, len(targets))\n\n\tfor i := range targets {\n\t\tchannels[i] = targets[i].(*Channel)\n\t}\n\n\treturn channels\n}", "func (m *TeamItemRequestBuilder) IncomingChannels()(*i1e6cfda39bf71ff6c49bf501ccb56055e496f12dd4a459a4c9f832017b3ed495.IncomingChannelsRequestBuilder) {\n return i1e6cfda39bf71ff6c49bf501ccb56055e496f12dd4a459a4c9f832017b3ed495.NewIncomingChannelsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (n *Notifier) NotifyChannels() {\n\tif int(time.Now().Weekday()) == 6 || int(time.Now().Weekday()) == 0 {\n\t\treturn\n\t}\n\tchannels, err := n.db.GetChannels()\n\tif err != nil {\n\t\tlogrus.Errorf(\"notifier: ListAllStandupTime failed: %v\\n\", err)\n\t\treturn\n\t}\n\t// For each standup time, if standup time is now, start reminder\n\tfor _, channel := range channels {\n\t\tif channel.StandupTime == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tstandupTime := time.Unix(channel.StandupTime, 0)\n\t\twarningTime := time.Unix(channel.StandupTime-n.conf.ReminderTime*60, 0)\n\t\tif time.Now().Hour() == warningTime.Hour() && time.Now().Minute() == warningTime.Minute() {\n\t\t\tn.SendWarning(channel.ChannelID)\n\t\t}\n\t\tif time.Now().Hour() == standupTime.Hour() && time.Now().Minute() == standupTime.Minute() {\n\t\t\tgo n.SendChannelNotification(channel.ChannelID)\n\t\t}\n\t}\n}", "func (bot *ExchangeBot) UpdateChannels() *UpdateChannels {\n\tupdate := make(chan *UpdateSignal, 16)\n\tquit := make(chan struct{})\n\tbot.Lock()\n\tdefer bot.Unlock()\n\tbot.updateChans = append(bot.updateChans, update)\n\tbot.quitChans = append(bot.quitChans, quit)\n\treturn &UpdateChannels{\n\t\tUpdate: update,\n\t\tQuit: quit,\n\t}\n}", "func (vs *Viewers) Channels() []string {\n\tvs.lock.Lock()\n\tdefer vs.lock.Unlock()\n\tdefer util.TimeElapsed(time.Now(), \"Channels\")\n\n\tchannels := make([]string, 0)\n\tfor channel := range vs.views {\n\t\tchannels = append(channels, channel)\n\t}\n\treturn channels\n}", "func (o *ConnectorTypeAllOf) GetChannelsOk() (*[]string, bool) {\n\tif o == nil || o.Channels == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Channels, true\n}", "func (c *Client) Channels(guildID discord.GuildID) ([]discord.Channel, error) {\n\tvar chs []discord.Channel\n\treturn chs, c.RequestJSON(&chs, \"GET\", EndpointGuilds+guildID.String()+\"/channels\")\n}", "func (mf *MethodFrame) Channel() uint16 { return mf.ChannelID }", "func (o *ConnectorTypeAllOf) GetChannels() []string {\n\tif o == nil || o.Channels == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn *o.Channels\n}", "func (m *TeamItemRequestBuilder) AllChannels()(*ic08a09e622b3f3279dad3fb1dc0d9adf50886e9a08f52205e44e27965d46190a.AllChannelsRequestBuilder) {\n return ic08a09e622b3f3279dad3fb1dc0d9adf50886e9a08f52205e44e27965d46190a.NewAllChannelsRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func getChannels(channelNames []interface{}, prtgData *PRTGData) []map[string]float64 {\n\thistdata := prtgData.HistData\n\n\tchannelStream := make([]map[string]float64, 0)\n\n\tfor i := range histdata {\n\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\td := histdata[i].Fields\n\n\t\tchannelValues := make(map[string]float64)\n\n\t\tfor _, channelName := range channelNames {\n\t\t\tfor k, v := range d {\n\t\t\t\tk = strings.TrimSpace(k)\n\t\t\t\tif k == channelName {\n\t\t\t\t\tif channelValue, ok := v.(float64); ok {\n\t\t\t\t\t\tchannelValues[channelName.(string)] = channelValue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tchannelStream = append(channelStream, channelValues)\n\n\t}\n\n\treturn channelStream\n}", "func (nlcoord *NsqLookupCoordinator) GetRegisteredChannel(topic string) ([]string, error) {\n\ttopicMeta, _, err := nlcoord.leadership.GetTopicMetaInfo(topic)\n\tif err != nil {\n\t\tcoordLog.Infof(\"get topic key %v failed :%v\", topic, err)\n\t\treturn nil, err\n\t}\n\n\tvar registeredChannels []string\n\tregisteredChannelsMap := make(map[string]bool)\n\tfor i := 0; i < topicMeta.PartitionNum; i++ {\n\t\ttopicInfo, err := nlcoord.leadership.GetTopicInfo(topic, i)\n\t\tif err != nil {\n\t\t\tcoordLog.Infof(\"failed get info for topic : %v-%v, %v\", topic, i, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, ch := range topicInfo.Channels {\n\t\t\tregisteredChannelsMap[ch] = true\n\t\t}\n\t}\n\t//convert registered channels map back\n\tfor ch, _ := range registeredChannelsMap {\n\t\tchannelName := ch\n\t\tregisteredChannels = append(registeredChannels, channelName)\n\t}\n\n\treturn registeredChannels, nil\n}", "func (txs *TxServiceImpl) QueryChannels(targetPeer sdkApi.Peer) ([]string, error) {\n\tchannels, err := txs.FcClient.QueryChannels(targetPeer)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(errors.GeneralError, \"Error querying channels on %v: %s\", targetPeer, err)\n\t}\n\treturn channels, nil\n}", "func samplesToChannels(samples []float64, channelCount uint16) []Channel {\n\tchannels := make([]Channel, channelCount)\n\tchannelCount32 := uint32(channelCount)\n\tsize := len(samples)\n\tsize32 := uint32(size)\n\tsamplesPerChannel := size32 / channelCount32\n\n\t/*\n\t * Extract each channel from the sample data.\n\t */\n\tfor i := uint16(0); i < channelCount; i++ {\n\t\tcurrentSamples := make([]float64, samplesPerChannel)\n\t\ti32 := uint32(i)\n\n\t\t/*\n\t\t * Extract each sample for this channel.\n\t\t */\n\t\tfor j := uint32(0); j < samplesPerChannel; j++ {\n\t\t\tidx := (j * channelCount32) + i32\n\t\t\tcurrentSamples[j] = samples[idx]\n\t\t}\n\n\t\t/*\n\t\t * Data structure representing this channel.\n\t\t */\n\t\tchannel := channelStruct{\n\t\t\tsamples: currentSamples,\n\t\t}\n\n\t\tchannels[i] = &channel\n\t}\n\n\treturn channels\n}", "func (ec *executionContext) _Channel(ctx context.Context, sel []query.Selection, obj *model.Channel) graphql.Marshaler {\n\tfields := graphql.CollectFields(ec.Doc, sel, channelImplementors, ec.Variables)\n\n\tout := graphql.NewOrderedMap(len(fields))\n\tfor i, field := range fields {\n\t\tout.Keys[i] = field.Alias\n\n\t\tswitch field.Name {\n\t\tcase \"__typename\":\n\t\t\tout.Values[i] = graphql.MarshalString(\"Channel\")\n\t\tcase \"id\":\n\t\t\tout.Values[i] = ec._Channel_id(ctx, field, obj)\n\t\tcase \"name\":\n\t\t\tout.Values[i] = ec._Channel_name(ctx, field, obj)\n\t\tcase \"handle\":\n\t\t\tout.Values[i] = ec._Channel_handle(ctx, field, obj)\n\t\tcase \"isDefault\":\n\t\t\tout.Values[i] = ec._Channel_isDefault(ctx, field, obj)\n\t\tcase \"isPrivate\":\n\t\t\tout.Values[i] = ec._Channel_isPrivate(ctx, field, obj)\n\t\tdefault:\n\t\t\tpanic(\"unknown field \" + strconv.Quote(field.Name))\n\t\t}\n\t}\n\n\treturn out\n}", "func (c *Client) channelsList(ctx context.Context) ([]*channel, error) {\n\tvar resp struct {\n\t\tResponseHeader\n\t\tChannels []channel `json:\"channels\"`\n\t}\n\tif err := rpc(ctx, c, &resp, \"channels.list\"); err != nil {\n\t\treturn nil, err\n\t}\n\tchannels := make([]*channel, 0)\n\tfor _, ch := range resp.Channels {\n\t\tch := ch\n\t\tinitChannel(c, &ch)\n\t\tchannels = append(channels, &ch)\n\t}\n\treturn channels, nil\n}", "func (b *hereNowBuilder) Channels(ch []string) *hereNowBuilder {\n\tb.opts.Channels = ch\n\n\treturn b\n}", "func (n *Graph) channelByInPortAddr(addr address) (channel reflect.Value, found bool) {\n\tfor i := range n.inPorts {\n\t\tif n.inPorts[i].addr == addr {\n\t\t\treturn n.inPorts[i].channel, true\n\t\t}\n\t}\n\n\treturn reflect.Value{}, false\n}", "func (f *Filter) GetChannels(from, subject string) []string {\n\tfor _, r := range *f {\n\t\tif r.Match(from, subject) {\n\t\t\treturn r.Channels\n\t\t}\n\t}\n\treturn []string{\"\"}\n}", "func commands(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tfor command := range funcMap {\n\t\tmessage += command + \" \"\n\t}\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func (c *Component) Channels(ch map[string]ChannelInterface) {\n\tc.GM.Server.NewChannels(ch)\n}", "func InitChannel() {\n\tfor i := range raft.ClientHandlerChannel {\n\t\traft.ClientHandlerChannel[i] = make(chan raft.CommitInfo)\n\t}\n}", "func (s *ImageSpec) ChannelNames() []string {\n\tnames := make([]string, s.NumChannels())\n\tc_names := make([]*C.char, s.NumChannels())\n\tc_names_ptr := (**C.char)(unsafe.Pointer(&c_names[0]))\n\tC.ImageSpec_channelnames(s.ptr, c_names_ptr)\n\tfor i, c := range c_names {\n\t\tnames[i] = C.GoString(c)\n\t\tC.free(unsafe.Pointer(c))\n\t}\n\truntime.KeepAlive(s)\n\treturn names\n}", "func (g *GlobalChannels) GetChannels(api *slack.Client) {\n\tvar err error\n\n\tg.nameIndex = make(map[string]idxGrpChan)\n\tg.idIndex = make(map[string]idxGrpChan)\n\n\tg.Channels, err = api.GetChannels(true)\n\tif err != nil {\n\t\tlog.Printf(\"Error getting channels: %v\", err)\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(g.Channels); i++ {\n\t\tchannel := g.Channels[i]\n\t\t// log.Printf(\"Channel Name: %s, ID: %s, IsChannel: %t\\n\", channel.Name, channel.ID, channel.IsChannel)\n\t\tg.nameIndex[channel.Name] = idxGrpChan{t: \"c\", i: i}\n\t\tg.idIndex[channel.ID] = idxGrpChan{t: \"c\", i: i}\n\t}\n\n\tg.Groups, err = api.GetGroups(true)\n\tif err != nil {\n\t\tlog.Printf(\"Error getting groups: %v\", err)\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(g.Groups); i++ {\n\t\tgroup := g.Groups[i]\n\t\t// log.Printf(\"Group Name: %s, ID: %s, IsChannel: %t\\n\", group.Name, group.ID, false)\n\t\tg.nameIndex[group.Name] = idxGrpChan{t: \"g\", i: i}\n\t\tg.idIndex[group.ID] = idxGrpChan{t: \"g\", i: i}\n\t}\n\n\tg.IMs, err = api.GetIMChannels()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting IM channels: %v\", err)\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(g.IMs); i++ {\n\t\tim := g.IMs[i]\n\t\t// log.Printf(\"IM Name: %s, ID: %s, IsChannel: %t\\n\", im.User, im.ID, false)\n\t\tg.nameIndex[im.User] = idxGrpChan{t: \"d\", i: i}\n\t\tg.idIndex[im.ID] = idxGrpChan{t: \"d\", i: i}\n\t}\n\n}", "func (a *API) GetChannelsValues( /*ctx context.Context,*/ universe int, startAddr int, count int) (ChannelsValues, error) {\n\t// - `QLC+API|getChannelsValues|<universe>|<startAddr>|[<count>]`: Returns the channel values of a given `<universe>` (starting at one) beginning at given `<startAddr>` (starting at one) and returning one or given `<count>` channels\n\t// - answer: `QLC+API|getChannelsValues|[<channel>|<value>|<type>]...` with `<channel>` starting at one, value in range `[0,255]` and `<type>` the fixture type\n\n\t// lock API\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\n\t// Send message\n\terr := a.writeText([]byte(fmt.Sprintf(\"QLC+API|getChannelsValues|%d|%d|%d\", universe+1, startAddr+1, count)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Receive message\n\tmsg, err := a.receiveText()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal message\n\tparts := strings.Split(string(msg), \"|\")\n\tif len(parts) < 2 || (len(parts)-2)%3 != 0 {\n\t\treturn nil, errors.New(\"Invalid amount of parts\")\n\t}\n\tif parts[0] != \"QLC+API\" || parts[1] != \"getChannelsValues\" {\n\t\treturn nil, errors.New(\"Unexpected response\")\n\t}\n\n\tc := ChannelsValues{}\n\tfor i := 2; i < len(parts); i += 3 {\n\t\tAddr, err := strconv.Atoi(parts[i])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Failed to convert part #%d\", i)\n\t\t}\n\t\tValue, err := strconv.Atoi(parts[i+1])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Failed to convert part #%d\", i+1)\n\t\t}\n\n\t\tc = append(c, ChannelValue{Addr: Addr, Value: Value, Type: parts[i+2]})\n\t}\n\n\treturn c, nil\n}", "func (_TokensNetwork *TokensNetworkFilterer) FilterChannelOpenedAndDeposit(opts *bind.FilterOpts, token []common.Address) (*TokensNetworkChannelOpenedAndDepositIterator, error) {\n\n\tvar tokenRule []interface{}\n\tfor _, tokenItem := range token {\n\t\ttokenRule = append(tokenRule, tokenItem)\n\t}\n\n\tlogs, sub, err := _TokensNetwork.contract.FilterLogs(opts, \"ChannelOpenedAndDeposit\", tokenRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokensNetworkChannelOpenedAndDepositIterator{contract: _TokensNetwork.contract, event: \"ChannelOpenedAndDeposit\", logs: logs, sub: sub}, nil\n}", "func (s *SocketModeAdapter) GetPresentChannels() ([]*adapter.ChannelInfo, error) {\n\tallChannels, _, err := s.client.GetConversations(&slack.GetConversationsParameters{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannels := make([]*adapter.ChannelInfo, 0)\n\tfor _, ch := range allChannels {\n\t\t// Is this user in this channel?\n\t\tif ch.IsMember {\n\t\t\tchannels = append(channels, newChannelInfoFromSlackChannel(&ch))\n\t\t}\n\t}\n\n\treturn channels, nil\n}", "func (s *MemStorage) GetAllInChannel(channelID string) []Event {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tif events, ok := s.events[channelID]; ok {\n\t\treturn events\n\t}\n\treturn nil\n}", "func (o AlarmContactOutput) ChannelsAliim() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AlarmContact) pulumi.StringPtrOutput { return v.ChannelsAliim }).(pulumi.StringPtrOutput)\n}", "func (m *TeamItemRequestBuilder) IncomingChannelsById(id string)(*i986134cfb00ff93c88ffb51965b534e9da908849cf680fc5e4ff907a20066f7d.ChannelItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"channel%2Did\"] = id\n }\n return i986134cfb00ff93c88ffb51965b534e9da908849cf680fc5e4ff907a20066f7d.NewChannelItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func getChannelsOfKind(guildID string, s *discordgo.Session, kind string) []*discordgo.Channel {\n\tguild, err := s.State.Guild(guildID)\n\tchannels := []*discordgo.Channel{}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn channels\n\t}\n\tfor _, c := range guild.Channels {\n\t\tif c.Type == kind {\n\t\t\tchannels = append(channels, c)\n\t\t}\n\t}\n\treturn channels\n}", "func (r *serviceRegistry) GetAllServiceChannels() []string {\n\tservices := make([]string, 0)\n\tfor chanName, _ := range r.services {\n\t\t// do not return internal services like fabric-rest\n\t\tif isInternal, found := internalServices[chanName]; !isInternal || !found {\n\t\t\tservices = append(services, chanName)\n\t\t}\n\t}\n\treturn services\n}", "func inquireAMQPChannelAttributes(objectPatternsList string, infoMap map[string]*ObjInfo) error {\n\tvar err error\n\n\ttraceEntry(\"inquireAMQPChannelAttributes\")\n\n\tci := getConnection(GetConnectionKey())\n\tstatusClearReplyQ()\n\n\tif objectPatternsList == \"\" {\n\t\ttraceExitErr(\"inquireAMQPChannelAttributes\", 1, err)\n\t\treturn err\n\t}\n\n\tobjectPatterns := strings.Split(strings.TrimSpace(objectPatternsList), \",\")\n\tfor i := 0; i < len(objectPatterns) && err == nil; i++ {\n\t\tvar buf []byte\n\t\tpattern := strings.TrimSpace(objectPatterns[i])\n\t\tif len(pattern) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tputmqmd, pmo, cfh, buf := statusSetCommandHeaders()\n\n\t\t// Can allow all the other fields to default\n\t\tcfh.Command = ibmmq.MQCMD_INQUIRE_CHANNEL\n\t\tcfh.ParameterCount = 0\n\n\t\t// Add the parameters one at a time into a buffer\n\t\tpcfparm := new(ibmmq.PCFParameter)\n\t\tpcfparm.Type = ibmmq.MQCFT_STRING\n\t\tpcfparm.Parameter = ibmmq.MQCACH_CHANNEL_NAME\n\t\tpcfparm.String = []string{pattern}\n\t\tcfh.ParameterCount++\n\t\tbuf = append(buf, pcfparm.Bytes()...)\n\n\t\tpcfparm = new(ibmmq.PCFParameter)\n\t\tpcfparm.Type = ibmmq.MQCFT_INTEGER\n\t\tpcfparm.Parameter = ibmmq.MQIACH_CHANNEL_TYPE\n\t\tpcfparm.Int64Value = []int64{int64(ibmmq.MQCHT_AMQP)}\n\t\tcfh.ParameterCount++\n\t\tbuf = append(buf, pcfparm.Bytes()...)\n\n\t\tpcfparm = new(ibmmq.PCFParameter)\n\t\tpcfparm.Type = ibmmq.MQCFT_INTEGER_LIST\n\t\tpcfparm.Parameter = ibmmq.MQIACF_CHANNEL_ATTRS\n\t\tpcfparm.Int64Value = []int64{int64(ibmmq.MQIACH_MAX_INSTANCES), int64(ibmmq.MQIACH_MAX_INSTS_PER_CLIENT), int64(ibmmq.MQCACH_DESC), int64(ibmmq.MQIACH_CHANNEL_TYPE)}\n\t\tcfh.ParameterCount++\n\t\tbuf = append(buf, pcfparm.Bytes()...)\n\n\t\t// Once we know the total number of parameters, put the\n\t\t// CFH header on the front of the buffer.\n\t\tbuf = append(cfh.Bytes(), buf...)\n\n\t\t// And now put the command to the queue\n\t\terr = ci.si.cmdQObj.Put(putmqmd, pmo, buf)\n\t\tif err != nil {\n\t\t\ttraceExitErr(\"inquireAMQPChannelAttributes\", 2, err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor allReceived := false; !allReceived; {\n\t\t\tcfh, buf, allReceived, err = statusGetReply(putmqmd.MsgId)\n\t\t\tif buf != nil {\n\t\t\t\tparseAMQPChannelAttrData(cfh, buf, infoMap)\n\t\t\t}\n\t\t}\n\t}\n\n\ttraceExit(\"inquireAMQPChannelAttributes\", 0)\n\treturn nil\n}", "func getChannelsIfPresent(events []provider.RelayerEvent) []zapcore.Field {\n\tchannelTags := []string{srcChanTag, dstChanTag}\n\tfields := []zap.Field{}\n\n\t// While a transaction may have multiple messages, we just need to first\n\t// pair of channels\n\tfoundTag := map[string]struct{}{}\n\n\tfor _, event := range events {\n\t\tfor _, tag := range channelTags {\n\t\t\tfor attributeKey, attributeValue := range event.Attributes {\n\t\t\t\tif attributeKey == tag {\n\t\t\t\t\t// Only append the tag once\n\t\t\t\t\t// TODO: what if they are different?\n\t\t\t\t\tif _, ok := foundTag[tag]; !ok {\n\t\t\t\t\t\tfields = append(fields, zap.String(tag, attributeValue))\n\t\t\t\t\t\tfoundTag[tag] = struct{}{}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn fields\n}", "func (m *Mixer) Channels() ChannelConf {\n\treturn ChannelConf(C.al_get_mixer_channels((*C.ALLEGRO_MIXER)(m)))\n}", "func buildChannelFilterQuery(channels []string) []elastic.Query {\n\tfilters := make([]elastic.Query, len(channels))\n\tfor i := range channels {\n\t\tfilters[i] = elastic.NewMatchQuery(\"channel\", channels[i])\n\t}\n\treturn filters\n}", "func (_WandappETH *WandappETHCaller) GetChannelInfo(opts *bind.CallOpts, user common.Address) (*big.Int, *big.Int, *big.Int, *big.Int, uint64, uint64, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t\tret3 = new(*big.Int)\n\t\tret4 = new(uint64)\n\t\tret5 = new(uint64)\n\t\tret6 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t\tret5,\n\t\tret6,\n\t}\n\terr := _WandappETH.contract.Call(opts, out, \"getChannelInfo\", user)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, *ret5, *ret6, err\n}", "func Channels() []string {\n\treturn db.Redis().SMembers(PusherChannelSetKey).Val()\n}", "func (q channelQuery) All(ctx context.Context, exec boil.ContextExecutor) (ChannelSlice, error) {\n\tvar o []*Channel\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 Channel slice\")\n\t}\n\n\tif len(channelAfterSelectHooks) != 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 *connectedPlayer) knownChannels() sets.String {\n\tp.pluginChannelsMu.RLock()\n\tdefer p.pluginChannelsMu.RUnlock()\n\treturn p.pluginChannels\n}", "func (b *presenceBuilder) Channels(ch []string) *presenceBuilder {\n\tb.opts.channels = ch\n\n\treturn b\n}", "func (pxd pixelData) MultiChannelCircles(dest string, index int) error {\n\n rgbChannels := []RGBChannel {cs.red, cs.blue, cs.green}\n\n err := pxd.pixelLooper(func(pxAddr chan pxAddress) {\n\n for pxa := range pxAddr {\n\n row := float64(pxa.row)\n col := float64(pxa.column)\n mult := float64(pxd.blockSize)\n\n // Assign RGB values\n rgb := []float64{\n pxa.pixelWand.GetRed(), \n pxa.pixelWand.GetGreen(), \n pxa.pixelWand.GetBlue(), \n }\n\n for idx, channel := range rgbChannels {\n\n // Calculate how large each cirlce should be\n circleSize := mult / (rgb[idx] * 255 / 255 * 15 + 3)\n\n pxd.wands.pw.SetColor(channel.fill)\n // TODO\n // pxd.wands.dw.SetStrokeWidth(0)\n // pxd.wands.dw.SetStrokeColor(channel.stroke)\n pxd.wands.pw.SetOpacity(channel.opacity)\n pxd.wands.dw.SetFillColor(pxd.wands.pw)\n\n ox := float64(col*mult + channel.offset)\n oy := float64(row*mult + channel.offset)\n px := ox-float64(circleSize)\n py := oy-float64(circleSize)\n\n pxd.wands.dw.Circle(ox,oy,px,py)\n }\n }\n }, dest)\n\n return err\n}", "func (s *TestSuite) TestGetChannels(c *C) {\n\tsvc := s.serviceGroup.UserService\n\tteam, _ := s.serviceGroup.TeamService.SaveTeam(msgcore.NewTeam(1, \"org\", \"team\"))\n\n\tusers := make([]*msgcore.User, 0, 0)\n\tchannels := make([]*msgcore.Channel, 0, 0)\n\tfor i := 1; i <= 10; i++ {\n\t\tcreator := msgcore.NewUser(int64(i), fmt.Sprintf(\"%d\", i), team)\n\t\t_ = svc.SaveUser(&msgcore.SaveUserRequest{nil, creator, false})\n\t\tusers = append(users, creator)\n\t\tchannel := msgcore.NewChannel(team, creator, int64(i), fmt.Sprintf(\"channel%d\", i))\n\t\tchannel, err := s.serviceGroup.ChannelService.CreateChannel(&msgcore.CreateChannelRequest{channel, nil, true})\n\t\tif err != nil {\n\t\t\tlog.Println(\"CreateChannel Error: \", err)\n\t\t}\n\t\tchannels = append(channels, channel)\n\t}\n\n\tfor i := 1; i <= 10; i++ {\n\t\t// add the creator and 4 next users as members\n\t\tmembers := make([]string, 0, 4)\n\t\tfor j := 0; j < 5; j++ {\n\t\t\tmembers = append(members, users[(i+j-1)%len(users)].Username)\n\t\t}\n\t\ts.serviceGroup.ChannelService.AddChannelMembers(&msgcore.InviteMembersRequest{nil, channels[i-1], members})\n\t}\n\n\t// Test owner filter\n\trequest := &msgcore.GetChannelsRequest{team, users[0], \"\", nil, true}\n\tresult, _ := s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 1)\n\tc.Assert(len(result.Members), Equals, 1)\n\t// ensure all users have the same creator\n\tc.Assert(result.Channels[0].Creator.Id, Equals, users[0].Id)\n\tc.Assert(len(result.Members[0]), Equals, 5)\n\n\t// Test participants\n\trequest = &msgcore.GetChannelsRequest{team, nil, \"\", []*msgcore.User{users[1], users[2]}, true}\n\tresult, _ = s.serviceGroup.ChannelService.GetChannels(request)\n\tc.Assert(len(result.Channels), Equals, 4)\n\tfor i := 0; i < 4; i++ {\n\t\tc.Assert(len(result.Members[i]), Equals, 5)\n\t}\n}", "func (b *Bot) loadChannels() (map[string]string, error) {\n\tvar err error\n\tvar cursor string\n\tvar chunkedChannels []slack.Channel\n\n\tchannels := make(map[string]string)\n\n\t// in CLI context we don't have to channels\n\tif b.config.Slack.IsFakeServer() {\n\t\treturn channels, nil\n\t}\n\n\tfor {\n\t\toptions := &slack.GetConversationsParameters{\n\t\t\tLimit: 1000,\n\t\t\tCursor: cursor,\n\t\t\tExcludeArchived: true,\n\t\t}\n\n\t\tchunkedChannels, cursor, err = b.slackClient.GetConversations(options)\n\t\tif err != nil {\n\t\t\treturn channels, err\n\t\t}\n\t\tfor _, channel := range chunkedChannels {\n\t\t\tchannels[channel.ID] = channel.Name\n\t\t}\n\t\tif cursor == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn channels, nil\n}", "func (s *p4RuntimeServer) StreamChannel(stream p4.P4Runtime_StreamChannelServer) error {\n\tfmt.Println(\"Starting bi-directional channel\")\n\tfor {\n\t\tinData, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Printf(\"%v\", inData)\n\t}\n\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkCaller) GetChannelInfo(opts *bind.CallOpts, token common.Address, participant1 common.Address, participant2 common.Address) ([32]byte, uint64, uint64, uint8, uint64, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t\tret1 = new(uint64)\n\t\tret2 = new(uint64)\n\t\tret3 = new(uint8)\n\t\tret4 = new(uint64)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t\tret3,\n\t\tret4,\n\t}\n\terr := _TokensNetwork.contract.Call(opts, out, \"getChannelInfo\", token, participant1, participant2)\n\treturn *ret0, *ret1, *ret2, *ret3, *ret4, err\n}", "func ParseChannel(in <-chan *Raw, out chan<- *Message) {\n\tfor rm := range in {\n\t\tm, err := Parse(rm.Origin, rm.Data)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to parse message: %q. error - %v\\n\", rm.Data, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tout <- m\n\t}\n}", "func ws_MessageLoop(messages chan string, receive_channel ReceiveChannel) {\n\n\tfor {\n\t\tmsg := <-messages\n\t\tlog.Printf(\"[%s] MESSAGE !!! \", __FILE__)\n\t\trcv := Command{}\n\t\tjson.Unmarshal([]byte(msg), &rcv)\n\t\tlog.Printf(rcv.Cmd)\n\n\t\tswitch rcv.Cmd {\n\t\tcase \"connected\":\n\t\t\tlog.Printf(\"[%s] connected succefully~~\", __FILE__)\n\t\tcase \"GetContainersInfo\":\n\t\t\treceive_channel.containers <- true\n\t\tcase \"UpdateImage\":\n\t\t\tlog.Printf(\"[%s] command <UpdateImage>\", __FILE__)\n\t\t\tupdate_msg, r := parseUpdateParam(msg)\n\t\t\tif r == nil {\n\t\t\t\treceive_channel.updateinfo <- update_msg\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[%s] UpdateImage message null !!!\")\n\t\t\t}\n\t\tcase \"err\":\n\t\t\tlog.Printf(\"[%s] Error Case in connection need to recovery\", __FILE__)\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[%s] add command of {%s}\", __FILE__, rcv.Cmd)\n\t\t}\n\n\t}\n}", "func testChannel(t *testing.T, src, dst *Chain) {\n\tchans, err := src.QueryChannels(1, 1000)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(chans))\n\trequire.Equal(t, chans[0].GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, chans[0].GetState().String(), \"OPEN\")\n\trequire.Equal(t, chans[0].GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, chans[0].GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n\n\th, err := src.Client.Status()\n\trequire.NoError(t, err)\n\n\tch, err := src.QueryChannel(h.SyncInfo.LatestBlockHeight)\n\trequire.NoError(t, err)\n\trequire.Equal(t, ch.Channel.GetOrdering().String(), \"ORDERED\")\n\trequire.Equal(t, ch.Channel.GetState().String(), \"OPEN\")\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetChannelID(), dst.PathEnd.ChannelID)\n\trequire.Equal(t, ch.Channel.GetCounterparty().GetPortID(), dst.PathEnd.PortID)\n}", "func Channels(chs int) Option {\n\treturn func(args *Options) {\n\t\targs.Channels = chs\n\t}\n}", "func (c Client) GetChannels(lineupURI string) (*ChannelResponse, error) {\n\turl := fmt.Sprint(DefaultBaseURL, lineupURI)\n\tfmt.Println(\"URL:>\", url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"token\", c.Token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Fatal(resp.Status)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n\n\t// make the map\n\th := new(ChannelResponse)\n\n // debug code\t\n //body, _ := ioutil.ReadAll(resp.Body)\n\t//fmt.Println(string(body))\n\n\t// decode the body into the map\n\terr = json.NewDecoder(resp.Body).Decode(&h)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing channel response line\")\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\treturn h, nil\n}", "func (host *DinnerHost) AskChannels() (chan string, chan string) {\n\treturn host.requestChannel, host.finishChannel\n}", "func (s *SlackService) GetChannels() []Channel {\n\tvar chans []Channel\n\n\t// Channel\n\tslackChans, err := s.Client.GetChannels(true)\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, chn := range slackChans {\n // fmt.Println(chn.Name)\n if chn.Name == \"time\" {\n s.SlackChannels = append(s.SlackChannels, chn)\n chans = append(chans, Channel{chn.ID, chn.Name, chn.Topic.Value})\n }\n\t}\n\n // Just return after finding a specific channel\n s.Channels = chans\n return chans\n\n // Uncomment this to see all the channels\n // os.Exit(1)\n\n\t// Groups\n\tslackGroups, err := s.Client.GetGroups(true)\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, grp := range slackGroups {\n\t\ts.SlackChannels = append(s.SlackChannels, grp)\n\t\tchans = append(chans, Channel{grp.ID, grp.Name, grp.Topic.Value})\n\t}\n\n\t// IM\n\tslackIM, err := s.Client.GetIMChannels()\n\tif err != nil {\n\t\tchans = append(chans, Channel{})\n\t}\n\tfor _, im := range slackIM {\n\n\t\t// Uncover name, when we can't uncover name for\n\t\t// IM channel this is then probably a deleted\n\t\t// user, because we wont add deleted users\n\t\t// to the UserCache, so we skip it\n\t\tname, ok := s.UserCache[im.User]\n\t\tif ok {\n\t\t\tchans = append(chans, Channel{im.ID, name, \"\"})\n\t\t\ts.SlackChannels = append(s.SlackChannels, im)\n\t\t}\n\t}\n\n\ts.Channels = chans\n\n\treturn chans\n}", "func Channels(mods ...qm.QueryMod) channelQuery {\n\tmods = append(mods, qm.From(\"\\\"channels\\\"\"))\n\treturn channelQuery{NewQuery(mods...)}\n}", "func (c *ChanDirectionChecker) biDirChanParams(fn *ast.FuncDecl) []*ast.Field {\n\tparams := fn.Type.Params.List\n\tvar biDirChans []*ast.Field\n\tfor _, param := range params {\n\t\tt, ok := param.Type.(*ast.ChanType) // If not a chan type we ignore it\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif t.Dir != biDirectionalChan {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(param.Names) == 0 { // unnamed chan param\n\t\t\tcontinue\n\t\t}\n\n\t\tbiDirChans = append(biDirChans, param)\n\t}\n\n\treturn biDirChans\n}", "func (c *IrcBot) connected() irc.HandlerFunc {\n return func(conn *irc.Conn, line *irc.Line) {\n for _,channel := range c.channels {\n c.connection.Join(channel)\n }\n }\n}", "func (n *Notifier) NotifyChannels() {\n\tif int(time.Now().Weekday()) == 6 || int(time.Now().Weekday()) == 0 {\n\t\tlogrus.Info(\"It is Weekend!!! No standups!!!\")\n\t\treturn\n\t}\n\tstandupTimes, err := n.DB.ListAllStandupTime()\n\tif err != nil {\n\t\tlogrus.Errorf(\"notifier: ListAllStandupTime failed: %v\\n\", err)\n\t\treturn\n\t}\n\t// For each standup time, if standup time is now, start reminder\n\tfor _, st := range standupTimes {\n\t\tstandupTime := time.Unix(st.Time, 0)\n\t\twarningTime := time.Unix(st.Time-n.Config.ReminderTime*60, 0)\n\t\tif time.Now().Hour() == warningTime.Hour() && time.Now().Minute() == warningTime.Minute() {\n\t\t\tn.SendWarning(st.ChannelID)\n\t\t}\n\t\tif time.Now().Hour() == standupTime.Hour() && time.Now().Minute() == standupTime.Minute() {\n\t\t\tgo n.SendChannelNotification(st.ChannelID)\n\t\t}\n\t}\n}", "func (p *RelPublisher) registerChannels() {\n\tdcdChan := make(chan DcdRnd, 64)\n\tp.dcdChan = dcdChan\n\tp.dmx.RegisterChannel(dcdChan)\n}", "func (c *Channel) Channels() Channels {\n\treturn c.children\n}", "func channelsIntersect(visibleChannels ch.TimedSet, channels []interface{}) bool {\n\tfor _, channel := range channels {\n\t\tif visibleChannels.Contains(channel.(string)) || channel == \"*\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (l *listener) run(ch <-chan interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ch:\n\t\t\t\tif msg == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// remove threading guarantees when mulitplexing into channels\n\t\t\t\tlog.Printf(\"listener raw: %#v\", msg)\n\t\t\t\tswitch msg.(type) {\n\t\t\t\tcase error:\n\t\t\t\t\tl.errors <- msg.(error)\n\t\t\t\tcase *bitfinex.Ticker:\n\t\t\t\t\tl.ticks <- msg.(*bitfinex.Ticker)\n\t\t\t\tcase *websocket.InfoEvent:\n\t\t\t\t\tl.infoEvents <- msg.(*websocket.InfoEvent)\n\t\t\t\tcase *websocket.SubscribeEvent:\n\t\t\t\t\tl.subscriptionEvents <- msg.(*websocket.SubscribeEvent)\n\t\t\t\tcase *websocket.UnsubscribeEvent:\n\t\t\t\t\tl.unsubscriptionEvents <- msg.(*websocket.UnsubscribeEvent)\n\t\t\t\tcase *websocket.AuthEvent:\n\t\t\t\t\tl.authEvents <- msg.(*websocket.AuthEvent)\n\t\t\t\tcase *bitfinex.WalletUpdate:\n\t\t\t\t\tl.walletUpdates <- msg.(*bitfinex.WalletUpdate)\n\t\t\t\tcase *bitfinex.BalanceUpdate:\n\t\t\t\t\tl.balanceUpdates <- msg.(*bitfinex.BalanceUpdate)\n\t\t\t\tcase *bitfinex.Notification:\n\t\t\t\t\tl.notifications <- msg.(*bitfinex.Notification)\n\t\t\t\tcase *bitfinex.TradeExecutionUpdate:\n\t\t\t\t\tl.tradeUpdates <- msg.(*bitfinex.TradeExecutionUpdate)\n\t\t\t\tcase *bitfinex.TradeExecution:\n\t\t\t\t\tl.tradeExecutions <- msg.(*bitfinex.TradeExecution)\n\t\t\t\tcase *bitfinex.PositionUpdate:\n\t\t\t\t\tl.positions <- msg.(*bitfinex.PositionUpdate)\n\t\t\t\tcase *bitfinex.OrderCancel:\n\t\t\t\t\tl.cancels <- msg.(*bitfinex.OrderCancel)\n\t\t\t\tcase *bitfinex.MarginInfoBase:\n\t\t\t\t\tl.marginBase <- msg.(*bitfinex.MarginInfoBase)\n\t\t\t\tcase *bitfinex.MarginInfoUpdate:\n\t\t\t\t\tl.marginUpdate <- msg.(*bitfinex.MarginInfoUpdate)\n\t\t\t\tcase *bitfinex.OrderNew:\n\t\t\t\t\tl.orderNew <- msg.(*bitfinex.OrderNew)\n\t\t\t\tcase *bitfinex.FundingInfo:\n\t\t\t\t\tl.funding <- msg.(*bitfinex.FundingInfo)\n\t\t\t\tcase *bitfinex.PositionSnapshot:\n\t\t\t\t\tl.positionSnapshot <- msg.(*bitfinex.PositionSnapshot)\n\t\t\t\tcase *bitfinex.WalletSnapshot:\n\t\t\t\t\tl.walletSnapshot <- msg.(*bitfinex.WalletSnapshot)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}", "func handleChannelRequests(\n\treqs <-chan *ssh.Request,\n\tc ssh.Channel,\n\tinfo string,\n) {\n\tfor r := range reqs {\n\t\tgo handleRequest(\n\t\t\tr,\n\t\t\tfunc( /* Ugh, a closure */\n\t\t\t\tname string,\n\t\t\t\twantReply bool,\n\t\t\t\tpayload []byte,\n\t\t\t) (bool, []byte, error) {\n\t\t\t\tb, e := c.SendRequest(name, wantReply, payload)\n\t\t\t\treturn b, nil, e\n\t\t\t},\n\t\t\tfunc() error { return c.Close() }, /* Another? */\n\t\t\tinfo,\n\t\t)\n\t}\n}", "func (_obj *Apichannels) Channels_getFullChannel(params *TLchannels_getFullChannel, _opt ...map[string]string) (ret Messages_ChatFull, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_getFullChannel\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (info TrackInfo) NChannels() int {\n\t// bit 28 - 1 = stereo audio; 0 = mono audio\n\tif info&0x10000000 != 0 {\n\t\t// stero audio.\n\t\treturn 2\n\t}\n\t// mono audio.\n\treturn 1\n}", "func CFList(phy *band.Band, channels ...*ttnpb.MACParameters_Channel) *ttnpb.CFList {\n\tif !phy.ImplementsCFList {\n\t\treturn nil\n\t}\n\n\tswitch phy.CFListType {\n\tcase ttnpb.CFListType_CHANNEL_MASKS:\n\t\treturn chMaskCFList(phy, channels...)\n\tcase ttnpb.CFListType_FREQUENCIES:\n\t\treturn frequenciesCFList(phy, channels...)\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (r *RecordStream) Channels() int {\n\treturn int(r.createReply.Channels)\n}", "func (this *fileStruct) ChannelCount() uint16 {\n\tn := len(this.channels)\n\tn16 := uint16(n)\n\treturn n16\n}", "func ChanFsInfoSSlice(inp ...[]fs.FsInfoS) (out <-chan fs.FsInfoS) {\n\tcha := make(chan fs.FsInfoS)\n\tgo sendFsInfoSSlice(cha, inp...)\n\treturn cha\n}", "func handlerChannelStates(wr http.ResponseWriter, req *http.Request) {\n\tweblib.WriteResponse(wr, se.AllChannelStates(), nil)\n}", "func handleServerChannels(t *testing.T, ctx context.Context, wg *sync.WaitGroup, sshCn ssh.Conn, chans <-chan ssh.NewChannel) {\n\tdefer wg.Done()\n\tfor nc := range chans {\n\t\tif nc.ChannelType() != \"direct-tcpip\" {\n\t\t\tnc.Reject(ssh.UnknownChannelType, \"not implemented\")\n\t\t\tcontinue\n\t\t}\n\t\tvar args struct {\n\t\t\tDstHost string\n\t\t\tDstPort uint32\n\t\t\tSrcHost string\n\t\t\tSrcPort uint32\n\t\t}\n\t\tif !unmarshalData(nc.ExtraData(), &args) {\n\t\t\tnc.Reject(ssh.Prohibited, \"invalid request\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Open a connection for both sides.\n\t\tcn, err := net.Dial(\"tcp\", net.JoinHostPort(args.DstHost, strconv.Itoa(int(args.DstPort))))\n\t\tif err != nil {\n\t\t\tnc.Reject(ssh.ConnectionFailed, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tch, reqs, err := nc.Accept()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"accept channel error: %v\", err)\n\t\t\tcn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tgo ssh.DiscardRequests(reqs)\n\n\t\twg.Add(1)\n\t\tgo bidirCopyAndClose(t, ctx, wg, cn, ch)\n\t}\n}", "func (o *Channels) GetChannelsOk() (*[]Channel, bool) {\n\tif o == nil || o.Channels == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Channels, true\n}", "func (o *ConnectorTypeAllOf) HasChannels() bool {\n\tif o != nil && o.Channels != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (_e *MockDataCoord_Expecter) WatchChannels(ctx interface{}, req interface{}) *MockDataCoord_WatchChannels_Call {\n\treturn &MockDataCoord_WatchChannels_Call{Call: _e.mock.On(\"WatchChannels\", ctx, req)}\n}" ]
[ "0.59246016", "0.58601475", "0.5738874", "0.5678419", "0.56488675", "0.561803", "0.55692255", "0.55614203", "0.5532338", "0.54174966", "0.5414731", "0.5362655", "0.5323363", "0.528319", "0.52456826", "0.5197814", "0.5194817", "0.51875466", "0.5176433", "0.5154607", "0.5154348", "0.51470566", "0.5138192", "0.5119886", "0.5115105", "0.51149493", "0.5102179", "0.509413", "0.507765", "0.50570065", "0.50542194", "0.50518674", "0.5040423", "0.5040302", "0.5040283", "0.502079", "0.5014944", "0.501411", "0.5009413", "0.5003674", "0.49970067", "0.49846885", "0.49819717", "0.4972928", "0.4960691", "0.4955926", "0.49512637", "0.49463677", "0.49154463", "0.489187", "0.48783877", "0.48746145", "0.48603496", "0.48598439", "0.48570412", "0.48500666", "0.48499942", "0.48485968", "0.484855", "0.48480123", "0.48452082", "0.48342624", "0.48341864", "0.48279512", "0.48276845", "0.48276636", "0.48256084", "0.4824022", "0.48150957", "0.48098874", "0.4804399", "0.4803817", "0.48037234", "0.47916445", "0.4787585", "0.47858423", "0.47851202", "0.4782414", "0.47809124", "0.47765967", "0.4770854", "0.47622558", "0.4758469", "0.47583288", "0.47537273", "0.47527006", "0.47499982", "0.4735389", "0.47319105", "0.47273976", "0.47230536", "0.471851", "0.47175458", "0.47153145", "0.4712899", "0.47113964", "0.47080383", "0.47073784", "0.47072455", "0.47037917" ]
0.7096321
0
Splash draws a message in the center of the screen that can be dismissed with the escape key
func Splash(title, text string) { sw, sh := termbox.Size() lines := strings.Split(text, "\n") h := len(lines) w := 10 for _, l := range lines { if len(l) > w { w = len(l) + 4 } } bg := termbox.ColorCyan fg := termbox.ColorBlack xPos := sw/2 - w/2 yPos := sh/2 - h/2 - 2 Clear(xPos, yPos, xPos+w, yPos+h+1, fg, bg) for i, line := range lines { DrawText(xPos+2, yPos+1+i, line, fg, bg) } termbox.Flush() for { switch input.ReadKeyEvent() { case input.KeyEnter, input.KeyEscape, ' ': return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func splash() {\n\tfmt.Print(`\n ________ ________ .____ _____ __________ _____ \n / _____/ \\_____ \\ | | / _ \\\\______ \\ / _ \\ \n/ \\ ___ / | \\| | / /_\\ \\| _/ / /_\\ \\ \n\\ \\_\\ \\/ | \\ |___/ | \\ | \\/ | \\\n \\______ /\\_______ /_______ \\____|__ /____|_ /\\____|__ /\n \\/ \\/ \\/ \\/ \\/ \\/ \n`)\n}", "func displayWelcomeMessage() {\n\tart :=\n\t\t` \t\n================================================================================================ \n ___ __ __ _ _ ___ ___ __ ___ __ ___ __ ___ ___ \n| | |__ | / ' / \\ | \\/ | |__ | / \\ |\\ | |__ / \\ /__ / \\ |__ | \n|/\\| |___ |___\\__, \\__/ | | |___ | \\__/ | \\| |___ \\__/ ___/ \\__/ | | \n\n================================================================================================= \n\t \n\t\n\t`\n\tfmt.Println(art)\n\tquitMessage := \"\\nPress Ctrl + C to stop the tracker..\"\n\tfmt.Println(quitMessage)\n\n}", "func (s *Splasher) splash(cmd *exec.Cmd) (sp *Splash, err error) {\n\t// Exec\n\tsp = &Splash{cmd: cmd}\n\tastilog.Debugf(\"Executing %s\", strings.Join(cmd.Args, \" \"))\n\tif err = sp.cmd.Start(); err != nil {\n\t\terr = errors.Wrapf(err, \"starting %s failed\", s.binaryPath)\n\t}\n\n\t// Wait\n\tgo cmd.Wait()\n\treturn\n}", "func (s *Splasher) Splash(src string, width, height int) (*Splash, error) {\n\treturn s.splash(exec.Command(s.binaryPath, \"-b\"+src, \"-w\"+strconv.Itoa(width), \"-h\"+strconv.Itoa(height)))\n}", "func DrawWelcome() {\n\tfmt.Println(`\n\t\t\t____. .___ __________ .___ \n\t\t\t| | ____ __ _____ ___ __| _/_ __ \\______ \\ ____ ____ __| _/_ __ \n\t\t\t| |/ __ \\| | \\ \\/ / / __ | | \\ | ___// __ \\ / \\ / __ | | \\\n\t\t/\\__| \\ ___/| | /> < / /_/ | | / | | \\ ___/| | \\/ /_/ | | /\n\t\t\\________|\\___ >____//__/\\_ \\ \\____ |____/ |____| \\___ >___| /\\____ |____/ \n\t\t\t\t\t\\/ \\/ \\/ \\/ \\/ \\/ \n\t`)\n}", "func DefeatScreen(con tcod.Console) {\n\tif i := tinput.NewInput(); i.Check() == tinput.EvKeyPress &&\n\t\ti.GetVk() == tinput.KeyEnter {\n\t\tUpdateFunc = TitleScreen\n\t\treturn\n\t}\n\tcon.PrintEx(con.GetW()/2, con.GetH()/2,\n\t\ttcod.BgNone, tcod.AlignCenter, \"Defeated!\")\n}", "func imgTopReleaseEvent() {\n\tAbout.Width = 400\n\tAbout.ImageOkButtonSize = 24\n\tAbout.Show()\n}", "func (win *winInfo) displayLoading() {\n\ttexture, _ := win.renderText(\"Loading...\")\n\tww, wh := win.window.GetSize()\n\twin.renderer.Copy(texture, nil, &sdl.Rect{X: int32(ww/2 - 50), Y: int32(wh/2 - 1), W: 65, H: 20})\n\ttexture.Destroy()\n\twin.renderer.Present()\n}", "func PanicMessage(msg string, err error) {\n\tmodal := dom.GetDocument().GetElementById(\"modal-panic\")\n\tjs.Global().Get(\"UIkit\").Call(\"modal\", modal.JSValue()).Call(\"show\")\n\twaquery.AddStyle(\".uk-modal * { opacity: 1; }\")\n\tmodal.AddEventListener(\"shown\", func(e dom.Event) {\n\t\tfmt.Printf(\"[FRAME PANIC] %s\\n\", msg)\n\t\tpanic(err)\n\t})\n\ttime.Sleep(time.Second)\n\tfmt.Printf(\"[FRAME PANIC] %s\\n\", msg)\n\tpanic(err)\n}", "func PAUSE() { ctx.PAUSE() }", "func ClearScreen() {\n\temitEscape(\"J\", 2)\n}", "func (s *start) Draw() {\n\ts.frameCounter++\n\tif s.frameCounter < 10 {\n\t\ts.r.Copy(s.t1, nil, &sdl.Rect{X: s.tx, Y: s.ty, W: s.tw, H: s.th})\n\t} else {\n\t\ts.r.Copy(s.t2, nil, &sdl.Rect{X: s.tx, Y: s.ty, W: s.tw, H: s.th})\n\t}\n\tif s.frameCounter > 20 {\n\t\ts.frameCounter = 0\n\t}\n\n\tmaxX, maxY, _ := s.r.GetRendererOutputSize()\n\n\ttitle, _ := s.titleFont.RenderUTF8_Solid(\n\t\t\"lil' e invaders\",\n\t\tsdl.Color{R: 0xF6, G: 0x25, B: 0x9B, A: 0},\n\t)\n\tdefer title.Free()\n\n\tinfo, _ := s.infoFont.RenderUTF8_Solid(\n\t\t\"PRESS ENTER TO START\",\n\t\tsdl.Color{R: 0xF6, G: 0x25, B: 0x9B, A: 0},\n\t)\n\tdefer info.Free()\n\n\tvar clipRect sdl.Rect\n\ttitle.GetClipRect(&clipRect)\n\tinfo.GetClipRect(&clipRect)\n\n\ttitleTex, _ := s.r.CreateTextureFromSurface(title)\n\tinfoTex, _ := s.r.CreateTextureFromSurface(info)\n\n\ts.r.Copy(\n\t\ttitleTex,\n\t\tnil,\n\t\t&sdl.Rect{\n\t\t\tX: int32(maxX)/2 - title.W/2,\n\t\t\tY: int32(maxY) - 250,\n\t\t\tW: title.W,\n\t\t\tH: title.H,\n\t\t},\n\t)\n\n\ts.r.Copy(\n\t\tinfoTex,\n\t\tnil,\n\t\t&sdl.Rect{\n\t\t\tX: int32(maxX)/2 - info.W/2,\n\t\t\tY: int32(maxY) - 120,\n\t\t\tW: info.W,\n\t\t\tH: info.H,\n\t\t},\n\t)\n}", "func ClearScreenPartialBackward() {\n\temitEscape(\"J\", 1)\n}", "func Outro(name string) {\n ClearScreen()\n fmt.Printf(\"\\n\\n\")\n TypedText(name+\" walks through the door into a long tunnel.\\n\", 80)\n time.Sleep(500 * time.Millisecond)\n TypedText(\"\\n\\nAfter walking what seems like an eternity \"+name+ \" approaches a ladder.\\n\", 80)\n time.Sleep(500 * time.Millisecond)\n TypedText(\"\\n\\nTrudging up the ladder step by step \"+name+\" comes face to face with an iron plate.\\n\", 80)\n time.Sleep(500 * time.Millisecond)\n TypedText(\"\\n\\nBestowing all inner strength \"+name+\" lifts the iron plate and is hit with bright light and a breath of fresh air.\\n\", 80)\n time.Sleep(500 * time.Millisecond)\n fmt.Printf(\"\\n\")\n TypedText(name+\" has escaped.\\n\", 80)\n time.Sleep(2 * time.Second)\n}", "func ClearScreenPartialForward() {\n\temitEscape(\"J\")\n}", "func clearScreen() {\n\tfmt.Print(\"\\x1b[2J\")\n}", "func pause() {\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Print(\"Press 'ENTER' key to return to the menu... \")\n\t//bufio.NewReader(os.Stdin).ReadBytes('\\n')\n\treader.ReadString('\\n')\n}", "func (f *FFmpeg_Generator) ValidateSplash() {\n\tvar splashFinder splash.Splash\n\ttmpSplash, status := splashFinder.FindSplash(f.Recipe.Splash)\n\tf.Error.Status = !status\n\tf.Error.Message = \"splash file error\"\n\tf.Splash = &tmpSplash\n}", "func printLogo() {\n\tif *flagNoLogo {\n\t\treturn\n\t}\n\tfmt.Println(\" ██████╗██╗ ███╗ ██╗██████╗\")\n\tfmt.Println(\"██╔════╝██║ ████╗ ██║██╔══██╗\")\n\tfmt.Println(\"██║ ██║ ██╔██╗ ██║██║ ██║\")\n\tfmt.Println(\"██║ ██║ ██║╚██╗██║██║ ██║\")\n\tfmt.Println(\"╚██████╗███████╗██║ ╚████║██████╔╝\")\n\tfmt.Println(\" ╚═════╝╚══════╝╚═╝ ╚═══╝╚═════╝ Cleaned\")\n\tfmt.Println(\"\")\n}", "func printLogo() {\n\tfmt.Println(\" ______ _ _____ _____ \")\n\tfmt.Println(\" / ____/ (_)__ ____ / /_ / ____/ __ /\")\n\tfmt.Println(\" / / / / / _ / __ / __/ / / __/ / / /\")\n\tfmt.Println(\" / /___/ / / __/ / / / /_ / /_/ / /_/ / \")\n\tfmt.Println(\"/_____/_/_/____/_/ /_/ __/ _____/ ____/ \")\n\tfmt.Println(\"\")\n}", "func ExitWithMessage(msg string) {\n\tcolor.Set(color.FgRed)\n\tfmt.Printf(msg)\n\tcolor.Unset()\n\tos.Exit(1)\n}", "func (f *FFmpeg_Generator) FitSplash() {\n\tvar splashMediaInfo mediainfo.MediaInfoStruct\n\terr := splashMediaInfo.GetVideoInfo(f.Dir + \"splash-file\")\n\tif err != nil {\n\t\tf.Error.Status = err == nil\n\t\tf.Error.Message = \"mediaInfo splash error\"\n\t\treturn\n\t}\n\tsplashCorrectionOperation := []string{\n\t\t\"-i\",\n\t\tf.Dir + \"splash-file\",\n\t\t\"-f\",\n\t\t\"lavfi\",\n\t\t\"-i\",\n\t\tfmt.Sprintf(\"color=red:s=%dx%d\", MakeEvenNumber(f.Frame.Width), MakeEvenNumber(f.Frame.Height)),\n\t\t\"-filter_complex\",\n\t\tfmt.Sprintf(\"[1]scale=%d:-1[inner];[inner][0]overlay=%d:0:shortest=1[out]\", MakeEvenNumber(f.Frame.Width), MakeEvenNumber((f.Frame.Width-int(splashMediaInfo.Width))/2)),\n\t\t\"-map\",\n\t\t\"[out]:v\",\n\t\t\"-map\",\n\t\t\"0:a\",\n\t\tf.Dir + \"splash.final.mp4\",\n\t}\n\terr = Execute(splashCorrectionOperation...)\n\tif err != nil {\n\t\tf.Error.Status = err == nil\n\t\tf.Error.Message = \"mediaInfo splash error\"\n\t}\n}", "func DoPin(message string) (bool, string, error) {\n\tvar dontFlash bool\n\t{\n\t\tflashEnv, found := os.LookupEnv(\"TREZOR_ENCRYPT_NOFLASH\")\n\t\tif found {\n\t\t\tdontFlash = flashEnv == \"1\"\n\t\t} else {\n\t\t\tdontFlash = false\n\t\t}\n\t}\n\n\tvalue := \"\"\n\t_done := false\n\n\tbuttons := make(map[int32]*gtk.Button)\n\tclearId := int32(1)\n\n\tgtk.Init(nil)\n\t{\n\t\tprovider, err := gtk.CssProviderNew()\n\t\tprovider.LoadFromData(\n\t\t\t\".pinkey { border: 1.5px solid black; border-radius: 0.3em; background: transparent; } \" +\n\t\t\t\t\".flash { background: #3F7FBF; } \" +\n\t\t\t\t\".top { padding: 0.5em; border: none; } \")\n\t\tscreen, err := gdk.ScreenGetDefault()\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tgtk.AddProviderForScreen(screen, provider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n\t}\n\twin, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\tflash := func(buttonId int32) {\n\t\tif dontFlash {\n\t\t\treturn\n\t\t}\n\t\tstyle, err := buttons[buttonId].GetStyleContext()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tstyle.AddClass(\"flash\")\n\t\tglib.TimeoutAdd(100, func() bool {\n\t\t\tstyle, err := buttons[buttonId].GetStyleContext()\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tstyle.RemoveClass(\"flash\")\n\t\t\treturn false\n\t\t})\n\t}\n\n\tcancel := func() {\n\t\twin.Hide()\n\t\tgtk.MainQuit()\n\t}\n\n\tdone := func() {\n\t\t_done = true\n\t\twin.Hide()\n\t\tgtk.MainQuit()\n\t}\n\n\tclear := func() {\n\t\tvalue = \"\"\n\t\tflash(clearId)\n\t}\n\n\tentry := func(letter int32) {\n\t\tvalue = value + string(letter)\n\t\tflash(letter)\n\t}\n\n\tmain, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, space)\n\tif err != nil {\n\t\treturn false, \"\", err\n\t}\n\n\t{\n\t\tlabel, err := gtk.LabelNew(message)\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tlabel.SetLineWrap(true)\n\t\tlabel.SetMaxWidthChars(50)\n\t\tmain.PackStart(label, false, false, 0)\n\t}\n\n\t{\n\t\tgrid, err := gtk.GridNew()\n\t\tgrid.SetColumnSpacing(5)\n\t\tgrid.SetRowSpacing(5)\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tfor i, v := range \"789456123\" {\n\t\t\tbutton, err := gtk.ButtonNew()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tbuttons[v] = button\n\t\t\tv2 := v\n\t\t\tbutton.Connect(\"clicked\", func() {\n\t\t\t\tentry(v2)\n\t\t\t})\n\t\t\tstyle, err := button.GetStyleContext()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tstyle.AddClass(\"pinkey\")\n\t\t\tcol := i % 3\n\t\t\trow := int(i / 3)\n\t\t\tgrid.Attach(button, col, row, 1, 1)\n\t\t}\n\t\tgrid.SetHAlign(gtk.ALIGN_CENTER)\n\t\tmain.PackStart(grid, true, false, 0)\n\t}\n\n\t{\n\t\tactions, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, space)\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\t{\n\t\t\tbutton, err := gtk.ButtonNew()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tbutton.SetLabel(\"Done\")\n\t\t\tactions.PackStart(button, false, false, 0)\n\t\t\tbutton.Connect(\"clicked\", done)\n\t\t}\n\t\t{\n\t\t\tbutton, err := gtk.ButtonNew()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tbutton.SetLabel(\"Clear\")\n\t\t\tactions.PackStart(button, false, false, 0)\n\t\t\tbutton.Connect(\"clicked\", clear)\n\t\t\tbuttons[clearId] = button\n\t\t}\n\t\t{\n\t\t\tbutton, err := gtk.ButtonNew()\n\t\t\tif err != nil {\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t\tbutton.SetLabel(\"Cancel\")\n\t\t\tactions.PackStart(button, false, false, 0)\n\t\t\tbutton.Connect(\"clicked\", cancel)\n\t\t}\n\t\tactions.SetHAlign(gtk.ALIGN_CENTER)\n\t\tmain.PackStart(actions, false, false, 0)\n\t}\n\n\t{\n\t\twin.SetTitle(\"Trezor PIN Entry\")\n\t\twin.Connect(\"destroy\", cancel)\n\t\twin.Connect(\"key-press-event\", func(win *gtk.Window, ev *gdk.Event) {\n\t\t\tkeyEvent := &gdk.EventKey{ev}\n\t\t\tif keyEvent.KeyVal() == gdk.KEY_Return {\n\t\t\t\tdone()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif keyEvent.KeyVal() == gdk.KEY_BackSpace {\n\t\t\t\tclear()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif keyEvent.KeyVal() == gdk.KEY_Escape {\n\t\t\t\tcancel()\n\t\t\t\treturn\n\t\t\t}\n\t\t\textraKeysets := []string{\"xcvsdfwer\", \"m,.jkluio\"}\n\t\t\tfor _, keyset := range append([]string{\"123456789\"}, extraKeysets...) {\n\t\t\t\tfor i, k := range keyset {\n\t\t\t\t\tif k == gdk.KeyvalToUnicode(keyEvent.KeyVal()) {\n\t\t\t\t\t\tentry(int32('1' + i))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\tframe, err := gtk.FrameNew(\"\")\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tstyle, err := frame.GetStyleContext()\n\t\tif err != nil {\n\t\t\treturn false, \"\", err\n\t\t}\n\t\tstyle.AddClass(\"top\")\n\t\tframe.SetShadowType(gtk.SHADOW_NONE)\n\t\tframe.Add(main)\n\n\t\twin.Add(frame)\n\t\twin.ShowAll()\n\t}\n\tgtk.Main()\n\n\treturn _done, value, nil\n}", "func onLaunch() {\n\tmenu := &Menu{}\n\n\tapp.MenuBar().Mount(menu)\n\tapp.Dock().Mount(menu)\n\n\tmainWindow = newWelcomeWindow()\n}", "func (sh *stmHelper) printMessage(msg string) (err error) {\n\terr = sh.ClearDisplay()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sh.PrintText(0, 0, stm.Foreground, msg)\n}", "func showSpinner() {\n\tfor { // while true\n\t\tfor _, r := range `⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏` {\n\t\t\tfmt.Printf(\"\\r%c %s\", r, \"Calculating colors\")\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t}\n\t}\n}", "func ScrSave() {\n PrintCtrOnErr(ESC_SAVE_SCREEN)\n PrintCtrOnErr(ESC_SAVE_CURSOR)\n PrintCtrOnErr(ESC_CURSOR_OFF)\n PrintCtrOnErr(ESC_CLEAR_SCREEN)\n}", "func ScrRestore() {\n PrintCtrOnErr(ESC_CURSOR_ON)\n PrintCtrOnErr(ESC_RESTORE_CURSOR)\n PrintCtrOnErr(ESC_RESTORE_SCREEN)\n}", "func Title(){\n fmt.Printf(\"\\n\\n\\n\\n\\n\")\n\n fmt.Printf(\" ████████╗██╗ ██╗███████╗ ███████╗███████╗██╗ ██╗███████╗██████╗\\n\")\n fmt.Printf(\" ╚══██╔══╝██║ ██║██╔════╝ ██╔════╝██╔════╝██║ ██║██╔════╝██╔══██╗\\n\")\n fmt.Printf(\" ██║ ███████║█████╗ ███████╗█████╗ ██║ █╗ ██║█████╗ ██████╔╝\\n\")\n fmt.Printf(\" ██║ ██╔══██║██╔══╝ ╚════██║██╔══╝ ██║███╗██║██╔══╝ ██╔══██╗\\n\")\n fmt.Printf(\" ██║ ██║ ██║███████╗ ███████║███████╗╚███╔███╔╝███████╗██║ ██║\\n\")\n fmt.Printf(\" ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚══════╝╚══════╝ ╚══╝╚══╝ ╚══════╝╚═╝ ╚═╝\\n\")\n\n\n}", "func DisplayMessage(msg string) {\n\tcolor.Set(color.FgRed)\n\tfmt.Println(msg)\n\tcolor.Unset()\n}", "func (s *scene) present() {\n\tscreen := s.win.Screen()\n\tctx := gfx.NewContext(screen)\n\n\tctx.SetColorRGBA(0, 0, 0, 255)\n\tctx.Clear()\n\n\t// Paint background and frame:\n\tctx.SetColorRGBA(100, 100, 100, 255)\n\tctx.Rectangle(0, 0, s.e.w, s.e.h)\n\n\t// Paint balls:\n\tctx.SetColorRGBA(200, 80, 0, 255)\n\tfor _, b := range s.e.balls {\n\t\ts.paintBall(ctx, b)\n\t}\n\n\ts.paintOSD(ctx)\n\n\ts.paintGravity(ctx)\n\n\ts.win.FlushImage()\n}", "func displayInstructions(s tcell.Screen) {\n emitStr(s, 2, 2, tcell.StyleDefault, \"Press f/b to go to next/previous stretches\")\n emitStr(s, 2, 3, tcell.StyleDefault, \"Press p to toggle pause\")\n emitStr(s, 2, 4, tcell.StyleDefault, \"Press ESC exit\")\n return\n}", "func outerloop(screen *ebiten.Image) error {\r\n\r\n //screen.Fill(color.NRGBA{0xff, 0xff, 128, 0xff}) // \r\n screen.Fill(color.NRGBA{154, 158, 5, 0xff}) \r\n\r\n if ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) &&\r\n mouseReleased {\r\n mx, my := ebiten.CursorPosition()\r\n mouseReleased = false\r\n if Button_Click(mx,my) == startButtonCode {\r\n fmt.Printf(\"click button\\n\")\r\n //mode = modeGameScreen\r\n //MG_Init()\r\n buttonRunTimer.set(buttonRunTimer.kButtonStart,30) // 60 is 1 seconds\\\r\n \r\n } else if Button_Click(mx,my) == quitButtonCode {\r\n buttonQuitTimer.set(buttonRunTimer.kButtonStart,30)\r\n }\r\n } else if ! ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\r\n mouseReleased = true\r\n }\r\n\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyQ) {\r\n \texitProgram()\r\n }\r\n \r\n Button_Draw(screen)\r\n\r\n // timers are to allow the user to see the button press animation\r\n buttonRunTimer.inc()\r\n if buttonRunTimer.check() {\r\n fmt.Printf(\"buttonRunTimer execcute!\\n\")\r\n buttonRunTimer.reset()\r\n mode = modeGameScreen\r\n MG_Init()\r\n \r\n }\r\n\r\n buttonQuitTimer.inc()\r\n if buttonQuitTimer.check() {\r\n fmt.Printf(\"quit execcute!\\n\")\r\n buttonQuitTimer.reset() // unnecessary but for consistency\r\n exitProgram()\r\n }\r\n\r\n\t//digitsDraw(screen)\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyJ) && PushKeyOnce(\"J\") {\r\n fmt.Print(\"key J\\n\")\r\n //PushKeyOnce(\"J\")\r\n }\r\n if ebiten.IsKeyPressed(ebiten.KeyU) && PushKeyOnce(\"U\") {\r\n fmt.Print(\"key U\\n\")\r\n //PushKeyOnce(\"U\")\r\n }\r\n ebitenutil.DebugPrint(screen, \"Memory Game \\nin Ebiten\\n\")\r\n return nil\r\n}", "func APC20Splash(out *portmidi.Stream) error {\n\trand.Seed(time.Now().UnixNano())\n\tgreenOrder, orangeOrder, redOrder := rand.Perm(40), rand.Perm(40), rand.Perm(40)\n\tgreenSplit, orangeSplit, redSplit := int64(rand.Intn(40)), int64(rand.Intn(40)), int64(rand.Intn(40))\n\n\t// Down GREEN\n\tfor i := int64(0); i < greenSplit; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(greenOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, midiInfo.Data2); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\n\t// Down ORANGE\n\tfor i := int64(0); i < orangeSplit; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(orangeOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, 5); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\n\t// Down RED\n\tfor i := int64(0); i < redSplit; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(redOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, 3); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfor i := orangeSplit; i < 40; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(orangeOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, 5); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\n\tfor i := greenSplit; i < 40; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(greenOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, midiInfo.Data2); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(20 * time.Millisecond)\n\t}\n\tfor i := redSplit; i < 40; i++ {\n\t\tmidiInfo := apc20.IntToMidiMessageDown[int64(redOrder[i])]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, 3); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\t// Up\n\tfor _, i := range rand.Perm(40) {\n\t\tmidiInfo := apc20.IntToMidiMessageUp[int64(i)]\n\t\tif err := out.WriteShort(midiInfo.Status, midiInfo.Data1, midiInfo.Data2); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not write short to midi device\")\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\ttime.Sleep(100 * time.Millisecond)\n\treturn nil\n}", "func Quit() {\n\tscreen.Fini()\n}", "func (p *PlayScreen) Enter() {\n\tif p.gameStart {\n\t\tp.world.AddMap(NewRandomMap(100, 100, true, \"Mines\"))\n\t\tp.world.SetMap(\"Mines\")\n\t}\n\tp.DefaultScene.Enter()\n}", "func (ec *ExecutionContext) Spin(message string) {\n\tif ec.IsTerminal {\n\t\tec.Spinner.Stop()\n\t\tec.Spinner.Prefix = message\n\t\tec.Spinner.Start()\n\t} else {\n\t\tec.Logger.Println(message)\n\t}\n}", "func (ts *Titlescreen) Tick(event tl.Event) {\n\tif event.Type == tl.EventKey {\n\t\tswitch event.Key {\n\t\tcase tl.KeyEnter:\n\t\t\tgs = NewGameScreen()\n\t\t\tgame.Screen().SetLevel(gs)\n\t\t}\n\t}\n}", "func ExitAltScreen() {\n\tfmt.Print(CSI + ExitAltScreenSeq)\n}", "func errorScreen(s string, conf config.UIConfig) ui.Drawable {\n\terrstyle := conf.GetStyle(config.STYLE_ERROR)\n\ttext := ui.NewText(s, errstyle).Strategy(ui.TEXT_CENTER)\n\tgrid := ui.NewGrid().Rows([]ui.GridSpec{\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t\t{ui.SIZE_EXACT, ui.Const(1)},\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t}).Columns([]ui.GridSpec{\n\t\t{ui.SIZE_WEIGHT, ui.Const(1)},\n\t})\n\tgrid.AddChild(ui.NewFill(' ')).At(0, 0)\n\tgrid.AddChild(text).At(1, 0)\n\tgrid.AddChild(ui.NewFill(' ')).At(2, 0)\n\treturn grid\n}", "func (p *PlayScreen) Render() {\n\tp.displayMessages()\n\tp.drawMap(p.world.CurMap, NewPoint(0, 0))\n\tBorder(p.stats, \"Stats\")\n\tBorder(p.info, \"Info\")\n\tBorder(p.skls, \"Skills\")\n\n}", "func (w *ScreenWriter) Display(message string) error {\n\terr := w.clearPrevious()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.previousMessage = message\n\n\t_, err = w.writer.WriteString(message)\n\treturn err\n}", "func QuitGame() {\n\t// Close the termbox\n\ttermbox.Close()\n\n\t// Display message to player\n\tfmt.Println(\"Thanks for playing!!\")\n\n\t// Close program without error\n\tos.Exit(0)\n}", "func GuiFade(alpha float32) {\n\tC.GuiFade(C.float(alpha))\n}", "func printBanner() {\n\tfmt.Print(\"\\033[31m\")\n\tfmt.Print(` \nd8b \nY8P \n \n888 88888b. .d88b. \n888 888 \"88b d8P Y8b \n888 888 888 88888888 \n888 888 d88P Y8b. \n888 88888P\" \"Y8888 \n 888 \n 888 \n 888 \n`)\n\tfmt.Println(\"\\033[0m\")\n}", "func MoveTopLeft() {\n\tfmt.Print(\"\\033[H\")\n}", "func (g *Game) Update(screen *ebiten.Image) error {\n\tif ebiten.IsKeyPressed(ebiten.KeyEscape) {\n\t\tos.Exit(0)\n\t}\n\treturn nil\n}", "func (this *MiniCon) ClearScreen() {\n\tthis.box.Clear()\n\tthis.pending.clear()\n\tthis.teletype.Clear()\n\tthis.hardlines = Hardlines{}\n\tthis.padding = 0\n}", "func ShakeScreen(dur time.Duration) {\n\tDefShaker.Shake(dur)\n}", "func (s *Spinner) FinishWithMessage(symbol, closingMessage string) error {\n\tif err := s.Stop(); err != nil {\n\t\treturn err\n\t}\n\ts.Reset()\n\tpreviousLen := len(s.previousFrame)\n\tfinalMsg := fmt.Sprintf(\"%s %s\", symbol, closingMessage)\n\tnewLen := len(finalMsg)\n\tif previousLen > newLen {\n\t\tr := previousLen - newLen\n\t\tsuffix := strings.Repeat(\" \", r)\n\t\tfinalMsg = finalMsg + suffix\n\t}\n\tfmt.Fprintf(s.Writer, \"%s%s\\n\", s.separator, finalMsg)\n\treturn nil\n}", "func Scaffold() {\n\t_, screenY := Screen.Size()\n\n\tShowCharacterInCenter(textart.Tux)\n\n\tBox(infoBoxPosX, infoBoxPosY, infoBoxPosX+infoBoxSizeX, infoBoxPosY+infoBoxSizeY, \" STATS \")\n\tPrintLine(screenY-BottomLineHeight, '─', false)\n\tPrintString(\">\", 0, InputLineNumber)\n}", "func StartupMessages(msgs *AppMessages) {\n\tfmt.Println(msgs.startMsg)\n\tfmt.Println(msgs.escapeMsg)\n\tfmt.Println(msgs.spaceMsg)\n}", "func (app *App) FatalBox(msg interface{}) {\n\tapp.ErrorBox(msg)\n\tos.Exit(1)\n}", "func ShowCharacterInCenter(character []string) {\n\n\tif ClearCurrentCharacter != nil {\n\t\tClearCurrentCharacter()\n\t}\n\n\tLongestCharacterSection = tools.FindLongestStringLen(character)\n\tCharacterXPos, CharacterYPos = FindTopLeftCoord(character, LongestCharacterSection)\n\n\tPrintTransparentMultiString(character, CharacterXPos, CharacterYPos)\n\n\tClearCurrentCharacter = MakeClearFunction(character, CharacterXPos, CharacterYPos)\n}", "func (ws *WindowSurface) Quit() {\n\tws.running = false\n}", "func TermMessage(msg ...interface{}) {\n\tscreenb := TempFini()\n\n\tfmt.Println(msg...)\n\tfmt.Print(\"\\nPress enter to continue\")\n\n\treader := bufio.NewReader(os.Stdin)\n\treader.ReadString('\\n')\n\n\tTempStart(screenb)\n}", "func TestCompletionEntry_Escape(t *testing.T) {\n\tentry := createEntry()\n\twin := test.NewWindow(entry)\n\twin.Resize(fyne.NewSize(500, 300))\n\tdefer win.Close()\n\n\tentry.SetText(\"init\")\n\n\twin.Canvas().Focused().TypedKey(&fyne.KeyEvent{Name: fyne.KeyDown})\n\twin.Canvas().Focused().TypedKey(&fyne.KeyEvent{Name: fyne.KeyEscape})\n\n\tassert.False(t, entry.popupMenu.Visible())\n}", "func (eg *endgameScreen) Tick(event term.Event) {\n\tif event.Type == term.EventKey { // Is it a keyboard event?\n\t\tif event.Key == term.KeyEnter {\n\t\t\tscore = 0\n\t\t\tgame.Screen().SetLevel(newMainLevel(isFullscreen))\n\t\t}\n\t}\n}", "func MainLoop(fullScreen bool, slideshow bool) int {\n\tvar event sdl.Event\n\tvar src, dst sdl.Rect\n\tvar err error\n\tvar flags uint32 = sdl.WINDOW_SHOWN | sdl.WINDOW_RESIZABLE | sdl.WINDOW_ALLOW_HIGHDPI\n\n\t// Load the font library\n\tif err := ttf.Init(); err != nil {\n\t\tlogger.Warning(\"Unable to open font lib\")\n\t}\n\n\twindow.window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winDefaultHeight, winDefaultWidth, flags)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to create window: %s\\n\", err)\n\t\treturn 1\n\t}\n\tdefer window.window.Destroy()\n\n\t// Load resources\n\tif f, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {\n\t\ticon := filepath.Join(f, \"app\", \"icon.bmp\")\n\t\tif i, err := sdl.LoadBMP(icon); err == nil {\n\t\t\twindow.window.SetIcon(i)\n\t\t}\n\n\t\tfont := filepath.Join(f, \"app\", \"fonts\", \"opensans.ttf\")\n\t\twindow.font, err = ttf.OpenFont(font, 14)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"Unable to load \" + font)\n\t\t}\n\t\twindow.font.SetKerning(false)\n\n\t\tfont = filepath.Join(f, \"app\", \"fonts\", \"fontawesome.ttf\")\n\t\twindow.symbols, err = ttf.OpenFont(font, 64)\n\t\tif err != nil {\n\t\t\tlogger.Warning(\"Unable to load \" + font)\n\t\t}\n\t}\n\n\twindow.renderer, err = sdl.CreateRenderer(window.window, -1, sdl.RENDERER_ACCELERATED)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to create renderer: %s\\n\", err)\n\t\treturn 2\n\t}\n\tdefer window.renderer.Destroy()\n\n\twindow.displayInfo = false\n\twindow.displayLoading()\n\twindow.setTitle(slide.current+1, len(slide.list), curImg().path)\n\twindow.loadCurrentImage(false)\n\n\t// Declare if the image needs to be updated\n\tvar update = false\n\tvar running = true\n\n\tfor running {\n\t\tevent = sdl.WaitEvent()\n\t\tswitch t := event.(type) {\n\t\tcase *sdl.QuitEvent:\n\t\t\trunning = false\n\n\t\tcase *sdl.DropEvent:\n\t\t\tfileName := t.File\n\n\t\t\t// Check if picture already in list\n\t\t\tfound := false\n\t\t\tfor i := range slide.list {\n\t\t\t\tif slide.list[i].path == fileName {\n\t\t\t\t\tfound = true\n\t\t\t\t\tslide.current = i\n\t\t\t\t\tupdate = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tif err := addPic(fileName); err != nil {\n\t\t\t\t\tsdl.ShowSimpleMessageBox(sdl.MESSAGEBOX_INFORMATION, \"File dropped on window\", \"Cannot add \"+fileName, window.window)\n\t\t\t\t} else {\n\t\t\t\t\tslide.current = len(slide.list) - 1\n\t\t\t\t\tupdate = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t/*case *sdl.MouseMotionEvent:\n\t\t\tfmt.Printf(\"[%d ms] MouseMotion\\ttype:%d\\tid:%d\\tx:%d\\ty:%d\\txrel:%d\\tyrel:%d\\n\",\n\t\t\t\tt.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel)\n\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\tfmt.Printf(\"[%d ms] MouseButton\\ttype:%d\\tid:%d\\tx:%d\\ty:%d\\tbutton:%d\\tstate:%d\\n\",\n\t\t\t\tt.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State)*/\n\n\t\tcase *sdl.WindowEvent:\n\t\t\tif t.Event == sdl.WINDOWEVENT_RESIZED || t.Event == sdl.WINDOWEVENT_EXPOSED {\n\t\t\t\twindow.window.SetSize(t.Data1, t.Data2)\n\n\t\t\t\t// Display information of the image\n\t\t\t\twWidth, wHeight := window.window.GetSize()\n\n\t\t\t\tsrc = sdl.Rect{X: 0, Y: 0, W: curImg().W, H: curImg().H}\n\t\t\t\tfitWidth, fitHeight := utils.ComputeFitImage(uint32(wWidth), uint32(wHeight), uint32(curImg().W), uint32(curImg().H))\n\t\t\t\tdst = sdl.Rect{X: int32(wWidth/2 - int32(fitWidth)/2), Y: int32(wHeight/2 - int32(fitHeight)/2), W: int32(fitWidth), H: int32(fitHeight)}\n\n\t\t\t\twindow.renderer.Clear()\n\t\t\t\twindow.renderer.Copy(curImg().texture, &src, &dst)\n\t\t\t\twindow.renderer.Present()\n\n\t\t\t\tif window.displayInfo {\n\t\t\t\t\twindow.displayPictureInfo()\n\t\t\t\t\twindow.renderer.Present()\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *sdl.KeyboardEvent:\n\n\t\t\tif t.GetType() != sdl.KEYDOWN {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Get next or previous image\n\t\t\tif t.Repeat == 0 {\n\t\t\t\tif t.Keysym.Sym == sdl.K_LEFT {\n\t\t\t\t\tslide.current = utils.Mod((slide.current - 1), len(slide.list))\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_RIGHT {\n\t\t\t\t\tslide.current = utils.Mod((slide.current + 1), len(slide.list))\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_PAGEUP {\n\t\t\t\t\tif err := picture.RotateImage(curImg().path, picture.CounterClockwise); err != nil {\n\t\t\t\t\t\tlogger.Warning(err.Error())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresetImg(slide.current)\n\t\t\t\t\t}\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_PAGEDOWN {\n\t\t\t\t\tif err := picture.RotateImage(curImg().path, picture.Clockwise); err != nil {\n\t\t\t\t\t\tlogger.Warning(err.Error())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresetImg(slide.current)\n\t\t\t\t\t}\n\t\t\t\t\tupdate = true\n\t\t\t\t} else if t.Keysym.Sym == 102 { // F\n\n\t\t\t\t\tif window.fullscreen {\n\t\t\t\t\t\twindow.window.SetFullscreen(0)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Go fullscreen\n\t\t\t\t\t\twindow.window.SetFullscreen(sdl.WINDOW_FULLSCREEN_DESKTOP)\n\t\t\t\t\t}\n\t\t\t\t\twindow.fullscreen = !window.fullscreen\n\t\t\t\t} else if t.Keysym.Sym == 105 { // I\n\n\t\t\t\t\twindow.displayInfo = !window.displayInfo\n\t\t\t\t\tif window.displayInfo {\n\t\t\t\t\t\tfmt.Println(\"Toggle info: on\")\n\t\t\t\t\t\twindow.displayPictureInfo()\n\t\t\t\t\t\twindow.renderer.Present()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(\"Toggle info: off\")\n\t\t\t\t\t\tupdate = true\n\t\t\t\t\t}\n\n\t\t\t\t} else if t.Keysym.Sym == sdl.K_ESCAPE {\n\n\t\t\t\t\tif window.fullscreen {\n\t\t\t\t\t\twindow.window.SetFullscreen(0)\n\t\t\t\t\t\twindow.fullscreen = false\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%d\\n\", t.Keysym.Sym)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif update {\n\t\t\twindow.loadCurrentImage(true)\n\t\t\tupdate = false\n\t\t}\n\t}\n\n\treturn 0\n}", "func GuiLock() {\n\tC.GuiLock()\n}", "func ClearScreen() {\n\tfmt.Printf(CSI+EraseDisplaySeq, 2)\n\tMoveCursor(1, 1)\n}", "func AltScreen() {\n\tfmt.Print(CSI + AltScreenSeq)\n}", "func draw() {\n\tw, h := termbox.Size() // Get width/height\n\ttermbox.Clear(termbox.ColorDefault, termbox.ColorDefault) // Clear\n\t// For whole screen, draw random colored block\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\ttermbox.SetCell(x, y, ' ', termbox.ColorDefault,\n\t\t\t\ttermbox.Attribute(rand.Int()%8)+1)\n\t\t}\n\t}\n\ttermbox.Flush()\n}", "func (h *Hud) EndGame(screen *ebiten.Image) { //method that checks the end of the game and the display\n\n\tif h.eatedCherrys != h.maxPoints {\n\t\tgoText := \"GAME OVER\"\n\t\ttextW, textH := textDimension(goText)\n\t\tscreenW := screen.Bounds().Dx()\n\t\tscreenH := screen.Bounds().Dy()\n\n\t\ttext.Draw(screen, goText, basicfont.Face7x13, screenW/2-textW/2, screenH/2+textH/2, color.White)\n\t} else if h.points == h.highestScore {\n\t\tgoText := \"YOU WIN!!\"\n\t\ttextW, textH := textDimension(goText)\n\t\tscreenW := screen.Bounds().Dx()\n\t\tscreenH := screen.Bounds().Dy()\n\n\t\ttext.Draw(screen, goText, basicfont.Face7x13, screenW/2-textW/2, screenH/2+textH/2, color.White)\n\t} else {\n\t\tgoText := \"GAME OVER\"\n\t\ttextW, textH := textDimension(goText)\n\t\tscreenW := screen.Bounds().Dx()\n\t\tscreenH := screen.Bounds().Dy()\n\n\t\ttext.Draw(screen, goText, basicfont.Face7x13, screenW/2-textW/2, screenH/2+textH/2, color.White)\n\t}\n}", "func (ptr *Application) onClickMenuAboutNotepad() {\n\tptr.setCurrentMsgBox(MsgBoxAboutNotepad)\n}", "func (s *EmptyScene) Exit() {\n}", "func InitUI(c *processor.Console) {\n\tconsole = c\n\tframe = image.NewRGBA(image.Rect(0, 0, width, height))\n\n\t// Call ebiten.Run to start your game loop.\n\tif err := ebiten.Run(update, width, height, scale, title); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (msg *ErrorMsg) Draw(x int, s tcell.Screen) int {\n\t_, h := s.Size()\n\ty := h - 2\n\n\tif len(msg.text) > 0 && time.Since(msg.ts) >= errDisplayTimeout {\n\t\t// clear error message\n\t\tfor i := x; i <= msg.width; i++ {\n\t\t\ts.SetCell(i, y, styles.Error, ' ')\n\t\t}\n\t\tmsg.text = \"\"\n\t} else {\n\t\tfor n, ch := range msg.text {\n\t\t\tif x+n > msg.width {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts.SetCell(x+n, y, styles.Error, ch)\n\t\t}\n\t}\n\n\treturn 0\n}", "func (p *Plasma) Draw(screen *ebiten.Image) {\r\n\tscreen.ReplacePixels(p.buffer)\r\n}", "func rePrompt(){\n\tfmt.Println(\"\\nPush Enter to continue....\\n\")\n}", "func Break() {\n\tfmt.Println(color.HiMagentaString(\"-------\"))\n}", "func ClearScreen() {\n\t// Attempt to clear cli screen.\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tcmd := exec.Command(\"cmd\", \"/c\", \"cls\") //Windows example, its tested\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t\treturn\n\t}\n\n\tprint(\"\\033[H\\033[2J\")\n}", "func Remind(text string, paus time.Duration) {\n\tfor {\n\t\tfmt.Println(\"Klockan är\", time.Now().Format(\"15:04\"), text)\n\t\ttime.Sleep(paus)\n\t}\n\n}", "func clearScreen() {\n\tif strings.Contains(runtime.GOOS, \"windows\") {\n\t\t// windows\n\t\tcmd := exec.Command(\"cmd\", \"/c\", \"cls\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t} else {\n\t\t// linux or mac\n\t\tcmd := exec.Command(\"clear\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Run()\n\t}\n}", "func Pause(msg string) {\n\tfmt.Print(msg, \"[Press Enter to Continue]: \")\n\tvar s string\n\t_, err := fmt.Scan(&s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func banner() {\n\tfmt.Println(\"**************************************************\")\n\tfmt.Println(\" ___ ____ ___ __ _ __\")\n\tfmt.Println(\" | | | | | | / \\\\ | ) |\")\n\tfmt.Println(\" | =| | | =~ |==| |==| |==| |= |=\")\n\tfmt.Println(\" |__| |__| ___| | | | | | \\\\ |__\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"**************************************************\")\n}", "func (w *VT100Writer) EraseScreen() {\n\tw.WriteRaw([]byte{0x1b, '[', '2', 'J'})\n}", "func OnExit() {\n\tapp.GetIndicator().Disconnect()\n}", "func ClearScreen() {\n\tfb.Clear()\n}", "func (app *Application) Fatal(err error) {\n\tdialog := gtk.MessageDialogNew(nil, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, err.Error())\n\tdialog.Connect(\"response\", func() {\n\t\tgtk.MainQuit()\n\t\tos.Exit(1)\n\t})\n\tdialog.Show()\n\tif gtk.MainLevel() == 0 {\n\t\tgtk.Main()\n\t}\n}", "func (s *Spinner) SetMessage(message string) {\n\ts.Lock()\n\ts.message = message\n\ts.Unlock()\n\ts.createFrames()\n}", "func GuiFade(alpha float32) {\n\tcalpha, _ := (C.float)(alpha), cgoAllocsUnknown\n\tC.GuiFade(calpha)\n}", "func (t *TextGame) ExitGame() {\n\t// Clean up screen object\n\tt.screen.Fini()\n}", "func (g *Game) Draw(screen *ebiten.Image) {\n\tscreen.Fill(color.NRGBA{0x2F, 0x3F, 0x5F, 0xff})\n\n\tui.Update(screen)\n\n\treturn\n}", "func PrintSuccess(message string) {\n\tfmt.Printf(green + \"✔ \" + message + noFormat + \"\\n\")\n}", "func WriteMessage(lcd *device.Lcd, str string, line device.ShowOptions) {\n\tm.Lock()\n\terr := lcd.ShowMessage(str, line)\n\tm.Unlock()\n\tif err != nil {\n\t\tlg.Fatalf(\"WriteMessage: %s\", err)\n\t}\n\treturn\n}", "func MessageBox(w *Window, msg, title string) {\n\t//if !started {\n\t//\tpanic(\"can't popup window before func Run()\")\n\t//}\n\tif runtime.GOOS == \"linux\" {\n\t\tmessageBoxLinux(w, msg, title)\n\t\treturn\n\t}\n\tcmsg := C.CString(msg)\n\tdefer C.free(unsafe.Pointer(cmsg))\n\tctitle := C.CString(title)\n\tdefer C.free(unsafe.Pointer(ctitle))\n\tvar nw C.NativeWnd\n\tif w != nil {\n\t\tnw = w.native\n\t}\n\tC.winl_message_box(nw, cmsg, ctitle)\n}", "func (button *Button) Draw(parent *Form, mousePosition mgl32.Vec2) {\n\t// Check if mouse is over the button and change his color\n\ttext := button.content\n\tif mousePosition.X() > button.position.X() && mousePosition.Y() < button.position.Y() && mousePosition.X() < button.position.X()+button.size.X() && mousePosition.Y() > button.position.Y()-button.size.Y() {\n\t\ttext = \"YEAH !!!\"\n\t\tparent.window.SetCursor(glfw.CreateStandardCursor(glfw.HandCursor))\n\t}\n\t// println(fmt.Sprintf(\"X: %f, Y: %f\", mousePosition.X(), mousePosition.Y()))\n\tparent.font.Draw(text, button.fgColor, button.position)\n}", "func advanceScreen(rows int) {\n\tsetCursorRow(terminalHeight)\n\tfmt.Print(strings.Repeat(lineBreak, rows))\n}", "func showIndicator(cmd *cobra.Command) func() {\n\tw := cmd.OutOrStderr()\n\tif w == nil {\n\t\tw = os.Stdout\n\t}\n\n\tctx, cancel := context.WithCancel(context.TODO())\n\n\tgo func() {\n\t\tw.Write([]byte(\"|\"))\n\t\tw.Write([]byte(\"_\"))\n\t\tw.Write([]byte(\"|\"))\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\n\t\t\t\tw.Write([]byte(\"\\010\\010-\"))\n\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\tw.Write([]byte(\"\\010\\\\\"))\n\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\tw.Write([]byte(\"\\010|\"))\n\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\tw.Write([]byte(\"\\010/\"))\n\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\tw.Write([]byte(\"\\010-\"))\n\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\tw.Write([]byte(\"|\"))\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn func() {\n\t\tcancel()\n\t\tw.Write([]byte(\"\\010\\010\\010\")) //remove the loading chars\n\t}\n}", "func (l *Label) Draw(screen *ebiten.Image) {\n\n\ttext.Draw(screen, l.text, l.font, l.origin.X, l.origin.Y+l.height, BasicColors[\"White\"])\n\n}", "func endApp() {\n\tfmt.Println(\"Aplikasi Selesai\")\n}", "func (app *AppPath) ShowMessage(m gobou.Message) {\n\tif !m.NotifyMessage.IsNone() {\n\t\tnotify.Notify(m.NotifyMessage.Text)\n\t}\n\tapp.Config.Jtalk.Play(m.JtalkMessage)\n\tif !m.StdoutMessage.IsNone() {\n\t\tfmt.Println(m.StdoutMessage.Text)\n\t}\n}", "func (d *Draw) TextCenter(text string, p Point, color sdl.Color, size int) {\n\tsurf, err := font.Size(size).RenderUTF8Blended(text, color)\n\tif err != nil {\n\t\td.err(err, \"error on render text\")\n\t\treturn\n\t}\n\tdefer surf.Free()\n\ttextTexture, err := d.renderer.CreateTextureFromSurface(surf)\n\tif err != nil {\n\t\td.err(err, \"error on create texture\")\n\t\treturn\n\t}\n\tdefer textTexture.Destroy()\n\terr = d.renderer.Copy(textTexture, nil, &sdl.Rect{X: p.X - int32(surf.W/2), Y: p.Y - int32(surf.H/2), W: surf.W, H: surf.H})\n\tif err != nil {\n\t\td.err(err, \"error on copy texture to surface\")\n\t\treturn\n\t}\n}", "func Clear() {\n\tfmt.Print(\"\\033[2J\")\n}", "func (w *Window) Present() {\n\tC.winl_swap_buffers(w.native)\n}", "func (win *Window) Fullscreen() {\n\twin.Candy().Guify(\"gtk_window_fullscreen\", win)\n}", "func PrintBlockyLogo() {\n\tfmt.Println(`\n::: ::: .::::::::... :::::::::::: \n ::: ::: .:::' ':::: ::: ::: \n ::: ::: ::: ::: .::::.. ..::::::.. ::: .:: ::: :::\n ::: ::: :::.: ::: .::' ':: ::: ....... ::: :::\n ::: .:: ::: ::: ::: ::: ::: ::: ::::::: ::: :::\n ::. ' ::: ::: ::: '::. .:: ::: ':::. ::: ::: ::: \n ::: ::: ::: ::: '::::::::' ::: ':::::::::::' :::::::::::: \n\n:::::::::::::\n:: ::\n:: :: ..::::::.. ::\n:::::::::: ..... :::::::: .::' ':: ::.:::::.\n:: .: :. :: ::: :: ::\n:: ::::::::: :: '::. .:: :: ::\n:: :..... ::. '::::::::' :: ::\n\n ::: ::: ::: \n ::: : ::. ::: :: \n ::: :: :: ::: :: :: \n ::: ::: ::: ::: ..... ..... :::::::: ::.:::::. ..... :: .::\n ::: :: ::: ::: .: :. .: :. :: :: :: .: :. ::.\n ::: : ::: : ::::::::: :: :: :: :: :: ::::::::: ::\n ::: ::: :..... ::....::.. ::. :: :: :..... ::\n\t`)\n}", "func (c Command) Draw() string { return strings.TrimSpace(c.result.String()) }", "func Clear() {\n\tprint(\"\\033[H\\033[2J\")\n}" ]
[ "0.69290227", "0.57025", "0.5530372", "0.53906137", "0.5334933", "0.52448684", "0.49548224", "0.49495384", "0.479707", "0.47962686", "0.4782869", "0.4744896", "0.47218937", "0.4683693", "0.46746337", "0.4671464", "0.46520698", "0.4631259", "0.4587818", "0.4570606", "0.45457944", "0.45340434", "0.448598", "0.44789758", "0.4473416", "0.44672403", "0.4462843", "0.4453657", "0.43972626", "0.43864346", "0.43857616", "0.4380626", "0.43672898", "0.43497", "0.43455434", "0.43413037", "0.43406498", "0.4314885", "0.4303479", "0.42997247", "0.42766428", "0.427652", "0.42737275", "0.42708734", "0.42603892", "0.42519277", "0.42490757", "0.42347687", "0.42262086", "0.42253858", "0.4205716", "0.42047897", "0.42003995", "0.42000377", "0.41726035", "0.41693836", "0.4169056", "0.41688487", "0.41628322", "0.4149219", "0.41411394", "0.41290972", "0.4127995", "0.41159317", "0.41152853", "0.4105993", "0.40987962", "0.408683", "0.4082417", "0.4076523", "0.40718538", "0.40704033", "0.40667036", "0.40650296", "0.40493813", "0.40411723", "0.40391052", "0.403055", "0.40297902", "0.402255", "0.4012028", "0.40090486", "0.39796093", "0.39781654", "0.39725646", "0.39654744", "0.39646903", "0.39641392", "0.39637285", "0.39634138", "0.39613053", "0.39605442", "0.3950269", "0.39498004", "0.39488423", "0.39405295", "0.39396486", "0.3938533", "0.39373657", "0.3932431" ]
0.6699799
1
sub substracts b from a without normalization
func sub(a, b Poly) Poly { var c Poly for i := 0; i < n; i++ { c[i] = a[i] - b[i] } return c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func substract(a, b float64) float64 {\n\treturn a - b\n}", "func (n *bigNumber) sub(x *bigNumber, y *bigNumber) *bigNumber {\n\treturn n.subRaw(x, y).bias(2).weakReduce()\n}", "func (a Balance) Sub(b *Balance) Balance {\n\tfor i, v := range b {\n\t\ta[i] -= v\n\t}\n\treturn a\n}", "func (a ImpactAmount) sub(b ImpactAmount) ImpactAmount {\n\tif b >= a {\n\t\treturn 0\n\t}\n\treturn a - b\n}", "func Subtract(a, b float64) float64 {\n\treturn a - b\n}", "func Subtract(a, b float64) float64 {\n\treturn a - b\n}", "func Subtract(a float64, b float64) float64 {\n\treturn a - b\n}", "func Substract(a, b NumberArray) (resultingMatrix NumberArray, err error) {\n\treturn binaryOperation(\"Substract\", a, b)\n}", "func (v *Vector2) Subtract(b Vector2) {\r\n\tv.x -= b.x\r\n\tv.y -= b.y\r\n}", "func (t Torus) Sub(a, b Point) Point {\n\ta, b = t.normPair(a, b)\n\treturn a.Sub(b)\n}", "func SUBB(imr, amr operand.Op) { ctx.SUBB(imr, amr) }", "func (z fermat) Sub(x, y fermat) fermat {\n\tif len(z) != len(x) {\n\t\tpanic(\"Add: len(z) != len(x)\")\n\t}\n\tn := len(y) - 1\n\tb := subVV(z[:n], x[:n], y[:n])\n\tb += y[n]\n\t// If b > 0, we need to subtract b<<n, which is the same as adding b.\n\tz[n] = x[n]\n\tif z[0] <= ^big.Word(0)-b {\n\t\tz[0] += b\n\t} else {\n\t\taddVW(z, z, b)\n\t}\n\tz.norm()\n\treturn z\n}", "func Subtract(a, operand int) int { return operand - a }", "func Sub(valueA gcv.Value, valueB gcv.Value) gcv.Value {\n\tif valueA.Type() == gcv.Complex || valueB.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(valueA.Complex() - valueB.Complex())\n\t}\n\treturn gcv.MakeValue(valueA.Real() - valueB.Real())\n}", "func Subtract(a cty.Value, b cty.Value) (cty.Value, error) {\n\treturn SubtractFunc.Call([]cty.Value{a, b})\n}", "func (a *Int64s) Subtract(b *Int64s) *Int64s {\n\tresult := a.Clone()\n\tfor x, _ := range b.backing {\n\t\tresult.Remove(x)\n\t}\n\treturn result\n}", "func Subtract(bytesPerDim, dim int, a, b, result []byte) error {\n\tstart := dim * bytesPerDim\n\tend := start + bytesPerDim\n\tborrow := 0\n\tfor i := end - 1; i >= start; i-- {\n\t\tdiff := int(a[i]) - int(b[i]&0xff) - borrow\n\t\tif diff < 0 {\n\t\t\tdiff += 256\n\t\t\tborrow = 1\n\t\t} else {\n\t\t\tborrow = 0\n\t\t}\n\t\tresult[i-start] = byte(diff)\n\t}\n\tif borrow != 0 {\n\t\treturn errors.New(\"a < b\")\n\t}\n\treturn nil\n}", "func sub(a, b, carry int32) (diff int32, newCarry int32) {\n\tdiff = a - b - carry\n\tif diff < 0 {\n\t\tnewCarry = 1\n\t\tdiff += wordBase\n\t} else {\n\t\tnewCarry = 0\n\t}\n\treturn diff, newCarry\n}", "func TestSubstract(t *testing.T) {\n\tvar i, j uint\n\tfor i = 1; i < 100; i++ {\n\t\ta := makeRandomVector(i)\n\t\tb := makeRandomVector(i)\n\t\tc, _ := Substract(a, b)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif c.dims[j] != a.dims[j]-b.dims[j] {\n\t\t\t\tt.Error(\"Substraction failed, didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f - %f != %f\", a.dims[j], b.dims[j], c.dims[j])\n\t\t\t}\n\t\t}\n\n\t\t// Test in-place sybstraction\n\t\tc = a.Copy()\n\t\tc.Substract(b)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif c.dims[j] != a.dims[j]-b.dims[j] {\n\t\t\t\tt.Error(\n\t\t\t\t\t\"In-place Substraction failed, didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f - %f != %f\", a.dims[j], b.dims[j], c.dims[j])\n\t\t\t}\n\t\t}\n\t}\n}", "func sm2P256Sub(c, a, b *sm2P256FieldElement) {\n\tvar carry uint32\n\n\tfor i := 0; ; i++ {\n\t\tc[i] = a[i] - b[i]\n\t\tc[i] += sm2P256Zero31[i]\n\t\tc[i] += carry\n\t\tcarry = c[i] >> 29\n\t\tc[i] &= bottom29Bits\n\t\ti++\n\t\tif i == 9 {\n\t\t\tbreak\n\t\t}\n\t\tc[i] = a[i] - b[i]\n\t\tc[i] += sm2P256Zero31[i]\n\t\tc[i] += carry\n\t\tcarry = c[i] >> 28\n\t\tc[i] &= bottom28Bits\n\t}\n\tsm2P256ReduceCarry(c, carry)\n}", "func (a Vec2) Sub(b Vec2) Vec2 {\n\treturn Vec2{a.X - b.X, a.Y - b.Y}\n}", "func (a *Array64) Subtr(b *Array64) *Array64 {\n\tif a.valRith(b, \"Subtr\") {\n\t\treturn a\n\t}\n\n\tif b.shape[len(b.shape)-1] == a.shape[len(a.shape)-1] {\n\t\tasm.Subtr(a.data, b.data)\n\t\treturn a\n\t}\n\n\tst := a.strides[len(a.strides)-1] * a.shape[len(a.shape)-1]\n\tfor i := 0; i < len(b.data); i++ {\n\t\tasm.SubtrC(b.data[i], a.data[i*st:(i+1)*st])\n\t}\n\treturn a\n}", "func subtract(x, y float64) float64 {\n\treturn x - y\n}", "func Subtract(a, b int64) int64 {\n\treturn a - b\n}", "func gfSub(a, b gfElement) gfElement {\n\treturn a ^ b\n}", "func Modsub(a, b, m *ED25519.BIG) *ED25519.BIG {\n\treturn Modadd(a, ED25519.Modneg(b, m), m)\n}", "func Modsub(a, b, m *ED25519.BIG) *ED25519.BIG {\n\treturn Modadd(a, ED25519.Modneg(b, m), m)\n}", "func Modsub(a, b, m *ED25519.BIG) *ED25519.BIG {\n\treturn Modadd(a, ED25519.Modneg(b, m), m)\n}", "func (s *Scalar) Subtract(x, y *Scalar) *Scalar {\n\ts.s.Sub(&x.s, &y.s)\n\treturn s\n}", "func Sub(a, b *big.Float) *big.Float {\n\treturn ZeroBigFloat().Sub(a, b)\n}", "func Sub( a *context.Value, b *context.Value ) (*context.Value,error) {\n if a != nil && b != nil {\n switch a.OperationType( b ) {\n case context.VAR_BOOL:\n return context.IntValue( a.Int() - b.Int() ), nil\n case context.VAR_INT:\n return context.IntValue( a.Int() - b.Int() ), nil\n case context.VAR_FLOAT:\n return context.FloatValue( a.Float() - b.Float() ), nil\n case context.VAR_COMPLEX:\n return context.ComplexValue( a.Complex() - b.Complex() ), nil\n default:\n }\n }\n\n return nil, errors.New( \"Unsupported type for sub\" )\n}", "func (a *Vec4) Subtract(b Vec4) {\n\ta.X -= b.X\n\ta.Y -= b.Y\n\ta.Z -= b.Z\n\ta.W -= b.W\n}", "func Sub(a int, b int) float32 {\n\treturn float32(a - b)\n}", "func (d *GF255e) Sub(a, b *GF255e) *GF255e {\n\tgf_sub((*[4]uint64)(d), (*[4]uint64)(a), (*[4]uint64)(b), mq255e)\n\treturn d\n}", "func sub(a, b big.Int) big.Int {\n\treturn *big.NewInt(1).Sub(&a, &b)\n}", "func sub(a string, b string) string {\n\tevenPad(&a, &b)\n\n\tdiff := \"\"\n\tc := false\n\tfor i := len(a) - 1; i >= 0; i-- {\n\t\taint, _ := strconv.Atoi(string(a[i]))\n\t\tbint, _ := strconv.Atoi(string(b[i]))\n\n\t\tif c {\n\t\t\taint--\n\t\t}\n\n\t\tif bint > aint {\n\t\t\taint += 10\n\t\t\tc = true\n\t\t} else {\n\t\t\tc = false\n\t\t}\n\n\t\td := aint - bint\n\n\t\tdiff = strconv.Itoa(d) + diff\n\t}\n\n\treturn unpad(diff)\n}", "func (c *CSR) Sub(a, b mat.Matrix) {\n\tc.addScaled(a, b, 1, -1)\n}", "func Sub(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.Sub(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.TransInv(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.TransInvR(a, opts...)\n\t}\n\tpanic(\"Unreachable\")\n}", "func PSUBB(mx, x operand.Op) { ctx.PSUBB(mx, x) }", "func (p *Int64) Sub(q, r *Int64) *Int64 {\n\tx := new(Int64).Set(q)\n\ty := new(Int64).Set(r)\n\tz := NewInt64()\n\tfor n, a := range x.c {\n\t\tif b, ok := y.Coeff(n); ok {\n\t\t\tz.SetCoeff(n, a-b)\n\t\t} else {\n\t\t\tz.SetCoeff(n, a)\n\t\t}\n\t}\n\tfor n, b := range y.c {\n\t\tif _, ok := x.Coeff(n); !ok {\n\t\t\tz.SetCoeff(n, -b)\n\t\t}\n\t}\n\treturn p.Set(z)\n}", "func ValueSub(a, b reflect.Value) (reflect.Value, error) {\n\taBkind := GetBaseKind(a)\n\tbBkind := GetBaseKind(b)\n\n\tswitch aBkind {\n\tcase reflect.Int64:\n\t\tswitch bBkind {\n\t\tcase reflect.Int64:\n\t\t\treturn reflect.ValueOf(a.Int() - b.Int()), nil\n\t\tcase reflect.Uint64:\n\t\t\treturn reflect.ValueOf(a.Int() - int64(b.Uint())), nil\n\t\tcase reflect.Float64:\n\t\t\treturn reflect.ValueOf(float64(a.Int()) - b.Float()), nil\n\t\tdefault:\n\t\t\treturn reflect.ValueOf(nil), errors.Errorf(\"Can not do subtraction math operator between %s and %s\", a.Kind().String(), b.Kind().String())\n\t\t}\n\tcase reflect.Uint64:\n\t\tswitch bBkind {\n\t\tcase reflect.Int64:\n\t\t\treturn reflect.ValueOf(int64(a.Uint()) - b.Int()), nil\n\t\tcase reflect.Uint64:\n\t\t\treturn reflect.ValueOf(a.Uint() - b.Uint()), nil\n\t\tcase reflect.Float64:\n\t\t\treturn reflect.ValueOf(float64(a.Uint()) - b.Float()), nil\n\t\tdefault:\n\t\t\treturn reflect.ValueOf(nil), errors.Errorf(\"Can not do subtraction math operator between %s and %s\", a.Kind().String(), b.Kind().String())\n\t\t}\n\tcase reflect.Float64:\n\t\tswitch bBkind {\n\t\tcase reflect.Int64:\n\t\t\treturn reflect.ValueOf(a.Float() - float64(b.Int())), nil\n\t\tcase reflect.Uint64:\n\t\t\treturn reflect.ValueOf(a.Float() - float64(b.Uint())), nil\n\t\tcase reflect.Float64:\n\t\t\treturn reflect.ValueOf(a.Float() - b.Float()), nil\n\t\tdefault:\n\t\t\treturn reflect.ValueOf(nil), errors.Errorf(\"Can not do subtraction math operator between %s and %s\", a.Kind().String(), b.Kind().String())\n\t\t}\n\tdefault:\n\t\treturn reflect.ValueOf(nil), errors.Errorf(\"Can not do subtraction math operator between %s and %s\", a.Kind().String(), b.Kind().String())\n\t}\n}", "func (z *Rat) Sub(x, y *Rat) *Rat {}", "func Bvsub(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_bvsub(C.term_t(t1), C.term_t(t2)))\n}", "func sub(a, b, carry int32) (int32, int32) {\n\ttrace_util_0.Count(_mydecimal_00000, 10)\n\tdiff := a - b - carry\n\tif diff < 0 {\n\t\ttrace_util_0.Count(_mydecimal_00000, 12)\n\t\tcarry = 1\n\t\tdiff += wordBase\n\t} else {\n\t\ttrace_util_0.Count(_mydecimal_00000, 13)\n\t\t{\n\t\t\tcarry = 0\n\t\t}\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 11)\n\treturn diff, carry\n}", "func (vn *VecN) Sub(dst *VecN, addend *VecN) *VecN {\n\tif vn == nil || addend == nil {\n\t\treturn nil\n\t}\n\tsize := intMin(len(vn.vec), len(addend.vec))\n\tdst = dst.Resize(size)\n\n\tfor i := 0; i < size; i++ {\n\t\tdst.vec[i] = vn.vec[i] - addend.vec[i]\n\t}\n\n\treturn dst\n}", "func (gdt *Vector3) OperatorSubtract(b Vector3) Vector3 {\n\targ0 := gdt.getBase()\n\targ1 := b.getBase()\n\n\tret := C.go_godot_vector3_operator_subtract(GDNative.api, arg0, arg1)\n\n\treturn Vector3{base: &ret}\n\n}", "func approxSub(a, b float64) float64 {\n\tif ((a < 0 && b < 0) || (a > 0 && b > 0)) && math.Abs(a-b) < 2.22045e-016 {\n\t\treturn 0\n\t}\n\treturn a - b\n}", "func (b *IBFCell) Subtract(b2 *IBFCell) {\n\tb.IDSum.XOR(&b2.IDSum)\n\tb.HashSum.XOR(&b2.HashSum)\n\tb.Count -= b2.Count\n}", "func Sub(x, y Number) Number {\n\treturn Number{\n\t\tReal: x.Real - y.Real,\n\t\tE1mag: x.E1mag - y.E1mag,\n\t\tE2mag: x.E2mag - y.E2mag,\n\t\tE1E2mag: x.E1E2mag - y.E1E2mag,\n\t}\n}", "func (z *Float64) Sub(x, y *Float64) *Float64 {\n\tz.l = x.l - y.l\n\tz.r = x.r - y.r\n\treturn z\n}", "func (z *BiComplex) Sub(x, y *BiComplex) *BiComplex {\n\tz.l.Sub(&x.l, &y.l)\n\tz.r.Sub(&x.r, &y.r)\n\treturn z\n}", "func Subtracao(a, b Matriz) Matriz {\n\n\tmatriz := Matriz{}\n\tmatriz.Iniciar(a.Linhas, b.Colunas)\n\n\tfor i := 0; i < a.Linhas; i++ {\n\t\tfor j := 0; j < a.Colunas; j++ {\n\t\t\tmatriz.Dados[i][j] = a.Dados[i][j] - b.Dados[i][j]\n\t\t}\n\t}\n\n\treturn matriz\n}", "func Subtract(a, b int) int {\n\treturn a - b\n}", "func Subtract(a, b int) int {\n\treturn a - b\n}", "func Subtract(a, b int) int {\n\treturn a - b\n}", "func (x *BigUInt) Subtract(y *BigUInt) (*BigUInt, error) {\n\tif len(y.data) > len(x.data) {\n\t\treturn nil, ErrUnderflow\n\t}\n\toriginalX := make([]byte, len(x.data), cap(x.data))\n\tcopy(originalX, x.data)\n\txSize, ySize := len(x.data), len(y.data)\n\tborrow, diff := uint16(0), uint16(0)\n\tfor i := 0; i < xSize || i < ySize; i++ {\n\t\txData, yData := uint16(x.data[i]), uint16(0)\n\t\tif i < ySize {\n\t\t\tyData = uint16(y.data[i])\n\t\t}\n\n\t\tif xData < (yData + borrow) {\n\t\t\tdiff = (xData + 0x100) - yData - borrow\n\t\t\tborrow = 0x01\n\t\t} else {\n\t\t\tdiff = (xData + 0x100) - yData - borrow\n\t\t\tborrow = 0x00\n\t\t}\n\t\tx.data[i] = uint8(diff & 0xff)\n\t}\n\tif borrow > 0 {\n\t\tcopy(x.data, originalX)\n\t\treturn nil, ErrUnderflow\n\t}\n\n\tcnt := len(x.data) - 1\n\tfor cnt >= 0 && x.data[cnt] == 0 {\n\t\tcnt--\n\t}\n\n\tx.data = x.data[:cnt+1]\n\treturn x, nil\n}", "func (m Mat2f) Sub(other Mat2f) Mat2f {\n\treturn Mat2f{\n\t\tm[0] - other[0], m[1] - other[1],\n\t\tm[2] - other[2], m[3] - other[3]}\n}", "func (z *polyGF2) Sub(a, b *polyGF2) *polyGF2 {\n\treturn z.Add(a, b)\n}", "func (cal *Calculate) sub(value float64) (result float64) {\n\tif len(cal.Arg) == 2 {\n\t\treturn (cal.Arg[0] - cal.Arg[1])\n\t} else if len(cal.Arg) == 1 {\n\t\treturn (value - cal.Arg[0])\n\t}\n\n\tlog.Fatalln(\"Please check the data format of the calculation unit\")\n\treturn\n}", "func sub(x, y int) (answer int, err error) {\n\tanswer = x - y\n\treturn\n}", "func (ibf *InvertibleBloomFilter) Subtract(ibf2 *InvertibleBloomFilter) *InvertibleBloomFilter {\n\tdifference := NewIBF(ibf.Size)\n\tcopy(difference.Cells, ibf.Cells)\n\n\tfor j := 0; j < ibf.Size; j++ {\n\t\tdifference.Cells[j].Subtract(&ibf2.Cells[j])\n\t}\n\n\treturn difference\n}", "func FloatSubtract(a, b float64) float64 {\n\treturn toFixed(toFixed(a) - toFixed(b))\n}", "func Subtract(x, y *Matrix) (*Matrix, error) {\n\tminusY, _ := Scale(-1, y)\n\tresult, err := Add(x, minusY)\n\treturn result, err\n}", "func (v Vector3D) Sub(other Vector3D) Vector3D {\n\treturn Vector3D{\n\t\tx: v.x - other.x,\n\t\ty: v.y - other.y,\n\t\tz: v.z - other.z,\n\t}\n}", "func (a *Allocation) Subtract(other *Allocation) *Allocation {\n\tresult := initializeZeroAlloc()\n\tfor t, v := range a.Value {\n\t\tresult.Value[t] = v.Subtract(other.Value[t])\n\t}\n\treturn result\n}", "func Sub(minuend, subtrahend *big.Int) *big.Int { return I().Sub(minuend, subtrahend) }", "func subtract(x, y int) (res int) {\n\tres = x - y\n\treturn\n}", "func (p Point2) Sub(ps ...Point2) Point2 {\n\tfor _, p2 := range ps {\n\t\tp[0] -= p2[0]\n\t\tp[1] -= p2[1]\n\t}\n\treturn p\n}", "func absSub(a, b id.ID) id.ID {\n\tcmp := id.Compare(a, b)\n\tswitch {\n\tcase cmp < 0: // a < b\n\t\treturn idSub(b, a)\n\tcase cmp == 0: // a == b\n\t\treturn id.Zero\n\tcase cmp > 0: // a > b\n\t\treturn idSub(a, b)\n\tdefault:\n\t\tpanic(\"impossible case\")\n\t}\n}", "func (v1 Vector2) Sub(v2 Vector2) Vector2 {\n\treturn Vector2{v1.X - v2.X, v1.Y - v2.Y}\n}", "func Sub(v1, v2 *Vec) *Vec {\n\tnegV2 := Negate(v2)\n\treturn Add(v1, negV2)\n}", "func (v Vec) SubBy(other Vec) Vec {\n\tassertSameLen(v, other)\n\tfor i, val := range other {\n\t\tv[i] -= val\n\t}\n\treturn v\n}", "func PSUBSB(mx, x operand.Op) { ctx.PSUBSB(mx, x) }", "func (a Vector3) Minus(b Vector3) Vector3 {\n\treturn Vector3{a.X - b.X, a.Y - b.Y, a.Z - b.Z}\n}", "func (v Vector2) Subtract(other Vector) Vector {\r\n\totherv := checkVector2(other)\r\n\treturn Vector2{\r\n\t\tv[0] - otherv[0],\r\n\t\tv[1] - otherv[1],\r\n\t}\r\n}", "func (v1 Vec3) Sub(v2 Vec3) *Vec3 {\n\treturn &Vec3{e: [3]float32{v1.X() - v2.X(), v1.Y() - v2.Y(), v1.Z() - v2.Z()}}\n}", "func (v1 *Vector) Subtract(v2 Vector) (Vector, error){\n\terr := v1.CompareDimensions(v2)\n\tif err != nil {\n\t\treturn Vector{}, err\n\t}\n\n\tvar diff []float64\n\n\tfor i, val1 := range v1.Values {\n\t\tval2 := v2.Values[i]\n\t\tdiff = append(diff, val1 - val2)\n\t}\n\n\treturn New(diff), nil\n}", "func (v *V) Sub(x *V) *V {\n\tif !IsVSameShape(x, v) {\n\t\tpanic(ErrShape)\n\t}\n\tfor i, e := range x.Data {\n\t\tv.Data[i] -= e\n\t}\n\treturn v\n}", "func (A Matrix) Subtract(B Matrix) {\n\tma, na := A.Dimensions()\n\tmb, nb := B.Dimensions()\n\tif ma != mb || na != nb {\n\t\tpanic(\"matrices must have the same number of rows and columns\")\n\t}\n\n\tfor i := 0; i < ma; i++ {\n\t\tfor j := 0; j < na; j++ {\n\t\t\tA[i][j] -= B[i][j]\n\t\t}\n\t}\n}", "func Sub(a uint8, b uint8, mc *microcontroller, borrow uint8) uint8 {\r\n\tresult16 := uint16(a) - uint16(b) - uint16(borrow)\r\n\tresult8 := uint8(result16)\r\n\tmc.zero = result8 == 0x0\r\n\tmc.sign = (result8 >> 7) == 0x1\r\n\tmc.parity = GetParity(result8)\r\n\tmc.carry = result16&0x100 > 0\r\n\r\n\tindex := (((a & 0x88) >> 1) | ((b & 0x88) >> 2) | ((result8 & 0x88) >> 3)) & 0x7\r\n\tmc.auxCarry = subHalfCarryTable[index]\r\n\treturn result8\r\n}", "func (f *Float) Sub(x, y *Float) *Float {\n\tx.doinit()\n\ty.doinit()\n\tf.doinit()\n\tC.mpf_sub(&f.i[0], &x.i[0], &y.i[0])\n\treturn f\n}", "func Subtract(v, u *Vec) *Vec {\n\treturn &Vec{\n\t\tv.X - u.X,\n\t\tv.Y - u.Y,\n\t}\n}", "func SUBW(imr, amr operand.Op) { ctx.SUBW(imr, amr) }", "func Subtract(nums ...float64) (total float64) {\n\ttotal = nums[0]\n\tfor i := 1; i < len(nums); i++ {\n\t\ttotal -= nums[i]\n\t}\n\treturn\n}", "func Subtract(t, other Tuplelike) Tuplelike {\n\tresult := []float64{}\n\n\tfor idx, value := range t.Values() {\n\t\tresult = append(result, value-other.At(idx))\n\t}\n\n\treturn Tuple(result)\n}", "func (v Vec) AbsSubBy(other Vec) Vec {\n\tassertSameLen(v, other)\n\tfor i, val := range other {\n\t\tv[i] = math.Abs(v[i] - val)\n\t}\n\treturn v\n}", "func (v Vec) AbsSub(other Vec) Vec {\n\treturn v.Copy().AbsSubBy(other)\n}", "func (v Vec2) Sub(x Vec2) Vec2 {\n\treturn Vec2{v[0] - x[0], v[1] - x[1]}\n}", "func Subtract(in []int) int {\n\tres := 0\n\tfor _, r := range in {\n\t\t//fmt.Println(\"r=\",r)\n\t\tres -= r\n\t}\n\treturn res\n}", "func (bal Balance) Sub(other Balance) Balance {\r\n\tif other.Coins > bal.Coins || other.Hours > bal.Hours {\r\n\t\tlogger.Panic(\"Cannot subtract balances, second balance is too large\")\r\n\t}\r\n\treturn Balance{\r\n\t\tCoins: bal.Coins - other.Coins,\r\n\t\tHours: bal.Hours - other.Hours,\r\n\t}\r\n}", "func (v Vec3i) Sub(other Vec3i) Vec3i {\n\treturn Vec3i{v.X - other.X, v.Y - other.Y, v.Z - other.Z}\n}", "func (v Vec3) Sub(w Vec3) Vec3 {\n\treturn Vec3{v[0] - w[0], v[1] - w[1], v[2] - w[2]}\n}", "func SUBSD(mx, x operand.Op) { ctx.SUBSD(mx, x) }", "func (a *EncryptedVec) Sub(b *EncryptedVec) (*EncryptedVec, error) {\n\n\tif len(a.Coords) != len(b.Coords) {\n\t\treturn nil, errors.New(\"cannot add vectors of different length\")\n\t}\n\n\tpk := a.Pk\n\tres := make([]*paillier.Ciphertext, len(a.Coords))\n\n\tfor i := range a.Coords {\n\t\tres[i] = pk.Sub(a.Coords[i], b.Coords[i])\n\t}\n\n\treturn &EncryptedVec{\n\t\tPk: pk,\n\t\tCoords: res,\n\t}, nil\n}", "func (p Point3) Sub(ps ...Point3) Point3 {\n\tfor _, p2 := range ps {\n\t\tp[0] -= p2[0]\n\t\tp[1] -= p2[1]\n\t\tp[2] -= p2[2]\n\t}\n\treturn p\n}", "func (s *server) Subtract(ctx context.Context, in *pb.SubtractRequest) (*pb.SubtractReply, error) {\n\treturn &pb.SubtractReply{N1: in.N1 - in.N2}, nil\n}", "func Subtract(args ...int) int {\n\tif len(args) < 2 {\n\t\treturn 0\n\t}\n\n\tres := args[0]\n\tfor i := 1; i < len(args); i++ {\n\t\tres -= args[i]\n\t}\n\n\treturn res\n}", "func (ai *Arith) Sub(decimal1 *ZnDecimal, others ...*ZnDecimal) *ZnDecimal {\n\tvar result = copyZnDecimal(decimal1)\n\tif len(others) == 0 {\n\t\treturn result\n\t}\n\n\tfor _, item := range others {\n\t\tr1, r2 := rescalePair(result, item)\n\t\tresult.co.Sub(r1.co, r2.co)\n\t\tresult.exp = r1.exp\n\t}\n\treturn result\n}", "func Subtract(v1, v2 sqltypes.Value) (sqltypes.Value, error) {\n\tif v1.IsNull() || v2.IsNull() {\n\t\treturn sqltypes.NULL, nil\n\t}\n\te1, err := valueToEval(v1, collationNumeric)\n\tif err != nil {\n\t\treturn sqltypes.NULL, err\n\t}\n\te2, err := valueToEval(v2, collationNumeric)\n\tif err != nil {\n\t\treturn sqltypes.NULL, err\n\t}\n\tr, err := subtractNumericWithError(e1, e2)\n\tif err != nil {\n\t\treturn sqltypes.NULL, err\n\t}\n\treturn evalToSQLValue(r), nil\n}", "func (m *Money) Sub(n *Money) *Money {\n\tr := m.M - n.M\n\tif (r^m.M)&^(r^n.M) < 0 {\n\t\tpanic(ErrMoneyOverflow)\n\t}\n\tm.M = r\n\treturn m\n}" ]
[ "0.68170184", "0.67906046", "0.6721392", "0.667754", "0.6461374", "0.6461374", "0.64583826", "0.6450735", "0.6415383", "0.64147174", "0.63522595", "0.6311199", "0.63032115", "0.6285672", "0.62755585", "0.626222", "0.62547195", "0.61661404", "0.61415184", "0.6138247", "0.6066103", "0.60601413", "0.6047649", "0.60322076", "0.6014398", "0.6008665", "0.6008665", "0.6008665", "0.6002096", "0.600101", "0.59849876", "0.5978296", "0.59686905", "0.5944644", "0.5937626", "0.5936883", "0.5927269", "0.5911168", "0.59071416", "0.5903326", "0.5886462", "0.58788085", "0.58173376", "0.58100945", "0.58074224", "0.5797934", "0.5782431", "0.57598156", "0.57353866", "0.5720371", "0.57058114", "0.5697287", "0.5652179", "0.5652179", "0.5652179", "0.564197", "0.5615297", "0.5611842", "0.5602506", "0.5599872", "0.55978507", "0.5595848", "0.55882776", "0.55635303", "0.5552588", "0.5552247", "0.55509496", "0.55468595", "0.55338955", "0.5517079", "0.5506253", "0.5505337", "0.5504716", "0.5495276", "0.54902583", "0.54872763", "0.54790676", "0.54566884", "0.5454049", "0.54537034", "0.5449118", "0.544874", "0.5439614", "0.5423812", "0.5418664", "0.5395723", "0.53937864", "0.53912777", "0.5389071", "0.5382752", "0.53807163", "0.5379612", "0.5377237", "0.53597236", "0.5358258", "0.5357883", "0.53575546", "0.5350505", "0.5349595", "0.5343217" ]
0.63840187
10
reduce calls barretReduce on each coef
func (p *Poly) reduce() { for i := 0; i < n; i++ { p[i] = barretReduce(p[i]) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func bzReduce(combine bzConsumer, start float64, L, d int, fn BzFunc) float64 {\n\tpoints := bzPoints(L, d)\n\ttotal := start\n\tfor i := 0; i < len(points); i++ {\n\t\tk := points[i]\n\t\ttotal = combine(fn(k), total)\n\t}\n\treturn total\n}", "func (z *Big) Reduce() *Big { return z.Context.Reduce(z) }", "func Reduce(data []float64, mean float64, exponent float64) float64 {\r\n\treturn Accumulate(data, 0, func(a float64, b float64) float64 {\r\n\t\treturn a + math.Pow(b-mean, exponent)\r\n\t})\r\n}", "func Reduce(elements []Value, memo Value, reductor BiMapper) Value {\n\tfor _, elem := range elements {\n\t\tmemo = reductor(memo, elem)\n\t}\n\treturn memo\n}", "func (mdl *Model) Reduce(callback func(std.Value) bool) std.Value {\n\treturn nil\n}", "func VREDUCEPS_BCST(ops ...operand.Op) { ctx.VREDUCEPS_BCST(ops...) }", "func VREDUCEPS(ops ...operand.Op) { ctx.VREDUCEPS(ops...) }", "func MULB(mr operand.Op) { ctx.MULB(mr) }", "func (s VectOp) Reduce(f fs.ReduceOperator, identity float64) float64 {\n\tresult := identity\n\tfor _, val := range s {\n\t\tresult = f(val, result)\n\t}\n\treturn result\n}", "func Reduce[ValT, AccumT any](\n\tslc []ValT,\n\tstart AccumT,\n\tfn func(AccumT, ValT) AccumT,\n) AccumT {\n\tret := start\n\tfor _, t := range slc {\n\t\tret = fn(ret, t)\n\t}\n\treturn ret\n}", "func (v Var) Reduce() Expression { return v }", "func p256ReduceCarry(inout *[p256Limbs]uint32, carry uint32) {\n\tcarry_mask := nonZeroToAllOnes(carry)\n\n\tinout[0] += carry << 1\n\tinout[3] += 0x10000000 & carry_mask\n\t// carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the\n\t// previous line therefore this doesn't underflow.\n\tinout[3] -= carry << 11\n\tinout[4] += (0x20000000 - 1) & carry_mask\n\tinout[5] += (0x10000000 - 1) & carry_mask\n\tinout[6] += (0x20000000 - 1) & carry_mask\n\tinout[6] -= carry << 22\n\t// This may underflow if carry is non-zero but, if so, we'll fix it in the\n\t// next line.\n\tinout[7] -= 1 & carry_mask\n\tinout[7] += carry << 25\n}", "func (f ReduceFunc) Reduce(value [][]byte) (reduced [][]byte, err error) {\n\treturn f(value)\n}", "func (o *oobRegCtr) compute(Y []float64) (float64, float64) {\n\trss := 0.0 // residual sum square\n\n\t// tss of Y\n\tn := 0\n\tmean := 0.0\n\ttss := 0.0\n\n\tfor i := range Y {\n\t\t// skip examples that were in all trees\n\t\tif o.ct[i] < 1 {\n\t\t\tcontinue\n\t\t}\n\t\tpredVal := o.sum[i] / float64(o.ct[i])\n\t\td := Y[i] - predVal\n\t\trss += d * d\n\n\t\t// update var\n\t\tn++\n\t\td = Y[i] - mean\n\t\tmean += d / float64(n)\n\t\ttss += d * (Y[i] - mean)\n\t}\n\n\tif n < 1 {\n\t\ttss = 0.0\n\t}\n\n\trSquared := 1.0 - rss/tss\n\tmse := rss / float64(n)\n\n\treturn mse, rSquared\n}", "func (r1cs *R1CS) mulWireByCoeff(res *fr.Element, t r1c.Term) *fr.Element {\n\tcoeffValue := t.CoeffValue()\n\tswitch coeffValue {\n\tcase 1:\n\t\treturn res\n\tcase -1:\n\t\treturn res.Neg(res)\n\tcase 0:\n\t\treturn res.SetZero()\n\tcase 2:\n\t\treturn res.Double(res)\n\tdefault:\n\t\treturn res.Mul(res, &r1cs.Coefficients[t.CoeffID()])\n\t}\n}", "func VREDUCEPD_BCST(ops ...operand.Op) { ctx.VREDUCEPD_BCST(ops...) }", "func calculateFuelCompound(mass, total int) int {\n\t// fmt.Printf(\"Called: %v, %v\\n\", mass, total)\n\n\tfuel := calculateFuel(mass)\n\n\tif fuel <= 0 {\n\t\t// fmt.Printf(\"Returning. Last call: %v, %v\\n\", mass, total)\n\t\treturn total\n\t}\n\n\ttotal += fuel\n\treturn calculateFuelCompound(fuel, total)\n}", "func SUBB(imr, amr operand.Op) { ctx.SUBB(imr, amr) }", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func Accumulate(data []float64, initValue float64, f Operation) float64 {\r\n\tres := initValue\r\n\tfor _, v := range data {\r\n\t\tres = f(res, v)\r\n\t}\r\n\treturn res\r\n}", "func PEXTRB(i, x, mr operand.Op) { ctx.PEXTRB(i, x, mr) }", "func calcTrendGrowthMultipleRegressionPart1(bConstant, bGrowth bool, mtxY, mtxX, newX, mtxRes [][]float64, meanY float64, RXN, K, N int) {\n\tvecR := make([]float64, N) // for QR decomposition\n\tmeans := getNewMatrix(K, 1) // mean of each column\n\tslopes := getNewMatrix(1, K) // from b1 to bK\n\tif len(means) == 0 || len(slopes) == 0 {\n\t\treturn\n\t}\n\tif bConstant {\n\t\tcalcColumnMeans(mtxX, means, K, N)\n\t\tcalcColumnsDelta(mtxX, means, K, N)\n\t}\n\tif !calcRowQRDecomposition(mtxX, vecR, K, N) {\n\t\treturn\n\t}\n\t// Later on we will divide by elements of vecR, so make sure that they aren't zero.\n\tbIsSingular := false\n\tfor row := 0; row < K && !bIsSingular; row++ {\n\t\tbIsSingular = bIsSingular || vecR[row] == 0\n\t}\n\tif bIsSingular {\n\t\treturn\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tcalcApplyRowsHouseholderTransformation(mtxX, col, mtxY, N)\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tputDouble(slopes, col, getDouble(mtxY, col))\n\t}\n\tcalcSolveWithUpperRightTriangle(mtxX, vecR, slopes, K, false)\n\t// Fill result matrix\n\tcalcFastMult(newX, slopes, mtxRes, RXN, K, 1)\n\tif bConstant {\n\t\tintercept := meanY - calcSumProduct(means, slopes, K)\n\t\tfor row := 0; row < RXN; row++ {\n\t\t\tmtxRes[0][row] = mtxRes[0][row] + intercept\n\t\t}\n\t}\n\tif bGrowth {\n\t\tfor i := 0; i < RXN; i++ {\n\t\t\tputDouble(mtxRes, i, math.Exp(getDouble(mtxRes, i)))\n\t\t}\n\t}\n}", "func sm2P256ReduceCarry(a *sm2P256FieldElement, carry uint32) {\n\ta[0] += sm2P256Carry[carry*9+0]\n\ta[2] += sm2P256Carry[carry*9+2]\n\ta[3] += sm2P256Carry[carry*9+3]\n\ta[7] += sm2P256Carry[carry*9+7]\n}", "func computeValues(o *Operation) {\n\to.Values[o.Size-1] = o.cumm[o.Size-1]\n\tfor i := o.Size - 2; i >= 0; i-- {\n\t\to.Values[i] = o.Values[i+1] + o.cumm[i]\n\t}\n}", "func PAVGB(mx, x operand.Op) { ctx.PAVGB(mx, x) }", "func VREDUCESS(ops ...operand.Op) { ctx.VREDUCESS(ops...) }", "func Reduce(in interface{}, memo interface{}, fn reducef) interface{} {\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tmemo = fn(memo,val.Index(i).Interface())\n\t}\n\n\treturn memo\n}", "func Reduce(input <-chan interface{}, f ReduceFn, initial ...interface{}) (interface{}, error) {\n\tvar init interface{}\n\tif len(initial) > 0 {\n\t\tinit = initial[0]\n\t} else {\n\t\tfor x := range input {\n\t\t\tinit = x\n\t\t\tbreak\n\t\t}\n\t}\n\n\tacc := init\n\n\tfor x := range input {\n\t\tv, err := f(acc, x)\n\t\tif err != nil {\n\t\t\treturn acc, err\n\t\t}\n\t\tacc = v\n\t}\n\n\treturn acc, nil\n}", "func DIVB(mr operand.Op) { ctx.DIVB(mr) }", "func (v Vec) Reduce(f func(accum, elem float64) float64, startVal float64) float64 {\n\taccum := startVal\n\tfor _, val := range v {\n\t\taccum = f(accum, val)\n\t}\n\treturn accum\n}", "func Reduce(c Context, op string, v Value) Value {\n\t// We must be right associative; that is the grammar.\n\t// -/1 2 3 == 1-2-3 is 1-(2-3) not (1-2)-3. Answer: 2.\n\tswitch v := v.(type) {\n\tcase Int, BigInt, BigRat:\n\t\treturn v\n\tcase Vector:\n\t\tif len(v) == 0 {\n\t\t\treturn v\n\t\t}\n\t\tacc := v[len(v)-1]\n\t\tfor i := len(v) - 2; i >= 0; i-- {\n\t\t\tacc = c.EvalBinary(v[i], op, acc)\n\t\t}\n\t\treturn acc\n\tcase *Matrix:\n\t\tif v.Rank() < 2 {\n\t\t\tErrorf(\"shape for matrix is degenerate: %s\", NewIntVector(v.shape))\n\t\t}\n\t\tstride := v.shape[v.Rank()-1]\n\t\tif stride == 0 {\n\t\t\tErrorf(\"shape for matrix is degenerate: %s\", NewIntVector(v.shape))\n\t\t}\n\t\tshape := v.shape[:v.Rank()-1]\n\t\tdata := make(Vector, size(shape))\n\t\tindex := 0\n\t\tfor i := range data {\n\t\t\tpos := index + stride - 1\n\t\t\tacc := v.data[pos]\n\t\t\tpos--\n\t\t\tfor i := 1; i < stride; i++ {\n\t\t\t\tacc = c.EvalBinary(v.data[pos], op, acc)\n\t\t\t\tpos--\n\t\t\t}\n\t\t\tdata[i] = acc\n\t\t\tindex += stride\n\t\t}\n\t\tif len(shape) == 1 { // TODO: Matrix.shrink()?\n\t\t\treturn NewVector(data)\n\t\t}\n\t\treturn NewMatrix(shape, data)\n\t}\n\tErrorf(\"can't do reduce on %s\", whichType(v))\n\tpanic(\"not reached\")\n}", "func Sum(input []float64) (sum float64) {\n\tfor _, v := range input {\n\t\tvar fuel float64\n\t\tfuel += calculator(v, fuel)\n\t\tsum += fuel\n\t}\n\treturn sum\n}", "func VREDUCESS_Z(i, mx, x, k, x1 operand.Op) { ctx.VREDUCESS_Z(i, mx, x, k, x1) }", "func VREDUCEPD(ops ...operand.Op) { ctx.VREDUCEPD(ops...) }", "func Reduce(series interface{}, reduceFunc interface{}, initial interface{}) (interface{}, error) {\n\treturn nil, ErrNotImplemented\n}", "func Reduce(r Reducer, d *datatransfer.Diff) (*datatransfer.Diff, error) {\n\tdiff := r.Reduce(d)\n\treturn diff, nil\n}", "func RCLB(ci, mr operand.Op) { ctx.RCLB(ci, mr) }", "func XCHGB(mr, mr1 operand.Op) { ctx.XCHGB(mr, mr1) }", "func reduceMsgTx(tx *wire.MsgTx) (in, out, fees, rate, size uint64) {\n\tfor _, txIn := range tx.TxIn {\n\t\tin += uint64(txIn.ValueIn)\n\t}\n\tfor _, txOut := range tx.TxOut {\n\t\tout += uint64(txOut.Value)\n\t}\n\tfees = in - out\n\tsize = uint64(tx.SerializeSize())\n\trate = fees / size\n\treturn\n}", "func reduceMsgTx(tx *wire.MsgTx) (in, out, fees, rate, size uint64) {\n\tfor _, txIn := range tx.TxIn {\n\t\tin += uint64(txIn.ValueIn)\n\t}\n\tfor _, txOut := range tx.TxOut {\n\t\tout += uint64(txOut.Value)\n\t}\n\tfees = in - out\n\tsize = uint64(tx.SerializeSize())\n\trate = fees / size\n\treturn\n}", "func ROLB(ci, mr operand.Op) { ctx.ROLB(ci, mr) }", "func XlaAllReduce(scope *Scope, input tf.Output, group_assignment tf.Output, reduce_op string, mode string) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"reduce_op\": reduce_op, \"mode\": mode}\n\topspec := tf.OpSpec{\n\t\tType: \"XlaAllReduce\",\n\t\tInput: []tf.Input{\n\t\t\tinput, group_assignment,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func BSFW(mr, r operand.Op) { ctx.BSFW(mr, r) }", "func (f *Regressor) Fit(X [][]float64, Y []float64) {\n\tf.NSample = len(Y)\n\n\tf.nFeatures = len(X[0])\n\n\tf.Trees = make([]*tree.Regressor, f.NTrees)\n\n\tif f.MaxFeatures < 0 {\n\t\tf.MaxFeatures = int(math.Sqrt(float64(f.nFeatures)))\n\t}\n\n\tvar oob *oobRegCtr\n\tif f.computeOOB {\n\t\toob = newOOBRegCtr(len(Y))\n\t}\n\n\tin := make(chan *fitRegTree)\n\tout := make(chan *fitRegTree)\n\n\tnWorkers := f.nWorkers\n\tif nWorkers < 1 {\n\t\tnWorkers = 1\n\t}\n\n\t// start workers\n\tfor i := 0; i < nWorkers; i++ {\n\t\tgo func(id int) {\n\t\t\tfor w := range in {\n\t\t\t\treg := tree.NewRegressor(tree.MinSplit(f.MinSplit), tree.MinLeaf(f.MinLeaf),\n\t\t\t\t\ttree.MaxDepth(f.MaxDepth), tree.MaxFeatures(f.MaxFeatures),\n\t\t\t\t\ttree.RandState(int64(id)*time.Now().UnixNano()))\n\t\t\t\treg.FitInx(X, Y, w.inx)\n\n\t\t\t\tw.t = reg\n\n\t\t\t\tif f.computeOOB {\n\t\t\t\t\toob.update(X, w.inBag, w.t)\n\t\t\t\t}\n\n\t\t\t\tout <- w\n\t\t\t}\n\t\t}(i)\n\t}\n\n\t// fill the queue\n\tgo func() {\n\t\tfor _ = range f.Trees {\n\t\t\tinx, inBag := bootstrapInx(len(X))\n\t\t\tin <- &fitRegTree{inx: inx, inBag: inBag}\n\t\t}\n\t\tclose(in)\n\t}()\n\n\tfor i := range f.Trees {\n\t\tw := <-out\n\t\tf.Trees[i] = w.t\n\t}\n\n\tif f.computeOOB {\n\t\tf.MSE, f.RSquared = oob.compute(Y)\n\t}\n}", "func (w *SimpleMapReduce) Reduce (reduceFn ReduceFn) *SimpleMapReduce {\n w.reduceFn = reduceFn\n return w\n}", "func BEXTRQ(r, mr, r1 operand.Op) { ctx.BEXTRQ(r, mr, r1) }", "func SBBL(imr, emr operand.Op) { ctx.SBBL(imr, emr) }", "func Reduce(in interface{}, memo interface{}, fn reduceFn) interface{} {\n\tresult := memo\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tresult = fn(result, val.Index(i).Interface())\n\t}\n\n\treturn result\n}", "func VPMAXUB(ops ...operand.Op) { ctx.VPMAXUB(ops...) }", "func (this *Worker) Combiner() mr.CombinerFunc {\n return this.combiner\n}", "func (cMap *MyStruct)Reduce(functor ReduceFunc, accum_str string, accum_int int) (string, int){\n\tres := new(ReduceStruct)\n\tres.accum_str = accum_str\n\tres.accum_int = accum_int\n\tcMap.reducing <- *res\n\n\tminPair := <- cMap.reduceTemp\n\n\treturn minPair.accum_str,minPair.accum_int\n}", "func (s *set) Reduce(i *Term, f func(*Term, *Term) (*Term, error)) (*Term, error) {\n\terr := s.Iter(func(x *Term) error {\n\t\tvar err error\n\t\ti, err = f(i, x)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\treturn i, err\n}", "func calcTotalBalance(chromoinfo []bybBalance) (totalBalace big.Int) {\n\n\tfor _, x := range chromoinfo {\n\t\ttotalBalace = Add(totalBalace, x.Value)\n\t}\n\treturn\n\n}", "func VREDUCEPS_BCST_Z(i, m, k, xyz operand.Op) { ctx.VREDUCEPS_BCST_Z(i, m, k, xyz) }", "func MULXL(mr, r, r1 operand.Op) { ctx.MULXL(mr, r, r1) }", "func reduceSum(key string, values []interface{}, r *reducer) {\n\tvar n float64\n\tfor _, v := range values {\n\t\tn += v.(float64)\n\t}\n\tr.emit(key, n)\n}", "func PMAXSB(mx, x operand.Op) { ctx.PMAXSB(mx, x) }", "func (f Frac) Reduce() Frac {\n\tif f.n == 0 {\n\t\treturn Frac{n: 0, d: 1}\n\t}\n\n\td := gcd(f.n, f.d)\n\n\tf1 := Frac{n: f.n / d, d: f.d / d}\n\n\tf1.normalizeSignage()\n\n\treturn f1\n}", "func prediction(xi float64) float64 {\n\treturn b0 + b1*xi\n}", "func Reduce[T any, R any](collection []T, accumulator func(R, T, int) R, initial R) R {\n\tfor i, item := range collection {\n\t\tinitial = accumulator(initial, item, i)\n\t}\n\n\treturn initial\n}", "func MULXQ(mr, r, r1 operand.Op) { ctx.MULXQ(mr, r, r1) }", "func (c *Clac) Comb() error {\n\treturn c.applyInt(2, func(vals []value.Value) (value.Value, error) {\n\t\te := &eval{}\n\t\tnf := e.e(func() (value.Value, error) { return factorial(vals[1]) })\n\t\trf := e.e(func() (value.Value, error) { return factorial(vals[0]) })\n\t\tnr := e.binary(vals[1], \"-\", vals[0])\n\t\tnrf := e.e(func() (value.Value, error) { return factorial(nr) })\n\t\tdenom := e.binary(nrf, \"*\", rf)\n\t\tn := e.binary(nf, \"/\", denom)\n\t\treturn n, e.err\n\t})\n}", "func predict(x_i interface{} , beta interface{} ) interface{} {\n//assumes that the first element of each x_i is 1\n\treturn dot(x_i,beta)\n}", "func PMAXUB(mx, x operand.Op) { ctx.PMAXUB(mx, x) }", "func Bvsum(t []TermT) TermT {\n\tcount := C.uint32_t(len(t))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_bvsum(count, (*C.term_t)(&t[0])))\n}", "func (m *Money) Reduce(bank *Bank, to string) *Money {\n\trate := bank.Rate(m.Currency(), to)\n\treturn &Money{\n\t\tamount: m.amount / rate,\n\t\tcurrency: to,\n\t}\n}", "func PMAXUW(mx, x operand.Op) { ctx.PMAXUW(mx, x) }", "func (f *Regressor) Predict(X [][]float64) []float64 {\n\tsum := make([]float64, len(X))\n\n\tfor _, t := range f.Trees {\n\t\tfor i, val := range t.Predict(X) {\n\t\t\tsum[i] += val\n\t\t}\n\t}\n\n\tfor i := range sum {\n\t\tsum[i] /= float64(f.NTrees)\n\t}\n\n\treturn sum\n}", "func (m MaterialPolynomial) ConductivityAvg(F2, F1 float64) float64 {\n\tK := make([]float64, len(m.factors))\n\tfor i := range m.factors {\n\t\tK[i] = m.factors[i]\n\t}\n\tfor i := 0; i < len(m.factors); i++ {\n\t\tK[i] *= (pow.En(F2, i+1) - pow.En(F1, i+1)) / float64(i+1)\n\t}\n\tKsum := 0.0\n\tfor i := range K {\n\t\tKsum += K[i]\n\t}\n\tKsum = Ksum / (F2 - F1)\n\treturn Ksum\n}", "func TrainNB1(trainMatrix [][]int, trainCategory []int)([]float64, []float64, float64) {\n numTrainDocs := len(trainMatrix)\n numWords := len(trainMatrix[0])\n sumCategory := calc.SumInt(trainCategory)\n \n pAbusive := float64(sumCategory) / float64(numTrainDocs)\n p0Num := make([]int, numWords)\n p1Num := make([]int, numWords)\n\n p0Denom := float64(2.0)\n p1Denom := float64(2.0)\n\n for i := 0; i < numTrainDocs; i++ {\n if trainCategory[i] == 1 {\n p1Num = calc.AddIntVec(p1Num, trainMatrix[i])\n p1Denom += float64(calc.SumInt(trainMatrix[i]))\n }else{\n p0Num = calc.AddIntVec(p0Num, trainMatrix[i])\n p0Denom += float64(calc.SumInt(trainMatrix[i])) \n }\n }\n \n fmt.Println(\"p0Num: \", p0Num)\n fmt.Println(\"p1Num: \", p1Num)\n p1Vec := calc.DivIntVec(p1Num, p1Denom)\n p0Vec := calc.DivIntVec(p0Num, p0Denom)\n \n p0Vec = LogVec(p0Vec)\n p1Vec = LogVec(p1Vec)\n\n return p0Vec, p1Vec, pAbusive\n}", "func BSFL(mr, r operand.Op) { ctx.BSFL(mr, r) }", "func PABSB(mx, x operand.Op) { ctx.PABSB(mx, x) }", "func BTCL(ir, mr operand.Op) { ctx.BTCL(ir, mr) }", "func BenchmarkPredictFull(b *testing.B) {\n\n\tmodel := &LinearSVC{\n\t\tcoefficients: Coefficients,\n\t\tintercepts: Intercepts,\n\t}\n\n\tvar internalResult int\n\tfor i := 0; i < b.N; i++ {\n\t\t// always record the result of Fib to prevent\n\t\t// the compiler eliminating the function call.\n\t\tinternalResult = model.Predict(Coefficients)\n\t}\n\n\t// always store the result to a package level variable\n\t// so the compiler cannot eliminate the Benchmark itself.\n\tresult = internalResult\n}", "func Reduce[I, A any](input <-chan I, reduceFunc func(accum A, element I) A) A {\n\tvar accum A\n\tfor element := range input {\n\t\taccum = reduceFunc(accum, element)\n\t}\n\n\treturn accum\n}", "func calculateCombinedMetric(nodeValues [][][]float64, isAverage bool) [][]float64 {\n numNodes := len(nodeValues)\n if numNodes == 0 {\n return [][]float64{}\n }\n if numNodes == 1 {\n return nodeValues[0]\n }\n // we assume all nodes have value array of same length\n numIntervals := len(nodeValues[0])\n newValues := make([][]float64, numIntervals)\n for i := 0; i < numIntervals; i++ {\n newValues[i] = []float64{nodeValues[0][i][0]}\n for j := 0; j < numNodes; j++ {\n value := nodeValues[j][i]\n if len(value) >= 2 {\n if len(newValues[i]) >= 2 {\n newValues[i][1] += value[1]\n } else {\n newValues[i] = append(newValues[i], value[1])\n }\n }\n }\n }\n if isAverage {\n for i := 0; i < numIntervals; i++ {\n if len(newValues[i]) >= 2 {\n newValues[i][1] = newValues[i][1] / float64(numNodes)\n }\n }\n }\n return newValues\n}", "func (s scope) Reduce() Expression { return s }", "func VPERMB(ops ...operand.Op) { ctx.VPERMB(ops...) }", "func _reduce(fn redfn, total int, c chan dict) dict {\n\tfinalMap := make(dict)\n\n\tfor worker := 0; worker < total; worker++ {\n\t\tm := <-c\n\t\tfn(finalMap, m)\n\t}\n\n\treturn finalMap\n}", "func eff(freq float64, fx []float64, lband int, filterType FilterType) float64 {\n\tif filterType != Differentiator {\n\t\treturn fx[lband]\n\t}\n\treturn fx[lband] * freq\n}", "func RV(rs []float64) float64 {\n\tvar sum float64\n\tfor _, r := range rs {\n\t\tsum += math.Pow(r, 2)\n\t}\n\treturn sum\n}", "func (b bills) sumTotal() float64 {\n\tvar sum float64\n\tfor i := 0; i < len(b); i++ {\n\t\tsum += b[i]\n\t}\n\treturn sum\n}", "func VREDUCEPS_Z(i, mxyz, k, xyz operand.Op) { ctx.VREDUCEPS_Z(i, mxyz, k, xyz) }", "func PSUBB(mx, x operand.Op) { ctx.PSUBB(mx, x) }", "func (z *Big) FMA(x, y, u *Big) *Big { return z.Context.FMA(z, x, y, u) }", "func ReduceSum(values []interface{}) interface{} {\n\tvar n float64\n\tcount := 0\n\tvar resultType NumberType\n\tfor _, v := range values {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcount++\n\t\tswitch n1 := v.(type) {\n\t\tcase float64:\n\t\t\tn += n1\n\t\tcase int64:\n\t\t\tn += float64(n1)\n\t\t\tresultType = Int64Type\n\t\t}\n\t}\n\tif count > 0 {\n\t\tswitch resultType {\n\t\tcase Float64Type:\n\t\t\treturn n\n\t\tcase Int64Type:\n\t\t\treturn int64(n)\n\t\t}\n\t}\n\treturn nil\n}", "func IMULB(mr operand.Op) { ctx.IMULB(mr) }", "func (m *Mare) Reduce(reduceFunc func(a, b interface{}) interface{}) map[interface{}]interface{} {\n\tresults := make(map[interface{}]interface{})\n\n\tfor item := range m.mapOutChan {\n\t\tmapItem, present := results[item.Key]\n\t\tif present {\n\t\t\tif m.trace {\n\t\t\t\tlog.Printf(\"Reducing %v with %v for key %v\", mapItem, item.Value, item.Key)\n\t\t\t}\n\t\t\tresults[item.Key] = reduceFunc(mapItem, item.Value)\n\t\t} else {\n\t\t\tif m.trace {\n\t\t\t\tlog.Printf(\"Saving %v for key %v\", item.Value, item.Key)\n\t\t\t}\n\t\t\tresults[item.Key] = item.Value\n\t\t}\n\t}\n\n\treturn results\n}", "func (m *MultilinearByValues) Fold(cs *frontend.ConstraintSystem, x frontend.Variable) {\n\tk := len(m.Table) / 2\n\tfor i := 0; i < k; i++ {\n\t\ttmpLinExp := cs.Sub(m.Table[i+k], m.Table[i])\n\t\t// cs.LinearExpression(\n\t\t// \tcs.Term(m.Table[i+k], big.NewInt(1)),\n\t\t// \tcs.Term(m.Table[i], big.NewInt(-1)),\n\t\t// )\n\t\ttmp := cs.Mul(tmpLinExp, x)\n\t\t// Ideally we replace this by a r1c.LinearExpression too ...\n\t\tm.Table[i] = cs.Add(m.Table[i], tmp)\n\t}\n\tm.Table = m.Table[:k]\n}", "func combinefue(mstf map[int]float64, lcs Loadcases) map[uint32]float64 {\n\tmcombstress := make(map[uint32]float64)\n\tvar sums, fuestress float64\n\tfor _, combl := range lcs.Loadcases {\n\t\tsums = 0\n\n\t\tunilcs := combl.Unilcs\n\t\tfor _, unilc := range unilcs {\n\t\t\tfuestress = mstf[unilc.Fueid]\n\t\t\tsums += unilc.Factor * fuestress\n\t\t}\n\t\tmcombstress[combl.Lcid] = sums\n\t}\n\t//fmt.Println(mcombstress)\n\treturn mcombstress\n}", "func calcTrendGrowthMultipleRegressionPart2(bConstant, bGrowth bool, mtxY, mtxX, newX, mtxRes [][]float64, meanY float64, nCXN, K, N int) {\n\tvecR := make([]float64, N) // for QR decomposition\n\tmeans := getNewMatrix(K, 1) // mean of each row\n\tslopes := getNewMatrix(K, 1) // row from b1 to bK\n\tif len(means) == 0 || len(slopes) == 0 {\n\t\treturn\n\t}\n\tif bConstant {\n\t\tcalcRowMeans(mtxX, means, N, K)\n\t\tcalcRowsDelta(mtxX, means, N, K)\n\t}\n\tif !calcColQRDecomposition(mtxX, vecR, K, N) {\n\t\treturn\n\t}\n\t// later on we will divide by elements of vecR, so make sure that they aren't zero\n\tbIsSingular := false\n\tfor row := 0; row < K && !bIsSingular; row++ {\n\t\tbIsSingular = bIsSingular || vecR[row] == 0\n\t}\n\tif bIsSingular {\n\t\treturn\n\t}\n\tfor row := 0; row < K; row++ {\n\t\tcalcApplyColsHouseholderTransformation(mtxX, row, mtxY, N)\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tputDouble(slopes, col, getDouble(mtxY, col))\n\t}\n\tcalcSolveWithUpperRightTriangle(mtxX, vecR, slopes, K, true)\n\t// fill result matrix\n\tcalcFastMult(slopes, newX, mtxRes, 1, K, nCXN)\n\tif bConstant {\n\t\tfIntercept := meanY - calcSumProduct(means, slopes, K)\n\t\tfor col := 0; col < nCXN; col++ {\n\t\t\tmtxRes[col][0] = mtxRes[col][0] + fIntercept\n\t\t}\n\t}\n\tif bGrowth {\n\t\tfor i := 0; i < nCXN; i++ {\n\t\t\tputDouble(mtxRes, i, math.Exp(getDouble(mtxRes, i)))\n\t\t}\n\t}\n}", "func BLSRQ(mr, r operand.Op) { ctx.BLSRQ(mr, r) }", "func ADDSUBPS(mx, x operand.Op) { ctx.ADDSUBPS(mx, x) }", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func ReduceErr(in interface{}, memo interface{}, fn reduceFnErr) (interface{}, error) {\n\tvar err error\n\tresult := memo\n\tval := reflect.ValueOf(in)\n\n\tfor i := 0; i < val.Len(); i++ {\n\t\tresult, err = fn(result, val.Index(i).Interface())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func MOVBLZX(mr, r operand.Op) { ctx.MOVBLZX(mr, r) }", "func VPERMILPS(ops ...operand.Op) { ctx.VPERMILPS(ops...) }", "func VPMAXUW(ops ...operand.Op) { ctx.VPMAXUW(ops...) }", "func MAXPS(mx, x operand.Op) { ctx.MAXPS(mx, x) }", "func (l *Layer) BatchR(rv autofunc.RVector, in autofunc.RResult, n int) autofunc.RResult {\n\tif l.DoneTraining {\n\t\tf := autofunc.RFuncBatcher{F: l}\n\t\treturn f.BatchR(rv, in, n)\n\t}\n\tif len(in.Output())%l.InputCount != 0 {\n\t\tpanic(\"invalid input size\")\n\t}\n\tn = len(in.Output()) / l.InputCount\n\treturn autofunc.PoolR(in, func(in autofunc.RResult) autofunc.RResult {\n\t\tvar mean autofunc.RResult\n\t\tvar variance autofunc.RResult\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvec := autofunc.SliceR(in, i*l.InputCount, (i+1)*l.InputCount)\n\t\t\tif mean == nil {\n\t\t\t\tmean = vec\n\t\t\t} else {\n\t\t\t\tmean = autofunc.AddR(mean, vec)\n\t\t\t}\n\t\t\tif variance == nil {\n\t\t\t\tvariance = autofunc.MulR(vec, vec)\n\t\t\t} else {\n\t\t\t\tvariance = autofunc.AddR(variance, autofunc.MulR(vec, vec))\n\t\t\t}\n\t\t}\n\t\tmean = autofunc.ScaleR(mean, 1/float64(n))\n\t\tvariance = autofunc.ScaleR(variance, 1/float64(n))\n\t\tmeanSquared := autofunc.SquareR(mean)\n\t\tvariance = autofunc.AddR(variance, autofunc.ScaleR(meanSquared, -1))\n\n\t\tnegMean := autofunc.RepeatR(autofunc.ScaleR(mean, -1), n)\n\t\tinvStd := autofunc.RepeatR(autofunc.PowR(autofunc.AddScalerR(variance,\n\t\t\tl.stabilizer()), -0.5), n)\n\t\tnormalized := autofunc.MulR(autofunc.AddR(in, negMean), invStd)\n\t\tscales := autofunc.RepeatR(autofunc.NewRVariable(l.Scales, rv), n)\n\t\tbiases := autofunc.RepeatR(autofunc.NewRVariable(l.Biases, rv), n)\n\t\treturn autofunc.AddR(autofunc.MulR(normalized, scales), biases)\n\t})\n}" ]
[ "0.5845267", "0.5497636", "0.54155177", "0.5325984", "0.50295204", "0.4979466", "0.49479905", "0.4896068", "0.489074", "0.48677424", "0.48512495", "0.4814495", "0.48057783", "0.47650486", "0.47615904", "0.47364292", "0.47128627", "0.4706833", "0.4668748", "0.46511766", "0.464172", "0.46326318", "0.46160528", "0.46021006", "0.4597612", "0.45917854", "0.45904616", "0.4571763", "0.4569293", "0.45633167", "0.45320708", "0.453071", "0.45301658", "0.45181972", "0.4516777", "0.4512664", "0.45048943", "0.4489685", "0.44895166", "0.44895166", "0.44824958", "0.4470356", "0.44673306", "0.44623327", "0.44565022", "0.44289878", "0.44227484", "0.44224846", "0.44193307", "0.4417803", "0.44173065", "0.44146776", "0.44100562", "0.44085884", "0.44047034", "0.438518", "0.43849534", "0.4369422", "0.43645313", "0.4351859", "0.43385217", "0.43380883", "0.43371606", "0.4337057", "0.43354434", "0.43351737", "0.4330949", "0.43249962", "0.43246132", "0.43242598", "0.4321561", "0.4320543", "0.43169028", "0.43112928", "0.43098527", "0.4306714", "0.429636", "0.42930487", "0.4293029", "0.4284483", "0.42828396", "0.42741555", "0.42675176", "0.42551103", "0.4238514", "0.42245448", "0.42187074", "0.42062888", "0.41952115", "0.418984", "0.41891256", "0.41884267", "0.41769022", "0.41739365", "0.41737366", "0.41698188", "0.41626337", "0.4161342", "0.41591886", "0.4159146" ]
0.62120545
0
freeze calls Freeze on each coef
func (p *Poly) freeze() { for i := 0; i < n; i++ { p[i] = freeze(p[i]) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *chainFreezer) freeze(db database.KeyValueStore) {\n\tnfdb := &nofreezedb{KeyValueStore: db}\n\n\tvar (\n\t\tbackoff bool\n\t\ttriggered chan struct{} // Used in tests\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-f.quit:\n\t\t\tlog.Info(\"Freezer shutting down\")\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif backoff {\n\t\t\t// If we were doing a manual trigger, notify it\n\t\t\tif triggered != nil {\n\t\t\t\ttriggered <- struct{}{}\n\t\t\t\ttriggered = nil\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-time.NewTimer(freezerRecheckInterval).C:\n\t\t\t\tbackoff = false\n\t\t\tcase triggered = <-f.trigger:\n\t\t\t\tbackoff = false\n\t\t\tcase <-f.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Retrieve the freezing threshold.\n\t\thash := ReadHeadBlockHash(nfdb)\n\t\tif hash == (common.Hash{}) {\n\t\t\tlog.Debug(\"Current full block hash unavailable\") // new chain, empty database\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\tnumber := ReadHeaderNumber(nfdb, hash)\n\t\tthreshold := atomic.LoadUint64(&f.threshold)\n\t\tfrozen := atomic.LoadUint64(&f.frozen)\n\t\tswitch {\n\t\tcase number == nil:\n\t\t\tlog.Error(\"Current full block number unavailable\", \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number < threshold:\n\t\t\tlog.Debug(\"Current full block not old enough\", \"number\", *number, \"hash\", hash, \"delay\", threshold)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number-threshold <= frozen:\n\t\t\tlog.Debug(\"Ancient blocks frozen already\", \"number\", *number, \"hash\", hash, \"frozen\", frozen)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\thead := ReadHeader(nfdb, hash, *number)\n\t\tif head == nil {\n\t\t\tlog.Error(\"Current full block unavailable\", \"number\", *number, \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Seems we have data ready to be frozen, process in usable batches\n\t\tvar (\n\t\t\tstart = time.Now()\n\t\t\tfirst, _ = f.Ancients()\n\t\t\tlimit = *number - threshold\n\t\t)\n\t\tif limit-first > freezerBatchLimit {\n\t\t\tlimit = first + freezerBatchLimit\n\t\t}\n\t\tancients, err := f.freezeRange(nfdb, first, limit)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error in block freeze operation\", \"err\", err)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Batch of blocks have been frozen, flush them before wiping from leveldb\n\t\tif err := f.Sync(); err != nil {\n\t\t\tlog.Critical(\"Failed to flush frozen tables\", \"err\", err)\n\t\t}\n\n\t\t// Wipe out all data from the active database\n\t\tbatch := db.NewBatch()\n\t\tfor i := 0; i < len(ancients); i++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif first+uint64(i) != 0 {\n\t\t\t\tDeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i))\n\t\t\t\tDeleteCanonicalHash(batch, first+uint64(i))\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen canonical blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Wipe out side chains also and track dangling side chains\n\t\tvar dangling []common.Hash\n\t\tfrozen = atomic.LoadUint64(&f.frozen) // Needs reload after during freezeRange\n\t\tfor number := first; number < frozen; number++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif number != 0 {\n\t\t\t\tdangling = ReadAllHashes(db, number)\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Deleting side chain\", \"number\", number, \"hash\", hash)\n\t\t\t\t\tDeleteBlock(batch, hash, number)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen side blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Step into the future and delete and dangling side chains\n\t\tif frozen > 0 {\n\t\t\ttip := frozen\n\t\t\tfor len(dangling) > 0 {\n\t\t\t\tdrop := make(map[common.Hash]struct{})\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Dangling parent from Freezer\", \"number\", tip-1, \"hash\", hash)\n\t\t\t\t\tdrop[hash] = struct{}{}\n\t\t\t\t}\n\t\t\t\tchildren := ReadAllHashes(db, tip)\n\t\t\t\tfor i := 0; i < len(children); i++ {\n\t\t\t\t\t// Dig up the child and ensure it's dangling\n\t\t\t\t\tchild := ReadHeader(nfdb, children[i], tip)\n\t\t\t\t\tif child == nil {\n\t\t\t\t\t\tlog.Error(\"Missing dangling header\", \"number\", tip, \"hash\", children[i])\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := drop[child.ParentHash]; !ok {\n\t\t\t\t\t\tchildren = append(children[:i], children[i+1:]...)\n\t\t\t\t\t\ti--\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// Delete all block data associated with the child\n\t\t\t\t\tlog.Debug(\"Deleting dangling block\", \"number\", tip, \"hash\", children[i], \"parent\", child.ParentHash)\n\t\t\t\t\tDeleteBlock(batch, children[i], tip)\n\t\t\t\t}\n\t\t\t\tdangling = children\n\t\t\t\ttip++\n\t\t\t}\n\t\t\tif err := batch.Write(); err != nil {\n\t\t\t\tlog.Critical(\"Failed to delete dangling side blocks\", \"err\", err)\n\t\t\t}\n\t\t}\n\n\t\t// Log something friendly for the user\n\t\tcontext := []interface{}{\n\t\t\t\"blocks\", frozen - first, \"elapsed\", common.PrettyDuration(time.Since(start)), \"number\", frozen - 1,\n\t\t}\n\t\tif n := len(ancients); n > 0 {\n\t\t\tcontext = append(context, []interface{}{\"hash\", ancients[n-1]}...)\n\t\t}\n\t\tlog.Infof(\"Deep froze chain segment: %+v\", context...)\n\n\t\t// Avoid database thrashing with tiny writes\n\t\tif frozen-first < freezerBatchLimit {\n\t\t\tbackoff = true\n\t\t}\n\t}\n}", "func (i *Index) Freeze() {\n\ti.frozen = true\n}", "func (i *Instance) Freeze() {\n}", "func (df *DataFrame) Freeze() { df.frozen = true }", "func (r *RunCtx) Freeze() {\n}", "func (s *Sub) Freeze() {}", "func (sa *SuffixArray) Freeze() error { return sa.ba.Freeze() }", "func (t *Target) Freeze() {}", "func freeze(o *goja.Object) {\n\tfor _, key := range o.Keys() {\n\t\to.DefineDataProperty(key, o.Get(key), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE)\n\t}\n}", "func (recv *Object) FreezeNotify() {\n\tC.g_object_freeze_notify((*C.GObject)(recv.native))\n\n\treturn\n}", "func (o *GradientDescent) updateParamsSerial() {\n\tfor param := range o.observed {\n\t\tif param.HasGrad() {\n\t\t\tdelta := o.method.Delta(param) // important: don't release delta here\n\t\t\tparam.ApplyDelta(delta)\n\t\t}\n\t}\n}", "func (g *metadataGraph) freeze(ctx context.Context) {\n\tg.root.freeze(ctx)\n}", "func freezetheworld() {\n\tatomic.Store(&freezing, 1)\n\t// stopwait and preemption requests can be lost\n\t// due to races with concurrently executing threads,\n\t// so try several times\n\tfor i := 0; i < 5; i++ {\n\t\t// this should tell the scheduler to not start any new goroutines\n\t\tsched.stopwait = freezeStopWait\n\t\tatomic.Store(&sched.gcwaiting, 1)\n\t\t// this should stop running goroutines\n\t\tif !preemptall() {\n\t\t\tbreak // no running goroutines\n\t\t}\n\t\tusleep(1000)\n\t}\n\t// to be sure\n\tusleep(1000)\n\tpreemptall()\n\tusleep(1000)\n}", "func (_OracleMgr *OracleMgrCaller) FreezePeriod(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _OracleMgr.contract.Call(opts, out, \"freezePeriod\")\n\treturn *ret0, err\n}", "func (p Path) Freeze() {}", "func (s *inMemSpannerServer) Unfreeze() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tclose(s.freezed)\n}", "func testModel(weights []float64) float64 {\n\n\truntime.LockOSThread()\n\n\t_gstate := python.PyGILState_Ensure()\n\n\targArray := python.PyList_New(len(weights))\n\n\tfor i := 0; i < len(weights); i++ {\n\t\tpython.PyList_SetItem(argArray, i, python.PyFloat_FromDouble(weights[i]))\n\t}\n\n\tvar trainErr float64\n\tpyTrainResult := pyTrainFunc.CallFunction(argArray)\n\ttrainErr = python.PyFloat_AsDouble(pyTrainResult)\n\n\tpython.PyGILState_Release(_gstate)\t\n\n\treturn trainErr\n\n}", "func (*CapturedStacktrace) Freeze() {}", "func NewFreezeParams() *FreezeParams {\n\treturn &FreezeParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (rbm *RBM) FreeEnergy(v []float64) float64 {\n\tenergy := 0.0\n\n\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\tenergy -= rbm.B[j] * v[j]\n\t}\n\n\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\tsum := rbm.C[i]\n\t\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\t\tsum += rbm.W[i][j] * v[j]\n\t\t}\n\t\tenergy -= math.Log(1 + math.Exp(sum))\n\t}\n\n\treturn energy\n}", "func SyncRuntimeDoSpin()", "func (b Bonds) FillCurrentPrice() {\n\tvar wg sync.WaitGroup\n\tfor i := range b {\n\t\twg.Add(1)\n\t\tgo func(bond *Bond) {\n\t\t\tif err := fillCurrentBondPrice(bond); err != nil {\n\t\t\t\tlog.Printf(\"failed to retrieve the last bond price: %s\", err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(&b[i])\n\t}\n\twg.Wait()\n}", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func (_OracleMgr *OracleMgrCallerSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (n *metadataNode) freeze(ctx context.Context) {\n\tn.assertNonFrozen()\n\n\t// md may be already non-nil for the root, this is fine.\n\tif n.md == nil {\n\t\tn.md = mergeIntoPrefixMetadata(ctx, n.prefix, n.acls)\n\t}\n\tn.acls = nil // mark as frozen, release unnecessary memory\n\n\tfor _, child := range n.children {\n\t\tchild.freeze(ctx)\n\t}\n}", "func (f *Regressor) Fit(X [][]float64, Y []float64) {\n\tf.NSample = len(Y)\n\n\tf.nFeatures = len(X[0])\n\n\tf.Trees = make([]*tree.Regressor, f.NTrees)\n\n\tif f.MaxFeatures < 0 {\n\t\tf.MaxFeatures = int(math.Sqrt(float64(f.nFeatures)))\n\t}\n\n\tvar oob *oobRegCtr\n\tif f.computeOOB {\n\t\toob = newOOBRegCtr(len(Y))\n\t}\n\n\tin := make(chan *fitRegTree)\n\tout := make(chan *fitRegTree)\n\n\tnWorkers := f.nWorkers\n\tif nWorkers < 1 {\n\t\tnWorkers = 1\n\t}\n\n\t// start workers\n\tfor i := 0; i < nWorkers; i++ {\n\t\tgo func(id int) {\n\t\t\tfor w := range in {\n\t\t\t\treg := tree.NewRegressor(tree.MinSplit(f.MinSplit), tree.MinLeaf(f.MinLeaf),\n\t\t\t\t\ttree.MaxDepth(f.MaxDepth), tree.MaxFeatures(f.MaxFeatures),\n\t\t\t\t\ttree.RandState(int64(id)*time.Now().UnixNano()))\n\t\t\t\treg.FitInx(X, Y, w.inx)\n\n\t\t\t\tw.t = reg\n\n\t\t\t\tif f.computeOOB {\n\t\t\t\t\toob.update(X, w.inBag, w.t)\n\t\t\t\t}\n\n\t\t\t\tout <- w\n\t\t\t}\n\t\t}(i)\n\t}\n\n\t// fill the queue\n\tgo func() {\n\t\tfor _ = range f.Trees {\n\t\t\tinx, inBag := bootstrapInx(len(X))\n\t\t\tin <- &fitRegTree{inx: inx, inBag: inBag}\n\t\t}\n\t\tclose(in)\n\t}()\n\n\tfor i := range f.Trees {\n\t\tw := <-out\n\t\tf.Trees[i] = w.t\n\t}\n\n\tif f.computeOOB {\n\t\tf.MSE, f.RSquared = oob.compute(Y)\n\t}\n}", "func (p *Perceptron) Fit(X [][]float64, y []int, nThreads int) {\n\tauxW := make([]float64, len(X[0])+1)\n\tp.w = append(p.w, auxW...)\n\tsubSetLen := int(len(X) / nThreads)\n\tchans := make([]chan []float64, nThreads)\n\tfor i := range chans {\n\t\tchans[i] = make(chan []float64)\n\t}\n\tfor i := 0; i < nThreads; i++ {\n\t\tgo p.ConcurrentForPerceptron(X[i*subSetLen:(i+1)*subSetLen], y[i*subSetLen:(i+1)*subSetLen], chans[i])\n\t}\n\tfor i := 0; i < nThreads; i++ {\n\t\tsubWeights := <-chans[i]\n\t\tfor j, newW := range subWeights {\n\t\t\tp.w[j] += newW\n\t\t}\n\t}\n}", "func (poly *PolynomialFeatures) Fit(Xmatrix, Ymatrix mat.Matrix) base.Fiter {\n\tX := base.ToDense(Xmatrix)\n\t_, nFeatures := X.Dims()\n\tpoly.Powers = make([][]int, 0)\n\tcomb := combinationsWithReplacement\n\tif poly.InteractionOnly {\n\t\tcomb = combinations\n\t}\n\tstart := 0\n\tif !poly.IncludeBias {\n\t\tstart = 1\n\t}\n\tfor i := start; i <= poly.Degree; i++ {\n\t\tfor c := range comb(intrange(nFeatures), i) {\n\t\t\tpoly.Powers = append(poly.Powers, bincount(c, nFeatures))\n\t\t}\n\t}\n\treturn poly\n}", "func oneGradientStep(globalW []float64) ([]float64, error) {\n\n\truntime.LockOSThread()\n\n\t_gstate := python.PyGILState_Ensure()\n\n\targArray := python.PyList_New(len(globalW))\n\n\tfor i := 0; i < len(globalW); i++ {\n\t\tpython.PyList_SetItem(argArray, i, python.PyFloat_FromDouble(globalW[i]))\n\t}\n\t\n\tvar result *python.PyObject\n\tresult = pyPrivFunc.CallFunction(argArray)\n\n\toutLog.Printf(\"Result from python is:%s\", result)\n\n\t// Convert the resulting array to a go byte array\n\tpyByteArray := python.PyByteArray_FromObject(result)\n\tgoByteArray := python.PyByteArray_AsBytes(pyByteArray)\n\n\t// outLog.Printf(\"GoByte is:%s\", goByteArray)\n\n\tpython.PyGILState_Release(_gstate)\n\n\tvar goFloatArray []float64\n\tsize := len(goByteArray) / 8\n\n\tfor i := 0; i < size; i++ {\n\t\tcurrIndex := i * 8\n\t\tbits := binary.LittleEndian.Uint64(goByteArray[currIndex : currIndex+8])\n\t\taFloat := math.Float64frombits(bits)\n\t\tgoFloatArray = append(goFloatArray, aFloat)\n\t}\n\n\t// outLog.Printf(\"GoFloat is:%s\", goFloatArray)\n\n\n\treturn goFloatArray, nil\n\n}", "func (s *Service) Frozen(ctx context.Context, req *pb.FrozenRequest) (*pb.FrozenResponse, error) {\n\tif !strings.HasPrefix(strings.Title(req.Address), \"Mx\") {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid address\")\n\t}\n\n\tcState := s.blockchain.CurrentState()\n\tcState.RLock()\n\tdefer cState.RUnlock()\n\n\tvar reqCoin *coins.Model\n\n\tif req.CoinId != nil {\n\t\tcoinID := types.CoinID(req.CoinId.GetValue())\n\t\treqCoin = cState.Coins().GetCoin(coinID)\n\t\tif reqCoin == nil {\n\t\t\treturn nil, s.createError(status.New(codes.NotFound, \"Coin not found\"), transaction.EncodeError(code.NewCoinNotExists(\"\", coinID.String())))\n\t\t}\n\t}\n\tvar frozen []*pb.FrozenResponse_Frozen\n\n\tcState.FrozenFunds().GetFrozenFunds(s.blockchain.Height())\n\n\tfor i := s.blockchain.Height(); i <= s.blockchain.Height()+candidates.UnbondPeriod; i++ {\n\n\t\tif timeoutStatus := s.checkTimeout(ctx); timeoutStatus != nil {\n\t\t\treturn nil, timeoutStatus.Err()\n\t\t}\n\n\t\tfunds := cState.FrozenFunds().GetFrozenFunds(i)\n\t\tif funds == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, fund := range funds.List {\n\t\t\tif fund.Address.String() != req.Address {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin := reqCoin\n\t\t\tif coin == nil {\n\t\t\t\tcoin = cState.Coins().GetCoin(fund.Coin)\n\t\t\t} else {\n\t\t\t\tif coin.ID() != fund.Coin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrozen = append(frozen, &pb.FrozenResponse_Frozen{\n\t\t\t\tHeight: funds.Height(),\n\t\t\t\tAddress: fund.Address.String(),\n\t\t\t\tCandidateKey: fund.CandidateKey.String(),\n\t\t\t\tCoin: &pb.Coin{\n\t\t\t\t\tId: uint64(fund.Coin),\n\t\t\t\t\tSymbol: coin.GetFullSymbol(),\n\t\t\t\t},\n\t\t\t\tValue: fund.Value.String(),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &pb.FrozenResponse{Frozen: frozen}, nil\n}", "func Freeze(x int32) int32 {\n\tx -= 9829 * ((13*x) >> 17)\n\tx -= 9829 * ((427*x + 2097152) >> 22)\n\ty := x + 9829\n\tv := subtle.ConstantTimeLessOrEq(int(x), -1)\n\treturn int32(subtle.ConstantTimeSelect(v, int(y), int(x)))\n}", "func (gg GlobGroup) Freeze() {}", "func (c *TickMap) Freeze() []string {\n\tc.mlock.Lock()\n\tdefer c.mlock.Unlock()\n\ts := make([]string, len(c.m))\n\ti := 0\n\tfor key, _ := range c.m {\n\t\ts[i] = key\n\t\ti++\n\t}\n\treturn s\n}", "func (iv *writeOnlyInterval) freeze(s *Schema) (*Interval, error) {\n\tif err := iv.closeCurrentSegment(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv.Segments = make([]*Segment, iv.NumSegments)\n\tfor i := 0; i < iv.NumSegments; i++ {\n\t\tif !iv.DiskBacked {\n\t\t\tiv.Segments[i] = &Segment{Bytes: iv.buffers[i].Bytes()}\n\t\t\tcontinue\n\t\t}\n\t\tfilename := iv.SegmentFilename(s, i)\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmapped, err := mmap.Map(f, mmap.RDONLY, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tiv.Segments[i] = &Segment{File: f, Bytes: mapped}\n\t}\n\treturn &iv.Interval, nil\n}", "func (model *Model) Free() {\n\tif model == nil {\n\t\treturn\n\t}\n\tC.GRBfreemodel(model.model)\n}", "func (s *Solver) ClearBarriers() {\n\tfor y := 0; y < s.ydim; y++ {\n\t\tfor x := 0; x < s.xdim; x++ {\n\t\t\ts.barrier[x+y*s.xdim] = false\n\t\t}\n\t}\n}", "func (c *Container) Freeze() *Container {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tif c.flags&flagDirty != 0 {\n\t\tif roaringParanoia {\n\t\t\tpanic(\"freezing dirty container\")\n\t\t}\n\t\t// c.Repair won't work if this is already frozen, but in\n\t\t// theory that can't happen?\n\t\tc.Repair()\n\t}\n\t// don't need to freeze\n\tif c.flags&flagFrozen != 0 {\n\t\treturn c\n\t}\n\tc.flags |= flagFrozen\n\treturn c\n}", "func (l *LinearRegression) Fit(x [][]float64, y []float64) {\n\tvar nIter int\n\tif l.NIter <= 0 {\n\t\tnIter = 200\n\t} else {\n\t\tnIter = l.NIter\n\t}\n\n\tif l.Method == \"gd\" || l.Method == \"\" {\n\t\tl.Weights = gdSolver(x, y, nIter, 0.01)\n\t} else if l.Method == \"sls\" {\n\t\tl.Weights = slsSolver(x, y)\n\t}\n}", "func busyloop() {\n\tfor {\n\t\tif *localWork {\n\t\t\tfor i := 0; i < 100*(1<<16); i++ {\n\t\t\t}\n\t\t}\n\t\tfoo1(100)\n\t\tfoo2(*skew)\n\t\t// Yield so that some preemption happens.\n\t\truntime.Gosched()\n\t}\n}", "func AxpyLoop(c, b []float64, s float64, bc, cib, bib, blockSize int)", "func BenchmarkPredictFull(b *testing.B) {\n\n\tmodel := &LinearSVC{\n\t\tcoefficients: Coefficients,\n\t\tintercepts: Intercepts,\n\t}\n\n\tvar internalResult int\n\tfor i := 0; i < b.N; i++ {\n\t\t// always record the result of Fib to prevent\n\t\t// the compiler eliminating the function call.\n\t\tinternalResult = model.Predict(Coefficients)\n\t}\n\n\t// always store the result to a package level variable\n\t// so the compiler cannot eliminate the Benchmark itself.\n\tresult = internalResult\n}", "func (_OracleMgr *OracleMgrSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (r1cs *R1CS) mulWireByCoeff(res *fr.Element, t r1c.Term) *fr.Element {\n\tcoeffValue := t.CoeffValue()\n\tswitch coeffValue {\n\tcase 1:\n\t\treturn res\n\tcase -1:\n\t\treturn res.Neg(res)\n\tcase 0:\n\t\treturn res.SetZero()\n\tcase 2:\n\t\treturn res.Double(res)\n\tdefault:\n\t\treturn res.Mul(res, &r1cs.Coefficients[t.CoeffID()])\n\t}\n}", "func calcTrendGrowthMultipleRegressionPart1(bConstant, bGrowth bool, mtxY, mtxX, newX, mtxRes [][]float64, meanY float64, RXN, K, N int) {\n\tvecR := make([]float64, N) // for QR decomposition\n\tmeans := getNewMatrix(K, 1) // mean of each column\n\tslopes := getNewMatrix(1, K) // from b1 to bK\n\tif len(means) == 0 || len(slopes) == 0 {\n\t\treturn\n\t}\n\tif bConstant {\n\t\tcalcColumnMeans(mtxX, means, K, N)\n\t\tcalcColumnsDelta(mtxX, means, K, N)\n\t}\n\tif !calcRowQRDecomposition(mtxX, vecR, K, N) {\n\t\treturn\n\t}\n\t// Later on we will divide by elements of vecR, so make sure that they aren't zero.\n\tbIsSingular := false\n\tfor row := 0; row < K && !bIsSingular; row++ {\n\t\tbIsSingular = bIsSingular || vecR[row] == 0\n\t}\n\tif bIsSingular {\n\t\treturn\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tcalcApplyRowsHouseholderTransformation(mtxX, col, mtxY, N)\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tputDouble(slopes, col, getDouble(mtxY, col))\n\t}\n\tcalcSolveWithUpperRightTriangle(mtxX, vecR, slopes, K, false)\n\t// Fill result matrix\n\tcalcFastMult(newX, slopes, mtxRes, RXN, K, 1)\n\tif bConstant {\n\t\tintercept := meanY - calcSumProduct(means, slopes, K)\n\t\tfor row := 0; row < RXN; row++ {\n\t\t\tmtxRes[0][row] = mtxRes[0][row] + intercept\n\t\t}\n\t}\n\tif bGrowth {\n\t\tfor i := 0; i < RXN; i++ {\n\t\t\tputDouble(mtxRes, i, math.Exp(getDouble(mtxRes, i)))\n\t\t}\n\t}\n}", "func Render(i Image, nMax uint, fn Fractaler) Fractal {\n nCPU := runtime.GOMAXPROCS(0)\n\txStep, yStep := i.Scale()\n\tf := NewFractal(i.W, i.H)\n\n\t// points are fed through in to be computed then to d to be written to memory\n\tprein := make(chan point, nCPU)\n\tin := make(chan point, nCPU)\n\td := make(chan point, nCPU)\n\tpcount, icount, count := 0, 0, 0 // used to coordinate the closing of d\n\n\t// create the raw points\n\tgo func() {\n\t\tfor x := uint(0); x < i.W; x = x + 1 {\n\t\t\tgo func(x uint) {\n\t\t\t\tfor y := uint(0); y < i.H; y = y + 1 {\n\t\t\t\t\tprein <- point{x: x, y: y}\n\t\t\t\t}\n\t\t\t\tif pcount+1 == int(i.W) {\n\t\t\t\t\tclose(prein)\n\t\t\t\t}\n\t\t\t\tpcount = pcount + 1\n\t\t\t}(x)\n\t\t}\n\t}()\n\n\t//Create the complex numbers\n\tfor j := 0; j < nCPU; j = j + 1 {\n\t\tgo func() {\n\t\t\tfor p := range prein {\n\t\t\t\tp.c = i.P1 - complex(float64(p.x)*xStep, float64(p.y)*yStep)\n\t\t\t\tin <- p\n\t\t\t}\n\t\t\tif icount+1 == nCPU {\n\t\t\t\tclose(in)\n\t\t\t}\n\t\t\ticount = icount + 1\n\t\t}()\n\t}\n\n\t// Start the worker functions who perform the calculations\n\tfor i := 0; i < nCPU; i = i + 1 {\n\t\tgo func() {\n\t\t\tfor p := range in {\n\t\t\t\tz := complex128(0)\n\t\t\t\tfor p.n = 1; p.n < nMax && fn.CheckBounds(z); p.n = p.n + 1 {\n\t\t\t\t\tz = fn.Iterate(z, p.c)\n\t\t\t\t}\n\t\t\t\td <- p\n\t\t\t}\n\t\t\tif count+1 == nCPU {\n\t\t\t\tclose(d)\n\t\t\t}\n\t\t\tcount = count + 1\n\t\t}()\n\t}\n\n\t// Enter the data into the array as it comes out\n\tfor p := range d {\n\t\tf.Data[p.x][p.y] = p.n\n\t}\n\n\treturn f\n}", "func (state *State) Constrain(ctx context.Context, loader SolverLoader, out SolverProgress, modules Modules, test bool) (*State, error) {\n\tvar err error\n\tif err = loader.FinishModules(ctx, out, modules); err != nil {\n\t\treturn state, err\n\t}\n\n\t// Back-track for any module that we have already considered for the\n\t// solution but need to upgrade.\n\tfor _, module := range modules {\n\t\tout.Constrain(state, module)\n\t\tif partial, ok := state.Solution[module.Name]; ok {\n\t\t\tif partial.Module.Before(module) {\n\t\t\t\tout.Backtrack(state, partial.Module, module)\n\t\t\t\t// Back-track to before the prior version was locked,\n\t\t\t\t// so we can forget modules and packages that might not exist\n\t\t\t\t// any longer.\n\t\t\t\t// Replace the old module with the new.\n\t\t\t\tstate = partial.Backtrack(module)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add all modules to the frontier.\n\tstate = state.Clone()\n\tfor _, module := range modules {\n\t\tif test {\n\t\t\tmodule.Test = true\n\t\t}\n\t\tif i, ok := state.Problem[module.Name]; ok {\n\t\t\tproblem := state.Frontier[i]\n\t\t\t// Promote test modules to normal modules if they are depended upon\n\t\t\t// by a non-test module.\n\t\t\tif !module.Test {\n\t\t\t\tproblem.Test = false\n\t\t\t}\n\t\t\t// Promote to the higher or newer of two versions.\n\t\t\tif problem.Before(module) {\n\t\t\t\tproblem = module\n\t\t\t}\n\t\t\tstate.Frontier[i] = problem\n\t\t} else {\n\t\t\tsolution, ok := state.Solution[module.Name]\n\t\t\tif ok && !module.Test {\n\t\t\t\tsolution.Module.Test = false\n\t\t\t\tstate.Solution[module.Name] = solution\n\t\t\t}\n\t\t\tif !ok || solution.Module.Before(module) {\n\t\t\t\t// Append modules to the frontier either if we have not already\n\t\t\t\t// seen them (not in the existing problem or solution), or if they\n\t\t\t\t// are already in the solution but at an earlier version.\n\t\t\t\tdelete(state.Solution, module.Name)\n\t\t\t\tstate.Problem[module.Name] = len(state.Frontier)\n\t\t\t\tstate.Frontier = append(state.Frontier, module)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn state, nil\n}", "func (n *SoupNode) Freeze() {}", "func rprop(f func(Vector) (Scalar, error), x0 ConstVector, step_init float64 , eta []float64,\n epsilon Epsilon,\n maxIterations MaxIterations,\n hook Hook,\n constraints Constraints) (Vector, error) {\n\n n := x0.Dim()\n t := x0.ElementType()\n // copy variables\n x1 := AsDenseRealVector(x0)\n x2 := AsDenseRealVector(x0)\n // step size for each variable\n step := make([]float64, n)\n // gradients\n gradient_new := make([]float64, n)\n gradient_old := make([]float64, n)\n // initialize values\n for i := 0; i < x1.Dim(); i++ {\n step[i] = step_init\n gradient_new[i] = 1\n gradient_old[i] = 1\n }\n if err := x1.Variables(1); err != nil {\n return nil, err\n }\n gradient_is_nan := func(s Scalar) bool {\n for i := 0; i < s.GetN(); i++ {\n if math.IsNaN(s.GetDerivative(i)) {\n return true\n }\n }\n return false\n }\n // check initial value\n if constraints.Value != nil && !constraints.Value(x1) {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n // evaluate objective function\n s, err := f(x1)\n if err != nil {\n return x1, fmt.Errorf(\"invalid initial value: %v\", x1)\n }\n if gradient_is_nan(s) {\n return x1, fmt.Errorf(\"gradient is NaN for initial value: %v\", x1)\n }\n for i := 0; i < maxIterations.Value; i++ {\n for i := 0; i < x1.Dim(); i++ {\n gradient_old[i] = gradient_new[i]\n }\n // compute partial derivatives and update x\n for i := 0; i < x1.Dim(); i++ {\n // save derivative\n gradient_new[i] = s.GetDerivative(i)\n }\n // execute hook if available\n if hook.Value != nil && hook.Value(gradient_new, step, x1, s) {\n break;\n }\n // evaluate stop criterion\n if (Norm(gradient_new) < epsilon.Value) {\n break;\n }\n // update step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if ((gradient_old[i] < 0 && gradient_new[i] < 0) ||\n (gradient_old[i] > 0 && gradient_new[i] > 0)) {\n step[i] *= eta[0]\n } else {\n step[i] *= eta[1]\n }\n }\n }\n for {\n // update x\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n if gradient_new[i] > 0.0 {\n x2.At(i).Sub(x1.At(i), NewScalar(t, step[i]))\n } else {\n x2.At(i).Add(x1.At(i), NewScalar(t, step[i]))\n }\n }\n if math.IsNaN(x2.At(i).GetValue()) {\n return x2, fmt.Errorf(\"NaN value detected\")\n }\n }\n // evaluate objective function\n s, err = f(x2)\n if err != nil || gradient_is_nan(s) ||\n (constraints.Value != nil && !constraints.Value(x2)) {\n // if the updated is invalid reduce step size\n for i := 0; i < x1.Dim(); i++ {\n if gradient_new[i] != 0.0 {\n step[i] *= eta[1]\n }\n }\n } else {\n // new position is valid, exit loop\n break\n }\n }\n x1.Set(x2)\n }\n return x1, nil\n}", "func (me *lmsEvaluator) Eval(game c4.State, p c4.Piece) float64 {\n\tvar bestScore, knownScore float64\n\n\t// Copy out the coefficients to reduce lock contention\n\tme.coeffsMutex.RLock()\n\tmyCoeffs := me.Coeffs\n\tme.coeffsMutex.RUnlock()\n\n\t// Estimate the game state's utility\n\tapproxScore, currentFeatures := BetterEval(myCoeffs, game, p)\n\n\t// Try to get a better estimate of the utility by looking one move ahead\n\t// with proven weights\n\tif game.GetTurn() != p {\n\t\tbestScore = math.Inf(-1)\n\t} else {\n\t\tbestScore = math.Inf(+1)\n\t}\n\n\tfor col := 0; col < c4.MaxColumns; col++ {\n\t\tif nextBoard, err := game.AfterMove(game.GetTurn(),\n\t\t\tcol); err == nil {\n\t\t\tnextScore, _ := BetterEval(\n\t\t\t\tmyCoeffs,\n\t\t\t\tnextBoard,\n\t\t\t\tnextBoard.GetTurn())\n\n\t\t\tif game.GetTurn() != p {\n\t\t\t\tif nextScore > bestScore {\n\t\t\t\t\tbestScore = nextScore\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif nextScore < bestScore {\n\t\t\t\t\tbestScore = nextScore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Use the evolved weights as a reference to prevent divergence\n\tknownScore, _ = BetterEval([6]float64{\n\t\t0.2502943943301069,\n\t\t-0.4952316649483701,\n\t\t0.3932539700819625,\n\t\t-0.2742452616759889,\n\t\t0.4746881137884282,\n\t\t0.2091091127191147}, game, p)\n\n\t// Change the coefficients according to the error\n\tme.count++\n\tif me.count%100000 == 0 {\n\t\tfmt.Println(me.count)\n\t\tfmt.Println(me.Coeffs)\n\t}\n\t// if !math.IsInf(bestScore, 0) {\n\t// \tfor j := 0; j < 6; j++ {\n\t// \t\tme.Coeffs[j] +=\n\t// \t\t\tmu * (bestScore - approxScore) * currentFeatures[j]\n\t// \t}\n\t// }\n\tgo func() {\n\t\tif !math.IsInf(bestScore, 0) {\n\t\t\tme.coeffsMutex.Lock()\n\t\t\tfor j := 0; j < 6; j++ {\n\t\t\t\tme.Coeffs[j] +=\n\t\t\t\t\tmu * (knownScore - approxScore) * currentFeatures[j]\n\t\t\t}\n\t\t\tme.coeffsMutex.Unlock()\n\t\t}\n\t}()\n\n\treturn approxScore\n}", "func (kb *KubeBackend) Unfreeze() error {\n\tlogrus.Infof(\"set deployment %s replica=1\", kb.ID())\n\tdeployment, err := kb.manager.di.Lister().Deployments(kb.manager.namespace).Get(kb.ID())\n\tif err != nil {\n\t\tif err := kb.manager.syncBackend(kb.ID()); err != nil {\n\t\t\tlogrus.Warnf(\"sycn app with error: %v\", err)\n\t\t}\n\t\treturn err\n\t}\n\tif *deployment.Spec.Replicas != 0 {\n\t\treturn nil\n\t}\n\tvar targetReplica int32 = 1\n\tdeployment.Spec.Replicas = &targetReplica\n\t_, err = kb.manager.client.AppsV1().Deployments(kb.manager.namespace).\n\t\tUpdate(context.Background(), deployment, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tkb.Lock()\n\tkb.stateStarting = true\n\tkb.stateHealthy = false\n\tkb.Unlock()\n\treturn nil\n}", "func (c *EgressController) worker() {\n\tfor c.processNextWorkItem() {\n\t}\n}", "func (e *Exponential) Fit(samples, weights []float64) {\n\tsuffStat := make([]float64, e.NumSuffStat())\n\tnSamples := e.SuffStat(suffStat, samples, weights)\n\te.ConjugateUpdate(suffStat, nSamples, make([]float64, e.NumSuffStat()))\n}", "func BSFW(mr, r operand.Op) { ctx.BSFW(mr, r) }", "func (acker *acker) Free() {\n\tfor k, _ := range acker.fmap {\n\t\tacker.fmap[k] = nil\n\t}\n\tacker.fmap = nil\n\tacker.mutex = nil\n}", "func (self *AbstractFilter) SyncUniforms() {\n self.Object.Call(\"syncUniforms\")\n}", "func (p Polynom) SetCoeff(i int, v *big.Int) {\n\tv = cp(v)\n\tp.coeff[i] = v.Mod(v, p.mod)\n}", "func (v *ReadCloserValue) Freeze() {}", "func (la *Lattice) Free() {\n\tla.Input = \"\"\n\tfor i := range la.Output {\n\t\tla.Output[i] = nil\n\t}\n\tla.Output = la.Output[:0]\n\tfor i := range la.list {\n\t\tfor j := range la.list[i] {\n\t\t\tnodePool.Put(la.list[i][j])\n\t\t\tla.list[i][j] = nil\n\t\t}\n\t\tla.list[i] = la.list[i][:0]\n\t}\n\tla.list = la.list[:0]\n\tla.udic = nil\n\tlatticePool.Put(la)\n}", "func (p thinPoly) x4Mul(f, g thinPoly) thinPoly {\n\tp.Zero()\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tp[i+j] += Freeze(f[i] * g[j])\n\t\t}\n\t}\n\treturn p\n}", "func (s *Client) Freeze(username string) error {\n\tuser := s.Init(username)\n\tdata, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(`INSERT OR REPLACE INTO frozen_user (user_id, data)VALUES((SELECT id FROM users WHERE username = ?), ?);`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(username, string(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func (s *Service) Exec(job interface{}) {\n\n\ts.Lock.RLock()\n\t// In case this routine has to wait for the calculation routine:\n\tif s.InProgress[job] {\n\n\t\t// Make a new channel (reader)\n\t\ts.Lock.RUnlock()\n\t\tresponse := make(chan interface{})\n\t\tdefer close(response)\n\n\t\t// Append the reader to its respective queue (regarding to the job)\n\t\ts.Lock.Lock()\n\t\ts.PendingReaders[job] = append(s.PendingReaders[job], response)\n\t\ts.Lock.Unlock()\n\n\t\t// The reader now only has to wait for the result of the routine\n\t\t// that is calculating the result for the required job\n\t\tfmt.Printf(\"Waiting for Response job: %d\\n\", job)\n\t\tresp := <-response\n\t\tfmt.Printf(\"Response Done, received %d\\n\", resp)\n\t\treturn\n\t}\n\n\t// In case this routine is the one to perform the calculation:\n\n\ts.Lock.RUnlock()\n\ts.Lock.Lock()\n\n\t// Flag to tell other routines that the required job is being calculated\n\ts.InProgress[job] = true\n\ts.Lock.Unlock()\n\n\tfmt.Printf(\"Performing expensive function for job %d\\n\", job)\n\tresult := s.f(job)\n\n\t// Once finished the function call, recall the channels\n\t// to send the result to\n\ts.Lock.RLock()\n\tpendingWorkers, inProgress := s.PendingReaders[job]\n\ts.Lock.RUnlock()\n\n\t// Send the message to all routines via channels\n\tif inProgress {\n\t\tfor _, pendingWorker := range pendingWorkers {\n\t\t\tpendingWorker <- result\n\t\t}\n\t\tfmt.Printf(\"Result sent - all pending workers ready job:%d\\n\", job)\n\t}\n\n\t// Free in-progess flag and delete all readers\n\ts.Lock.Lock()\n\ts.InProgress[job] = false\n\ts.PendingReaders[job] = make([]chan interface{}, 0)\n\ts.Lock.Unlock()\n}", "func (z *E6) Frobenius(x *E6) *E6 {\n\n\tz.B0.A0 = x.B0.A0\n\tz.B0.A1.Mul(&x.B0.A1, &_frobA)\n\tz.B0.A2.Mul(&x.B0.A2, &_frobB)\n\n\tz.B1.A0.Mul(&x.B1.A0, &_frobC)\n\tz.B1.A1.Mul(&x.B1.A1, &_frobAC)\n\tz.B1.A2.Mul(&x.B1.A2, &_frobBC)\n\n\treturn z\n}", "func (s *inMemSpannerServer) Freeze() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.freezed = make(chan struct{})\n}", "func (tester *FreezeTester) mdMulAcctNonExiNon(t *testing.T, d *Dandelion) {\n\ta := assert.New(t)\n\ta.True(d.Contract(constants.COSSysAccount, frCrtName).CheckExist())\n\tnewAcctName := \"account10\"\n tester.createNewAcct(t, d, newAcctName)\n\tnewAcct := d.Account(newAcctName)\n\tacct11 := d.Account(\"account11\")\n\tacct12 := d.Account(\"account12\")\n\ta.False(acct11.CheckExist())\n\ta.False(acct12.CheckExist())\n\tsta := newAcct.GetFreeze()\n\tmemo := newAcct.GetFreezeMemo()\n\tnewSta := tester.mdFreezeStatus(sta)\n\tacctList := []*DandelionAccount{newAcct, acct11, acct12}\n\tmemoArray,nameArray := tester.getProposalMemoAndNameParams(d,acctList)\n\tlastPropId,err := tester.getProposalId(d)\n\ta.NoError(err)\n\tApplyError(t, d, fmt.Sprintf(\"%s: %s.%s.proposalfreeze %s,%d,%s\", tester.acc1.Name, constants.COSSysAccount,\n\t\tfrCrtName, nameArray, newSta, memoArray))\n\ta.Equal(sta, newAcct.GetFreeze())\n\ta.Equal(memo, newAcct.GetFreezeMemo())\n\tnewPropId,err := tester.getProposalId(d)\n\ta.NoError(err)\n\ta.Equal(lastPropId, newPropId)\n\n}", "func (c *StepLookbackAccumulator) BufferStep() {\n\t// Update earliest lookback then remove stale values for the next\n\t// iteration of the datapoint set.\n\tc.earliestLookback = c.earliestLookback.Add(c.stepSize)\n\tif len(c.datapoints) == 0 {\n\t\tc.unconsumed = append(c.unconsumed, nil)\n\t\treturn\n\t}\n\n\taccumulated := make([]xts.Datapoint, len(c.datapoints))\n\tcopy(accumulated, c.datapoints)\n\tc.datapoints = c.datapoints[:0]\n\tc.unconsumed = append(c.unconsumed, accumulated)\n}", "func FreeZero() {\n\n}", "func main() {\n\tx := new(int)\n\t*x++ // ok\n\n\tx = freeze(x)\n\n\tfmt.Println(*x) // ok; prints 1\n\t//*x++ // not ok; panics!\n}", "func (b *Engine) run() {\n\t// mines blocks from difficulty to when it takes longer than 60 seconds to mine block\n\tb.logger.Log(\"Benchmark: starting benchmark\")\n\tdone := false\n\tclose := make(chan struct{})\n\tdifficulty := 10 //! difficulty starts at 10\n\tgo func() {\n\t\tvar wg sync.WaitGroup\n\t\tfor done == false {\n\t\t\tfor i := 0; i < 3; i++ { //? runs 3 difficulties in parralel to increase benchmark speed\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(myDifficulty int) { //? mines block of myDifficulty 5 times and adds average time and difficulty\n\t\t\t\t\tvar avg []float64\n\t\t\t\t\tvar mu sync.Mutex\n\t\t\t\t\tvar mineWG sync.WaitGroup\n\t\t\t\t\tfor j := 0; j < 5; j++ {\n\t\t\t\t\t\tmineWG.Add(1)\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tstart := time.Now()\n\t\t\t\t\t\t\tblock := b.block(uint8(myDifficulty))\n\t\t\t\t\t\t\tend := time.Now()\n\t\t\t\t\t\t\tblock.DeleteFile()\n\t\t\t\t\t\t\tdiff := end.Sub(start).Seconds()\n\t\t\t\t\t\t\tmu.Lock()\n\t\t\t\t\t\t\tavg = append(avg, diff)\n\t\t\t\t\t\t\tmu.Unlock()\n\t\t\t\t\t\t\tmineWG.Done()\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t\tmineWG.Wait()\n\t\t\t\t\tvar avgSum float64\n\t\t\t\t\tfor _, val := range avg {\n\t\t\t\t\t\tavgSum += val\n\t\t\t\t\t}\n\t\t\t\t\taverage := avgSum / float64(len(avg))\n\t\t\t\t\tif average > float64(60) { // a minute\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\tclose <- struct{}{}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif done == true {\n\t\t\t\t\t\t\twg.Done()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tb.addBenchmark(NewBenchmark(average, uint8(myDifficulty)))\n\t\t\t\t\t}\n\t\t\t\t\tb.logger.Log(\"Bechmark: completed benchmark for difficulty \" + strconv.FormatInt(int64(myDifficulty), 10))\n\t\t\t\t\twg.Done()\n\t\t\t\t}(difficulty)\n\t\t\t\tdifficulty++\n\t\t\t}\n\t\t\twg.Wait()\n\t\t}\n\t}()\n\n\t<-close //wait for close signal\n\n\tscore := float64(b.GetData()[len(b.GetData())-1].GetDifficulty()) - 10 //! 10 is subtracted to allow the score start from 1 since difficulty starts at 10\n\tscoreDecimal := 1 - b.GetData()[len(b.GetData())-1].GetAvgTime()/100 // determine decimal part of score\n\tb.setScore(score + scoreDecimal)\n\tb.logger.Info(\"Benchmark: benchmark done\")\n}", "func (d *Director) FreezeMonkey(rng *rand.Rand, intensity float64) {\n\tif intensity < 0.1 {\n\t\treturn\n\t}\n\ttarget := d.randomAgent(rng)\n\tduration := d.makeDuration(rng, 1000, intensity)\n\tlog.Printf(\"[monkey] Freezing %v for %v\", target, duration)\n\tgo target.Stop(duration)\n}", "func workers(done *int, jobs <-chan int, arrayA, arrayB, arrayF *arr) {\r\n\t// Inicia uma trhead para cada linha da matriz.\r\n\tfor job := range jobs {\r\n\t\tgo partial(job, done, arrayA, arrayB, arrayF)\r\n\t}\r\n}", "func (v *VolumesServiceMock) Freeze(podUID string, name string) (vol *api.Volume, err error) {\n\targs := v.Called(podUID, name)\n\tx := args.Get(0)\n\tif x != nil {\n\t\tvol = x.(*api.Volume)\n\t}\n\terr = args.Error(1)\n\treturn\n}", "func (s *Mobius) warm_start() {\n\tif s.frontier_writer != nil {\n\t\tdefer s.frontier_writer.Flush()\n\t}\n\n\ttype ws struct {\n\t\tschedule vrp.Schedule\n\t\tlabel string\n\t}\n\talphas := []float64{0.1, 0.25, 1.0, 5.0, 100.0}\n\tvar c chan ws\n\tif s.Solver.GetRTH() != nil {\n\t\tc = make(chan ws, 2)\n\t} else {\n\t\tc = make(chan ws, 2+len(alphas))\n\t}\n\tvar wg sync.WaitGroup\n\n\t// dedicate vehicle per app\n\tif len(s.Vehicles)%s.num_apps == 0 {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\td := vrp.DedicateSolver{}\n\t\t\td.Set(\n\t\t\t\ts.InterestMap,\n\t\t\t\ts.InterestMap,\n\t\t\t\ts.Vehicles,\n\t\t\t\ts.Horizon,\n\t\t\t\ts.Capacity,\n\t\t\t\ts.Solver.GetRTH(),\n\t\t\t)\n\t\t\td.SetTravelTimeMatrixPath(s.Solver.GetTravelTimeMatrixPath())\n\t\t\tsched := d.Solve()\n\t\t\tlog.Debugf(\n\t\t\t\t\"warm start: dedicate: %v, util %v\",\n\t\t\t\tsched.Allocation,\n\t\t\t\ts.utility(sched.Allocation),\n\t\t\t)\n\t\t\tc <- ws{schedule: sched, label: \"dedicate\"}\n\t\t}()\n\t}\n\n\t// max throughput schedule (standard VRP)\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ts.Solver.Set(\n\t\t\ts.InterestMap,\n\t\t\ts.InterestMap,\n\t\t\ts.Vehicles,\n\t\t\ts.Horizon,\n\t\t\ts.Capacity,\n\t\t\ts.Solver.GetRTH(),\n\t\t)\n\t\tsched := s.Solver.Solve()\n\t\tlog.Debugf(\n\t\t\t\"warm start: maxthp: %v, util %v\",\n\t\t\tsched.Allocation,\n\t\t\ts.utility(sched.Allocation),\n\t\t)\n\t\tc <- ws{schedule: sched, label: \"maxthp\"}\n\t}()\n\n\t// roi for different alphas\n\t// only works when no RTH\n\tif s.Solver.GetRTH() == nil && s.Solver.GetTravelTimeMatrixPath() == \"\" {\n\t\tfor _, a := range alphas {\n\t\t\twg.Add(1)\n\t\t\tgo func(alpha float64) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tsolver := vrp.RoiSolver{Alpha: alpha}\n\t\t\t\tsolver.Set(s.InterestMap, s.InterestMap, s.Vehicles, s.Horizon, 0, false)\n\t\t\t\tsched := solver.Solve()\n\t\t\t\tlog.Debugf(\n\t\t\t\t\t\"warm start: roi, alpha %v: %v, util %v\",\n\t\t\t\t\talpha,\n\t\t\t\t\tsched.Allocation,\n\t\t\t\t\ts.utility(sched.Allocation),\n\t\t\t\t)\n\t\t\t\tc <- ws{schedule: sched, label: fmt.Sprintf(\"roi_alpha%v\", alpha)}\n\t\t\t}(a)\n\t\t}\n\t}\n\n\t// wait for threads to finish\n\twg.Wait()\n\tclose(c)\n\tfor x := range c {\n\t\ts.heuristics[x.label] = x.schedule\n\t\tif s.frontier_writer != nil {\n\t\t\ts.frontier_writer.Write(\n\t\t\t\ts.get_csv_row(x.label, x.schedule.Allocation),\n\t\t\t)\n\t\t}\n\t}\n}", "func (s *Server) forwardRateLimit() {\n for range s.rateLimitTicker.C {\n s.io.BroadcastTo(\"ui\", \"rate-limit\", s.cache.GetRateLimitAllocation())\n }\n}", "func (rpcServer RpcServer) handleEstimateFee(params interface{}, closeChan <-chan struct{}) (interface{}, *RPCError) {\n\tLogger.log.Infof(\"handleEstimateFee params: %+v\", params)\n\t/******* START Fetch all component to ******/\n\t// all component\n\tarrayParams := common.InterfaceSlice(params)\n\tif len(arrayParams) < 5 {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Not enough params\"))\n\t}\n\t// param #1: private key of sender\n\tsenderKeyParam, ok := arrayParams[0].(string)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Sender private key is invalid\"))\n\t}\n\t// param #3: estimation fee coin per kb\n\tdefaultFeeCoinPerKbtemp, ok := arrayParams[2].(float64)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"Default FeeCoinPerKbtemp is invalid\"))\n\t}\n\tdefaultFeeCoinPerKb := int64(defaultFeeCoinPerKbtemp)\n\t// param #4: hasPrivacy flag for constant\n\thashPrivacyTemp, ok := arrayParams[3].(float64)\n\tif !ok {\n\t\treturn nil, NewRPCError(ErrRPCInvalidParams, errors.New(\"hasPrivacy is invalid\"))\n\t}\n\thasPrivacy := int(hashPrivacyTemp) > 0\n\n\tsenderKeySet, err := rpcServer.GetKeySetFromPrivateKeyParams(senderKeyParam)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrInvalidSenderPrivateKey, err)\n\t}\n\tlastByte := senderKeySet.PaymentAddress.Pk[len(senderKeySet.PaymentAddress.Pk)-1]\n\tshardIDSender := common.GetShardIDFromLastByte(lastByte)\n\t//fmt.Printf(\"Done param #1: keyset: %+v\\n\", senderKeySet)\n\n\tconstantTokenID := &common.Hash{}\n\tconstantTokenID.SetBytes(common.ConstantID[:])\n\toutCoins, err := rpcServer.config.BlockChain.GetListOutputCoinsByKeyset(senderKeySet, shardIDSender, constantTokenID)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrGetOutputCoin, err)\n\t}\n\t// remove out coin in mem pool\n\toutCoins, err = rpcServer.filterMemPoolOutCoinsToSpent(outCoins)\n\tif err != nil {\n\t\treturn nil, NewRPCError(ErrGetOutputCoin, err)\n\t}\n\n\testimateFeeCoinPerKb := uint64(0)\n\testimateTxSizeInKb := uint64(0)\n\tif len(outCoins) > 0 {\n\t\t// param #2: list receiver\n\t\treceiversPaymentAddressStrParam := make(map[string]interface{})\n\t\tif arrayParams[1] != nil {\n\t\t\treceiversPaymentAddressStrParam = arrayParams[1].(map[string]interface{})\n\t\t}\n\t\tpaymentInfos := make([]*privacy.PaymentInfo, 0)\n\t\tfor paymentAddressStr, amount := range receiversPaymentAddressStrParam {\n\t\t\tkeyWalletReceiver, err := wallet.Base58CheckDeserialize(paymentAddressStr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, NewRPCError(ErrInvalidReceiverPaymentAddress, err)\n\t\t\t}\n\t\t\tpaymentInfo := &privacy.PaymentInfo{\n\t\t\t\tAmount: uint64(amount.(float64)),\n\t\t\t\tPaymentAddress: keyWalletReceiver.KeySet.PaymentAddress,\n\t\t\t}\n\t\t\tpaymentInfos = append(paymentInfos, paymentInfo)\n\t\t}\n\n\t\t// Check custom token param\n\t\tvar customTokenParams *transaction.CustomTokenParamTx\n\t\tvar customPrivacyTokenParam *transaction.CustomTokenPrivacyParamTx\n\t\tif len(arrayParams) > 4 {\n\t\t\t// param #5: token params\n\t\t\ttokenParamsRaw := arrayParams[4].(map[string]interface{})\n\t\t\tprivacy := tokenParamsRaw[\"Privacy\"].(bool)\n\t\t\tif !privacy {\n\t\t\t\t// Check normal custom token param\n\t\t\t\tcustomTokenParams, _, err = rpcServer.buildCustomTokenParam(tokenParamsRaw, senderKeySet)\n\t\t\t\tif err.(*RPCError) != nil {\n\t\t\t\t\treturn nil, err.(*RPCError)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Check privacy custom token param\n\t\t\t\tcustomPrivacyTokenParam, _, _, err = rpcServer.buildPrivacyCustomTokenParam(tokenParamsRaw, senderKeySet, shardIDSender)\n\t\t\t\tif err.(*RPCError) != nil {\n\t\t\t\t\treturn nil, err.(*RPCError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// check real fee(nano constant) per tx\n\t\t_, estimateFeeCoinPerKb, estimateTxSizeInKb = rpcServer.estimateFee(defaultFeeCoinPerKb, outCoins, paymentInfos, shardIDSender, 8, hasPrivacy, nil, customTokenParams, customPrivacyTokenParam)\n\t}\n\tresult := jsonresult.EstimateFeeResult{\n\t\tEstimateFeeCoinPerKb: estimateFeeCoinPerKb,\n\t\tEstimateTxSizeInKb: estimateTxSizeInKb,\n\t}\n\tLogger.log.Infof(\"handleEstimateFee result: %+v\", result)\n\treturn result, nil\n}", "func BTW(ir, mr operand.Op) { ctx.BTW(ir, mr) }", "func (m *Binarizer) Fit(Xmatrix, Ymatrix mat.Matrix) base.Fiter {\n\treturn m\n}", "func FixFreezeLookupMigration(db *IndexerDb, state *MigrationState) error {\n\t// Technically with this query no transactions are needed, and the accounting state doesn't need to be locked.\n\tupdateQuery := \"INSERT INTO txn_participation (addr, round, intra) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING\"\n\tquery := fmt.Sprintf(\"select decode(txn.txn->'txn'->>'fadd','base64'),round,intra from txn where typeenum = %d AND txn.txn->'txn'->'snd' != txn.txn->'txn'->'fadd'\", idb.TypeEnumAssetFreeze)\n\trows, err := db.db.Query(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to query transactions: %v\", err)\n\t}\n\tdefer rows.Close()\n\n\ttxprows := make([][]interface{}, 0)\n\n\t// Loop through all transactions and compute account data.\n\tdb.log.Print(\"loop through all freeze transactions\")\n\tfor rows.Next() {\n\t\tvar addr []byte\n\t\tvar round, intra uint64\n\t\terr = rows.Scan(&addr, &round, &intra)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scanning row: %v\", err)\n\t\t}\n\n\t\ttxprows = append(txprows, []interface{}{addr, round, intra})\n\n\t\tif len(txprows) > 5000 {\n\t\t\terr = updateBatch(db, updateQuery, txprows)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t\t}\n\t\t\ttxprows = txprows[:0]\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn fmt.Errorf(\"error while processing freeze transactions: %v\", rows.Err())\n\t}\n\n\t// Commit any leftovers\n\tif len(txprows) > 0 {\n\t\terr = updateBatch(db, updateQuery, txprows)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t}\n\t}\n\n\t// Update migration state\n\treturn upsertMigrationState(db, state, true)\n}", "func (hm *HM) Barrier(b uint8) {\n\thm.LogDebug(\"Barrier(%d)..Start\", b)\n\tmanager := hm.getBarrierManager(b)\n\t// Only the non-manager processors send out the Barrier Request\n\t// to the manager. The manager is the only node receiving these\n\t// messages.\n\tif hm.pid != manager {\n\t\thm.CreateInterval()\n\t\tlastLt := hm.procArray.GetLatestLocalTimestamp(manager)\n\t\t// get local intervals between lastLt and VC[pid]\n\t\tintervals := hm.procArray.GetProcMissingIntervals(hm.pid, lastLt)\n\t\thm.IncorporateIntervals(intervals)\n\t\thm.sendBarrierRequest(manager, b, &hm.VC, intervals)\n\t} else {\n\t\tintervals := make([]IntervalRec, 0)\n\t\thm.sendBarrierRequest(manager, b, &hm.VC, intervals)\n\t}\n\t<-hm.waitChan\n\thm.LogDebug(\"Barrier(%d)..Done\", b)\n}", "func (m *ClusterService) clusterFreeze(ctx context.Context, args struct {\n\tStatus bool\n}) (*proto.GeneralResp, error) {\n\tif _, _, err := permissions(ctx, ADMIN); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.cluster.setDisableAutoAllocate(args.Status); err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Success(\"success\"), nil\n}", "func BSFL(mr, r operand.Op) { ctx.BSFL(mr, r) }", "func (m *PowerTransformer) Fit(X, Y mat.Matrix) base.Fiter {\n\tm.fit(X, Y, false)\n\treturn m\n}", "func calcTrendGrowthMultipleRegressionPart2(bConstant, bGrowth bool, mtxY, mtxX, newX, mtxRes [][]float64, meanY float64, nCXN, K, N int) {\n\tvecR := make([]float64, N) // for QR decomposition\n\tmeans := getNewMatrix(K, 1) // mean of each row\n\tslopes := getNewMatrix(K, 1) // row from b1 to bK\n\tif len(means) == 0 || len(slopes) == 0 {\n\t\treturn\n\t}\n\tif bConstant {\n\t\tcalcRowMeans(mtxX, means, N, K)\n\t\tcalcRowsDelta(mtxX, means, N, K)\n\t}\n\tif !calcColQRDecomposition(mtxX, vecR, K, N) {\n\t\treturn\n\t}\n\t// later on we will divide by elements of vecR, so make sure that they aren't zero\n\tbIsSingular := false\n\tfor row := 0; row < K && !bIsSingular; row++ {\n\t\tbIsSingular = bIsSingular || vecR[row] == 0\n\t}\n\tif bIsSingular {\n\t\treturn\n\t}\n\tfor row := 0; row < K; row++ {\n\t\tcalcApplyColsHouseholderTransformation(mtxX, row, mtxY, N)\n\t}\n\tfor col := 0; col < K; col++ {\n\t\tputDouble(slopes, col, getDouble(mtxY, col))\n\t}\n\tcalcSolveWithUpperRightTriangle(mtxX, vecR, slopes, K, true)\n\t// fill result matrix\n\tcalcFastMult(slopes, newX, mtxRes, 1, K, nCXN)\n\tif bConstant {\n\t\tfIntercept := meanY - calcSumProduct(means, slopes, K)\n\t\tfor col := 0; col < nCXN; col++ {\n\t\t\tmtxRes[col][0] = mtxRes[col][0] + fIntercept\n\t\t}\n\t}\n\tif bGrowth {\n\t\tfor i := 0; i < nCXN; i++ {\n\t\t\tputDouble(mtxRes, i, math.Exp(getDouble(mtxRes, i)))\n\t\t}\n\t}\n}", "func (_Token *TokenFilterer) WatchFreeze(opts *bind.WatchOpts, sink chan<- *TokenFreeze, from []common.Address) (event.Subscription, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.WatchLogs(opts, \"Freeze\", fromRule)\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(TokenFreeze)\n\t\t\t\tif err := _Token.contract.UnpackLog(event, \"Freeze\", 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 testBackends(inputSize, outputSize int, hiddenSize int) *backends {\n\tvar back backends\n\tinitValue := float32(1e-3)\n\tback.InputSize = inputSize\n\tback.OutputSize = outputSize\n\tback.HiddenSize = hiddenSize\n\tback.Wi = make([]float32, hiddenSize*inputSize)\n\tfor i := 0; i < hiddenSize*inputSize; i++ {\n\t\tback.Wi[i] = initValue * rand.Float32()\n\t}\n\tback.Ui = make([]float32, hiddenSize*hiddenSize)\n\tfor i := 0; i < hiddenSize*hiddenSize; i++ {\n\t\tback.Ui[i] = initValue * rand.Float32()\n\t}\n\tback.BiasI = make([]float32, hiddenSize)\n\tback.Wo = make([]float32, hiddenSize*inputSize)\n\tfor i := 0; i < hiddenSize*inputSize; i++ {\n\t\tback.Wo[i] = initValue * rand.Float32()\n\t}\n\tback.Uo = make([]float32, hiddenSize*hiddenSize)\n\tfor i := 0; i < hiddenSize*hiddenSize; i++ {\n\t\tback.Uo[i] = initValue * rand.Float32()\n\t}\n\tback.BiasO = make([]float32, hiddenSize)\n\tback.Wf = make([]float32, hiddenSize*inputSize)\n\tfor i := 0; i < hiddenSize*inputSize; i++ {\n\t\tback.Wf[i] = initValue * rand.Float32()\n\t}\n\tback.Uf = make([]float32, hiddenSize*hiddenSize)\n\tfor i := 0; i < hiddenSize*hiddenSize; i++ {\n\t\tback.Uf[i] = initValue * rand.Float32()\n\t}\n\tback.BiasF = make([]float32, hiddenSize)\n\tback.Wc = make([]float32, hiddenSize*inputSize)\n\tfor i := 0; i < hiddenSize*inputSize; i++ {\n\t\tback.Wc[i] = initValue * rand.Float32()\n\t}\n\tback.Uc = make([]float32, hiddenSize*hiddenSize)\n\tfor i := 0; i < hiddenSize*hiddenSize; i++ {\n\t\tback.Uc[i] = initValue * rand.Float32()\n\t}\n\tback.BiasC = make([]float32, hiddenSize)\n\tback.Wy = make([]float32, hiddenSize*outputSize)\n\tfor i := 0; i < hiddenSize*outputSize; i++ {\n\t\tback.Wy[i] = initValue * rand.Float32()\n\t}\n\tback.BiasY = make([]float32, outputSize)\n\treturn &back\n}", "func (stateObj *stateObject) finalise(prefetch bool) {\n\tlog.Debugf(\"stateObject finalise. address:%x, prefetch:%v\", stateObj.address, prefetch)\n\n\tslotsToPrefetch := make([][]byte, 0, len(stateObj.dirtyStorage))\n\tfor key, value := range stateObj.dirtyStorage {\n\t\tstateObj.pendingStorage[key] = value\n\t\tif value != stateObj.originStorage[key] {\n\t\t\tslotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure\n\t\t}\n\t}\n\tif stateObj.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && stateObj.data.Root != emptyRoot {\n\t\tstateObj.db.prefetcher.prefetch(stateObj.addrHash, stateObj.data.Root, slotsToPrefetch)\n\t}\n\tif len(stateObj.dirtyStorage) > 0 {\n\t\tstateObj.dirtyStorage = make(Storage)\n\t}\n}", "func (honest *Honest) requestNoise(iterationCount int) ([]float64, error) {\n\n\truntime.LockOSThread()\n\n\t_gstate := python.PyGILState_Ensure()\n\n\t// Either use full GD or SGD here\n\tvar result *python.PyObject\n\tresult = pyNoiseFunc.CallFunction(python.PyInt_FromLong(iterationCount))\n\n\t// Convert the resulting array to a go byte array\n\tpyByteArray := python.PyByteArray_FromObject(result)\n\tgoByteArray := python.PyByteArray_AsBytes(pyByteArray)\n\n\tpython.PyGILState_Release(_gstate)\n\n\tvar goFloatArray []float64\n\tsize := len(goByteArray) / 8\n\n\tfor i := 0; i < size; i++ {\n\t\tcurrIndex := i * 8\n\t\tbits := binary.LittleEndian.Uint64(goByteArray[currIndex : currIndex+8])\n\t\taFloat := math.Float64frombits(bits)\n\t\tgoFloatArray = append(goFloatArray, aFloat)\n\t}\n\n\treturn goFloatArray, nil\n\n}", "func (shp *SHPImpl) ComputMoveGainWithBufferParallel() {\n\tfor bucketI := uint64(0); bucketI < shp.bucketSize; bucketI++ {\n\t\tfor bucketJ := uint64(0); bucketJ < shp.bucketSize; bucketJ++ {\n\t\t\tshp.vertexTrans[bucketI][bucketJ] = 0\n\t\t}\n\t}\n\tparallel := uint64(runtime.NumCPU())\n\tatomic.StoreInt64(&shp.tf.bufferSize, 0)\n\t// TODO\n\t// make parallel seperate stable\n\tsegmentVertexSize := (shp.vertexSize + parallel - 1) / parallel\n\tvar wg sync.WaitGroup\n\tfor beginvertex := uint64(0); beginvertex < shp.vertexSize; beginvertex += segmentVertexSize {\n\t\twg.Add(1)\n\t\tgo func(begin, end uint64) {\n\t\t\tdefer wg.Done()\n\t\t\tfor vertex := begin; vertex != end; vertex++ {\n\t\t\t\tminGain, target := shp.calcSingleGain(shp.graph.Nodes[vertex])\n\t\t\t\tif minGain < 0 {\n\t\t\t\t\tshp.vertex2Target[vertex] = target\n\t\t\t\t\tatomic.AddUint64(&shp.vertexTrans[shp.vertex2Bucket[vertex]][target], 1)\n\t\t\t\t\ttp := atomic.AddInt64(&shp.tf.bufferSize, 1)\n\t\t\t\t\tshp.tf.buffer[tp-1] = vertex\n\t\t\t\t}\n\t\t\t}\n\t\t}(beginvertex, min(beginvertex+segmentVertexSize, shp.vertexSize))\n\t}\n\twg.Wait()\n\t// fmt.Println(shp.tf.bufferSize)\n}", "func TestBackoffConcurrentSimulation(t *testing.T) {\n\tif !(*sim) {\n\t\tt.Log(\"Skipping sim since -sim not passed\")\n\t\tt.Skip()\n\t}\n\n\tconst (\n\t\tperSecond = 1000\n\t\ttestSeconds = 1\n\t\titerations = testSeconds * perSecond\n\t)\n\n\twg := sync.WaitGroup{}\n\n\tc := Capped{cap: 10}\n\tlimiter := New(Config{\n\t\tCapacity: 100,\n\t\tMaxLimit: 20,\n\t})\n\n\tfor i := 0; i < 2; i++ {\n\t\tpriority := i * 10\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tinner := sync.WaitGroup{}\n\n\t\t\tsuccess := int64(0)\n\n\t\t\tfor i := 0; i < iterations; i++ {\n\t\t\t\ttime.Sleep(msToWait(perSecond))\n\t\t\t\tinner.Add(1)\n\n\t\t\t\tgo func() {\n\n\t\t\t\t\tdefer inner.Done()\n\t\t\t\t\tb := Backoff{\n\t\t\t\t\t\tLimiter: &limiter,\n\t\t\t\t\t\tStep: 10 * time.Millisecond,\n\t\t\t\t\t\tPriority: priority,\n\t\t\t\t\t}\n\t\t\t\t\tdefer b.Close()\n\n\t\t\t\t\tfor b.Try(context.Background()) {\n\n\t\t\t\t\t\terr := c.Lock()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttime.Sleep(msToWait(100))\n\n\t\t\t\t\t\tc.Unlock()\n\n\t\t\t\t\t\tatomic.AddInt64(&success, 1)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\t// Wait for the inner loop to finish\n\t\t\tinner.Wait()\n\n\t\t\tt.Logf(\"priority=%d, limit=%d, success=%f\", priority, limiter.limit, (float64(success) / (iterations)))\n\n\t\t}()\n\t}\n\n\twg.Wait()\n\n}", "func (o *GradientDescent) updateParams() {\n\tvar wg sync.WaitGroup\n\tfor key := range o.observed {\n\t\tif key.HasGrad() {\n\t\t\twg.Add(1)\n\t\t\tgo func(param Optimizable) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tdelta := o.method.Delta(param)\n\t\t\t\tparam.ApplyDelta(delta)\n\t\t\t}(key)\n\t\t}\n\t}\n\twg.Wait()\n}", "func (honest *Honest) computeUpdate(iterationCount int) {\n\tprevModel := honest.bc.getLatestGradient()\n\t//outLog.Printf(\"Global Model:%s\", prevModel)\n\tdeltas, err := oneGradientStep(prevModel) // TODO: Create commitment here\n\n\t// outLog.Printf(strconv.Itoa(client.id)+\":Computed update as %s\\n\", deltas)\n\n\tif DP_IN_MODEL {\n\t\tnoise,err := honest.requestNoise(iterationCount)\n\t\tcheck(err)\n\t\tfor i := 0; i < len(noise); i++ {\n\n\t\t\tdeltas[i] = deltas[i] + noise[i]\n\t\t}\n\t}\n\t\n\t//outLog.Printf(\"Deltas:%s\", deltas)\n\t// outLog.Printf(\"This update float:%s\", deltas)\n\tdeltasInt := updateFloatToInt(deltas, PRECISION)\n\t// outLog.Printf(\"This update:%s\", deltasInt)\n\n\tupdateCommitment := createCommitment(deltasInt, client.Keys.CommitmentKey.PKG1)\n\tbyteCommitment, err := updateCommitment.MarshalBinary()\n\tcheck(err)\n\thonest.update = Update{\n\t\tSourceID: honest.id,\n\t\tIteration: iterationCount, \n\t\tCommitment: byteCommitment,\n\t\tDelta: deltas, \n\t\tNoisedDelta: deltas, \n\t\tNoise: deltas,\n\t\tAccepted: true}\n\t\n\t//outLog.Printf(\"Deltas:%s\", honest.update.Delta)\n\n}", "func (th *Throttler) bufferize() {\n\tswitch th.mode {\n\tcase Discard:\n\t\tfor e := range th.in {\n\t\t\tselect {\n\t\t\tcase th.out <- e:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\tcase Backpressure:\n\t\tfor e := range th.in {\n\t\t\tth.out <- e\n\t\t}\n\tdefault:\n\t\tpanic(\"Unsupported ThrottleMode\")\n\t}\n\tclose(th.done)\n\tclose(th.out)\n\tclose(th.notify)\n}", "func (f GoWallet)Free(){\n C.walletFree(f.cxxwallet)\n}", "func (c *Client) flush() {\n\tsubmissions := make([]*Request, 0, len(c.requests)+1)\n\tif c.newMetrics {\n\t\tc.newMetrics = false\n\t\tr := c.newRequest(RequestTypeGenerateMetrics)\n\t\tpayload := &Metrics{\n\t\t\tNamespace: c.Namespace,\n\t\t\tLibLanguage: \"go\",\n\t\t\tLibVersion: version.Tag,\n\t\t}\n\t\tfor _, m := range c.metrics {\n\t\t\ts := Series{\n\t\t\t\tMetric: m.name,\n\t\t\t\tType: string(m.kind),\n\t\t\t\tTags: m.tags,\n\t\t\t\tCommon: m.common,\n\t\t\t}\n\t\t\ts.Points = [][2]float64{{m.ts, m.value}}\n\t\t\tpayload.Series = append(payload.Series, s)\n\t\t}\n\t\tr.Payload = payload\n\t\tsubmissions = append(submissions, r)\n\t}\n\n\t// copy over requests so we can do the actual submission without holding\n\t// the lock. Zero out the old stuff so we don't leak references\n\tfor i, r := range c.requests {\n\t\tsubmissions = append(submissions, r)\n\t\tc.requests[i] = nil\n\t}\n\tc.requests = c.requests[:0]\n\n\tgo func() {\n\t\tfor _, r := range submissions {\n\t\t\terr := c.submit(r)\n\t\t\tif err != nil {\n\t\t\t\tc.log(\"telemetry submission failed: %s\", err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (_m *BandwidthThrottlerSvc) Wait() {\n\t_m.Called()\n}", "func (z *Writer) freeBuffers() {\n\t// Put the buffer back into the pool, if any.\n\tputBuffer(z.Header.BlockMaxSize, z.data)\n\tz.data = nil\n}", "func (p *Poly) reduce() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = barretReduce(p[i])\n\t}\n}", "func (m *NN) Fit(x, y [][]float64, para TrainingParameter) {\n\tnewX := make([][]float64, 0, 2*len(x)+1)\n\tnewY := make([][]float64, 0, 2*len(y)+1)\n\n\tfor i := 0; i < len(x); i++ {\n\t\tnewX = append(newX, x[i])\n\t\tnewX = append(newX, x[i])\n\t\tnewY = append(newY, y[i])\n\t\tnewY = append(newY, y[i])\n\t}\n\tx = newX\n\ty = newY\n\t//============================================================\n\tinputX := x\n\tinputY := y\n\n\t//Normalize the input data. And stock the information into m.FitStock.\n\tS := Stock{}\n\tif m.Normal {\n\t\tinputX, S.meanListX, S.stdListX = Normalized(x)\n\t\tinputY, S.meanListY, S.stdListY = Normalized(y)\n\t}\n\n\t// set S into struct m.\n\tm.FitStock = S\n\n\t// reshape data\n\tflattenX := ToOneDimSlice(inputX)\n\tflattenY := ToOneDimSlice(inputY)\n\tsampleSize := len(inputX)\n\n\tif sampleSize != len(inputY) {\n\t\tpanic(\"x and y are not in the same size!\")\n\t}\n\n\t// Define shapes\n\tinputShape := m.W[0].Shape()[0]\n\toutputShape := m.W[len(m.W)-1].Shape()[1]\n\n\t// batch size will not greater than sample size and won't less than 2. Since batch size equal to 1 will crash the model.\n\tbatchSize, batches := CalBatch(sampleSize, para.BatchSize)\n\n\t// Construct the input data tensor and node.\n\txT := tensor.New(tensor.WithBacking(flattenX), tensor.WithShape(sampleSize, inputShape))\n\tyT := tensor.New(tensor.WithBacking(flattenY), tensor.WithShape(sampleSize, outputShape))\n\n\t// costVal will be used outside the loop.\n\tvar costVal gorgonia.Value\n\n\tdelivery := paraDelivery{\n\t\tbatches: batches,\n\t\tbatchsize: batchSize,\n\t\tinputShape: inputShape,\n\t\toutputShape: outputShape,\n\t\tcostVal: costVal,\n\t\tpara: para,\n\t\tsamplesize: sampleSize,\n\t\tS: S,\n\t}\n\n\t// Since different optimizer are not the same type. We should rewrite code.\n\t\n\tif para.Solver == \"Adam\" {\n\t\tm._AdamTrain(xT, yT, delivery)\n\t} /* else if para.Solver == \"RMSProp\" {\n\t\tm._RMSPropTrain(xT, yT, delivery)\n\t} */\n\tlog.Printf(\"training finish!\")\n}", "func Sync() Fitting {\n\treturn &syncFitting{}\n}", "func (_Token *TokenFilterer) FilterFreeze(opts *bind.FilterOpts, from []common.Address) (*TokenFreezeIterator, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.FilterLogs(opts, \"Freeze\", fromRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenFreezeIterator{contract: _Token.contract, event: \"Freeze\", logs: logs, sub: sub}, nil\n}", "func (joint Joint) Free() {\n\n\tif joint.joint != nil {\n\t\tC.skeltrack_joint_free(joint.joint)\n\t}\n}" ]
[ "0.5931735", "0.59271103", "0.5713689", "0.54602486", "0.5445745", "0.5433887", "0.5389751", "0.536787", "0.5143105", "0.5045885", "0.5007846", "0.50046474", "0.49904928", "0.49764717", "0.49014533", "0.48751804", "0.483695", "0.48262054", "0.48064995", "0.48045477", "0.47849074", "0.4778334", "0.47772396", "0.47591153", "0.47590262", "0.4757463", "0.47267082", "0.4724171", "0.4712435", "0.4707917", "0.46784538", "0.46781543", "0.4671618", "0.46714896", "0.46534768", "0.46431634", "0.4607945", "0.4577291", "0.45706505", "0.45457205", "0.4502558", "0.44696587", "0.445604", "0.44267833", "0.4423547", "0.44097766", "0.4406139", "0.439951", "0.4399116", "0.4398738", "0.43931806", "0.4390001", "0.43751037", "0.43725842", "0.4368", "0.43617162", "0.43579072", "0.43561912", "0.43548477", "0.43470538", "0.43370157", "0.43239573", "0.43226704", "0.43194118", "0.43163812", "0.43152854", "0.431467", "0.42963055", "0.42901742", "0.42875373", "0.42872503", "0.4279074", "0.42614576", "0.42349255", "0.42282608", "0.4215104", "0.4209212", "0.42082074", "0.41952893", "0.41918132", "0.4187289", "0.41684905", "0.4162725", "0.41620964", "0.41616803", "0.4160034", "0.4154802", "0.41432902", "0.4140264", "0.41311416", "0.4128541", "0.4127703", "0.41191715", "0.41090888", "0.41089395", "0.41032565", "0.40946087", "0.40875307", "0.40841314", "0.40840542" ]
0.66387415
0
rej fills a with coefs in [0, Q) generated with buf using rejection sampling
func rej(a []int16, buf []byte) int { ctr, buflen, alen := 0, len(buf), len(a) for pos := 0; pos+3 <= buflen && ctr < alen; pos += 3 { val0 := (uint16(buf[pos]) | (uint16(buf[pos+1]) << 8)) & 0xfff val1 := (uint16(buf[pos+1]>>4) | (uint16(buf[pos+2]) << 4)) & 0xfff if val0 < uint16(q) { a[ctr] = int16(val0) ctr++ } if val1 < uint16(q) && ctr != alen { a[ctr] = int16(val1) ctr++ } } return ctr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *answer) reject(msgs []rpccapnp.Message, err error) []rpccapnp.Message {\n\tif err == nil {\n\t\tpanic(\"answer.reject called with nil\")\n\t}\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.done {\n\t\tpanic(\"answer.reject called more than once\")\n\t}\n\ta.err, a.done = err, true\n\tm := newReturnMessage(nil, a.id)\n\tmret, _ := m.Return()\n\tsetReturnException(mret, err)\n\tmsgs = append(msgs, m)\n\tfor i := range a.queue {\n\t\tmsgs = a.queue[i].a.reject(msgs, err)\n\t\ta.queue[i] = pcall{}\n\t}\n\tclose(a.resolved)\n\treturn msgs\n}", "func PSRLDQ(i, x operand.Op) { ctx.PSRLDQ(i, x) }", "func (s *sink) requeueUnattemptedReq(req *produceRequest, err error) {\n\tvar maybeDrain bool\n\treq.batches.onEachFirstBatchWhileBatchOwnerLocked(func(batch seqRecBatch) {\n\t\t// If we fail all records here, we likely will have out of\n\t\t// order seq nums; hopefully the client user does not stop\n\t\t// on data loss, since this is not truly data loss.\n\t\tif batch.isTimedOut(s.cl.cfg.recordTimeout) {\n\t\t\tbatch.owner.lockedFailAllRecords(ErrRecordTimeout)\n\t\t} else if batch.tries == s.cl.cfg.retries {\n\t\t\tbatch.owner.lockedFailAllRecords(err)\n\t\t}\n\t\tbatch.owner.resetBatchDrainIdx()\n\t\tmaybeDrain = true\n\t})\n\tif maybeDrain {\n\t\ts.maybeTriggerBackoff(req.backoffSeq)\n\t\ts.maybeDrain()\n\t}\n}", "func RCRQ(ci, mr operand.Op) { ctx.RCRQ(ci, mr) }", "func rrq(rq []byte, file string) []byte {\n\tfilename := ztString(rq[2:])\n\tfmt.Printf(\"RRQ: %s\\n\", filename)\n\tif len(file) != 0 {\n\t\tfmt.Printf(\"Using instead supplied file %s\\n\", filename)\n\t\tfilename = file\n\t}\n\tif !open(filename) {\n\t\treturn terr(\"file not found\")\n\t}\n\treturn data(0)\n}", "func SQRTPD(mx, x operand.Op) { ctx.SQRTPD(mx, x) }", "func RORXQ(i, mr, r operand.Op) { ctx.RORXQ(i, mr, r) }", "func RETFQ(i operand.Op) { ctx.RETFQ(i) }", "func PDEPQ(mr, r, r1 operand.Op) { ctx.PDEPQ(mr, r, r1) }", "func RSQRTPS(mx, x operand.Op) { ctx.RSQRTPS(mx, x) }", "func (qc *queueClient) rejectQueue(msgs []rpccapnp.Message) []rpccapnp.Message {\n\tqc.mu.Lock()\n\tfor {\n\t\tc := qc.pop()\n\t\tif w := c.which(); w == qcallRemoteCall {\n\t\t\tmsgs = c.a.reject(msgs, errQueueCallCancel)\n\t\t} else if w == qcallLocalCall {\n\t\t\tc.f.Reject(errQueueCallCancel)\n\t\t} else if w == qcallDisembargo {\n\t\t\tm := newDisembargoMessage(nil, rpccapnp.Disembargo_context_Which_receiverLoopback, c.embargoID)\n\t\t\td, _ := m.Disembargo()\n\t\t\td.SetTarget(c.embargoTarget)\n\t\t\tmsgs = append(msgs, m)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tqc.mu.Unlock()\n\treturn msgs\n}", "func BSRQ(mr, r operand.Op) { ctx.BSRQ(mr, r) }", "func RCLQ(ci, mr operand.Op) { ctx.RCLQ(ci, mr) }", "func MakeBandReject(h []float64, wf window.Func, stop1, stop2 float64) {\n\ta := make([]float64, len(h))\n\tb := make([]float64, len(h))\n\tMakeLowPass(a, wf, stop1)\n\tMakeHighPass(b, wf, stop2)\n\tfor i := range h {\n\t\th[i] = a[i] + b[i]\n\t}\n}", "func BLSRQ(mr, r operand.Op) { ctx.BLSRQ(mr, r) }", "func SQRTPS(mx, x operand.Op) { ctx.SQRTPS(mx, x) }", "func BEXTRQ(r, mr, r1 operand.Op) { ctx.BEXTRQ(r, mr, r1) }", "func deleteRejected(bidx BIDX) {\n\tif tr, ok := TransactionsRejected[bidx]; ok {\n\t\tif tr.Waiting4 != nil {\n\t\t\tw4i, _ := WaitingForInputs[tr.Waiting4.BIdx()]\n\t\t\tdelete(w4i.Ids, bidx)\n\t\t\tif len(w4i.Ids) == 0 {\n\t\t\t\tWaitingForInputsSize -= uint64(w4i.TxLen)\n\t\t\t\tdelete(WaitingForInputs, tr.Waiting4.BIdx())\n\t\t\t}\n\t\t}\n\t\tif tr.Tx != nil {\n\t\t\tTransactionsRejectedSize -= uint64(TransactionsRejected[bidx].Size)\n\t\t}\n\t\tdelete(TransactionsRejected, bidx)\n\t}\n}", "func PSRLQ(imx, x operand.Op) { ctx.PSRLQ(imx, x) }", "func (c *Context) RETFQ(i operand.Op) {\n\tc.addinstruction(x86.RETFQ(i))\n}", "func respondTransferReject(ctx context.Context, masterDB *db.DB,\r\n\tholdingsChannel *holdings.CacheChannel, config *node.Config, w *node.ResponseWriter,\r\n\ttransferTx *inspector.Transaction, transfer *actions.Transfer, rk *wallet.Key, code uint32,\r\n\tstarted bool, text string) error {\r\n\r\n\tv := ctx.Value(node.KeyValues).(*node.Values)\r\n\r\n\t// Determine UTXOs to fund the reject response.\r\n\tutxos, err := transferTx.UTXOs().ForAddress(rk.Address)\r\n\tif err != nil {\r\n\t\treturn errors.Wrap(err, \"Transfer UTXOs not found\")\r\n\t}\r\n\r\n\t// Remove boomerang from funding UTXOs since it was already spent.\r\n\tif started {\r\n\t\t// Remove utxo spent by boomerang\r\n\t\tboomerangIndex := findBoomerangIndex(transferTx, transfer, rk.Address)\r\n\t\tif boomerangIndex != 0xffffffff && transferTx.Outputs[boomerangIndex].Address.Equal(rk.Address) {\r\n\t\t\tfound := false\r\n\t\t\tfor i, utxo := range utxos {\r\n\t\t\t\tif utxo.Index == boomerangIndex {\r\n\t\t\t\t\tfound = true\r\n\t\t\t\t\tutxos = append(utxos[:i], utxos[i+1:]...) // Remove\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif !found {\r\n\t\t\t\treturn errors.New(\"Boomerang output not found\")\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tbalance := uint64(0)\r\n\tfor _, utxo := range utxos {\r\n\t\tbalance += uint64(utxo.Value)\r\n\t}\r\n\r\n\tupdates := make(map[bitcoin.Hash20]*map[bitcoin.Hash20]*state.Holding)\r\n\r\n\tw.SetRejectUTXOs(ctx, utxos)\r\n\r\n\t// Add refund amounts for all bitcoin senders (if \"first\" contract, first contract receives bitcoin funds to be distributed)\r\n\tfirst := firstContractOutputIndex(transfer.Assets, transferTx)\r\n\tif first == 0xffff {\r\n\t\treturn errors.New(\"First contract output index not found\")\r\n\t}\r\n\r\n\t// Determine if this contract is the first contract and needs to send a refund.\r\n\tif !transferTx.Outputs[first].Address.Equal(rk.Address) {\r\n\t\treturn errors.New(\"This is not the first contract\")\r\n\t}\r\n\r\n\trefundBalance := uint64(0)\r\n\tfor assetOffset, assetTransfer := range transfer.Assets {\r\n\t\tif assetTransfer.AssetType == protocol.BSVAssetID && len(assetTransfer.AssetCode) == 0 {\r\n\t\t\t// Process bitcoin senders refunds\r\n\t\t\tfor _, sender := range assetTransfer.AssetSenders {\r\n\t\t\t\tif int(sender.Index) >= len(transferTx.Inputs) {\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\r\n\t\t\t\tnode.LogVerbose(ctx, \"Bitcoin refund %d : %s\", sender.Quantity,\r\n\t\t\t\t\tbitcoin.NewAddressFromRawAddress(transferTx.Inputs[sender.Index].Address,\r\n\t\t\t\t\t\tw.Config.Net))\r\n\t\t\t\tw.AddRejectValue(ctx, transferTx.Inputs[sender.Index].Address, sender.Quantity)\r\n\t\t\t\trefundBalance += sender.Quantity\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Add all other senders to be notified\r\n\t\t\tfor _, sender := range assetTransfer.AssetSenders {\r\n\t\t\t\tif int(sender.Index) >= len(transferTx.Inputs) {\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\r\n\t\t\t\tw.AddRejectValue(ctx, transferTx.Inputs[sender.Index].Address, 0)\r\n\t\t\t}\r\n\r\n\t\t\tif started { // Revert holding statuses\r\n\t\t\t\tif len(transferTx.Outputs) <= int(assetTransfer.ContractIndex) {\r\n\t\t\t\t\treturn fmt.Errorf(\"Contract index out of range for asset %d\", assetOffset)\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif !transferTx.Outputs[assetTransfer.ContractIndex].Address.Equal(rk.Address) {\r\n\t\t\t\t\tcontinue // This asset is not ours. Skip it.\r\n\t\t\t\t}\r\n\r\n\t\t\t\tassetCode, err := bitcoin.NewHash20(assetTransfer.AssetCode)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn errors.Wrap(err, \"invalid asset code\")\r\n\t\t\t\t}\r\n\t\t\t\tupdatedHoldings := make(map[bitcoin.Hash20]*state.Holding)\r\n\t\t\t\tupdates[*assetCode] = &updatedHoldings\r\n\r\n\t\t\t\t// Revert sender pending statuses\r\n\t\t\t\tfor _, sender := range assetTransfer.AssetSenders {\r\n\t\t\t\t\t// Revert holding status\r\n\t\t\t\t\th, err := holdings.GetHolding(ctx, masterDB, rk.Address, assetCode,\r\n\t\t\t\t\t\ttransferTx.Inputs[sender.Index].Address, v.Now)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"get holding\")\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\thash, err := transferTx.Inputs[sender.Index].Address.Hash()\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"sender address hash\")\r\n\t\t\t\t\t}\r\n\t\t\t\t\tupdatedHoldings[*hash] = h\r\n\r\n\t\t\t\t\t// Revert holding status\r\n\t\t\t\t\terr = holdings.RevertStatus(h, transferTx.Hash)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"revert status\")\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Revert receiver pending statuses\r\n\t\t\t\tfor _, receiver := range assetTransfer.AssetReceivers {\r\n\t\t\t\t\treceiverAddress, err := bitcoin.DecodeRawAddress(receiver.Address)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn err\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\th, err := holdings.GetHolding(ctx, masterDB, rk.Address, assetCode,\r\n\t\t\t\t\t\treceiverAddress, v.Now)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"get holding\")\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\thash, err := receiverAddress.Hash()\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"receiver address hash\")\r\n\t\t\t\t\t}\r\n\t\t\t\t\tupdatedHoldings[*hash] = h\r\n\r\n\t\t\t\t\t// Revert holding status\r\n\t\t\t\t\terr = holdings.RevertStatus(h, transferTx.Hash)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\treturn errors.Wrap(err, \"revert status\")\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif started {\r\n\t\terr = saveHoldings(ctx, masterDB, holdingsChannel, updates, rk.Address)\r\n\t\tif err != nil {\r\n\t\t\treturn errors.Wrap(err, \"save holdings\")\r\n\t\t}\r\n\t}\r\n\r\n\tif refundBalance > balance {\r\n\t\tct, err := contract.Retrieve(ctx, masterDB, rk.Address, config.IsTest)\r\n\t\tif err != nil {\r\n\t\t\treturn errors.Wrap(err, \"Failed to retrieve contract\")\r\n\t\t}\r\n\r\n\t\t// Funding not enough to refund everyone, so don't refund to anyone. Send it to the\r\n\t\t// administration to hold.\r\n\t\tw.ClearRejectOutputValues(ct.AdminAddress)\r\n\t}\r\n\r\n\treturn node.RespondRejectText(ctx, w, transferTx, rk, code, text)\r\n}", "func BTRQ(ir, mr operand.Op) { ctx.BTRQ(ir, mr) }", "func (rl *RateLimit) relinquish() {\n\tfor {\n\t\tif rl.quotaLeft > 2*rl.baseQuota {\n\t\t\tok, err := rl.lock.Acquire()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\terr = rl.lock.Release()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tif ok {\n\t\t\t\trl.quotaLock.Lock()\n\t\t\t\trl.usableQuotaLeft = rl.usableQuotaLeft + rl.quotaLeft - rl.baseQuota\n\t\t\t\trl.quotaLeft = rl.baseQuota\n\t\t\t\tlog.Println(\"had too much quota, relinquising \", rl.quotaLeft-rl.baseQuota)\n\t\t\t\terr := rl.set(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"updating usable quota failed \", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(15 * time.Second)\n\t}\n}", "func qr_decoder_set_image_buffer(p _QrDecoderHandle, src *_IplImage) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_buffer(C.QrDecoderHandle(p), (*C.IplImage)(src))\n\treturn _QrDecoderHandle(v)\n}", "func (m *RecommendationsItemImpactedResourcesImpactedResourceItemRequestBuilder) Reactivate()(*RecommendationsItemImpactedResourcesItemReactivateRequestBuilder) {\n return NewRecommendationsItemImpactedResourcesItemReactivateRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (rp *Reprovider) Reprovide() error {\n\tkeychan, err := rp.keyProvider(rp.ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get key chan: %s\", err)\n\t}\n\tfor c := range keychan {\n\t\t// hash security\n\t\tif err := verifcid.ValidateCid(c); err != nil {\n\t\t\tlog.Errorf(\"insecure hash in reprovider, %s (%s)\", c, err)\n\t\t\tcontinue\n\t\t}\n\t\top := func() error {\n\t\t\terr := rp.rsys.Provide(rp.ctx, c, true)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debugf(\"Failed to provide key: %s\", err)\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO: this backoff library does not respect our context, we should\n\t\t// eventually work contexts into it. low priority.\n\t\terr := backoff.Retry(op, backoff.NewExponentialBackOff())\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Providing failed after number of retries: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (_m *ORM) RejectSpec(id int64, qopts ...pg.QOpt) error {\n\t_va := make([]interface{}, len(qopts))\n\tfor _i := range qopts {\n\t\t_va[_i] = qopts[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, id)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(int64, ...pg.QOpt) error); ok {\n\t\tr0 = rf(id, qopts...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func BSFQ(mr, r operand.Op) { ctx.BSFQ(mr, r) }", "func dgeqrf(m, n int, a []float64, lda int, tau []float64) error {\n\t// Query workspace size.\n\twork := make([]float64, 1)\n\terr := dgeqrfHelper(m, n, a, lda, tau, work, -1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlwork := int(work[0])\n\twork = make([]float64, max(1, lwork))\n\treturn dgeqrfHelper(m, n, a, lda, tau, work, lwork)\n}", "func (a *answer) fulfill(msgs []rpccapnp.Message, obj capnp.Pointer, makeCapTable capTableMaker) []rpccapnp.Message {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.done {\n\t\tpanic(\"answer.fulfill called more than once\")\n\t}\n\ta.obj, a.done = obj, true\n\t// TODO(light): populate resultCaps\n\n\tretmsg := newReturnMessage(nil, a.id)\n\tret, _ := retmsg.Return()\n\tpayload, _ := ret.NewResults()\n\tpayload.SetContent(obj)\n\tpayloadTab, err := makeCapTable(ret.Segment())\n\tif err != nil {\n\t\t// TODO(light): handle this more gracefully\n\t\tpanic(err)\n\t}\n\tpayload.SetCapTable(payloadTab)\n\tmsgs = append(msgs, retmsg)\n\n\tqueues, msgs := a.emptyQueue(msgs, obj)\n\tctab := obj.Segment().Message().CapTable\n\tfor capIdx, q := range queues {\n\t\tctab[capIdx] = newQueueClient(a.manager, ctab[capIdx], q, a.out, a.queueCloses)\n\t}\n\tclose(a.resolved)\n\treturn msgs\n}", "func zrqt02(m, n, k int, a, af, q, r *mat.CMatrix, tau, work *mat.CVector, lwork int, rwork, result *mat.Vector) {\n\tvar rogue complex128\n\tvar anorm, eps, one, resid, zero float64\n\tvar err error\n\n\tzero = 0.0\n\tone = 1.0\n\trogue = (-1.0e+10 + (-1.0e+10)*1i)\n\tsrnamt := &gltest.Common.Srnamc.Srnamt\n\n\t// Quick return if possible\n\tif m == 0 || n == 0 || k == 0 {\n\t\tresult.Set(0, zero)\n\t\tresult.Set(1, zero)\n\t\treturn\n\t}\n\n\teps = golapack.Dlamch(Epsilon)\n\n\t// Copy the last k rows of the factorization to the array Q\n\tgolapack.Zlaset(Full, m, n, rogue, rogue, q)\n\tif k < n {\n\t\tgolapack.Zlacpy(Full, k, n-k, af.Off(m-k, 0), q.Off(m-k, 0))\n\t}\n\tif k > 1 {\n\t\tgolapack.Zlacpy(Lower, k-1, k-1, af.Off(m-k+2-1, n-k), q.Off(m-k+2-1, n-k))\n\t}\n\n\t// Generate the last n rows of the matrix Q\n\t*srnamt = \"Zungrq\"\n\tif err = golapack.Zungrq(m, n, k, q, tau.Off(m-k), work, lwork); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Copy R(m-k+1:m,n-m+1:n)\n\tgolapack.Zlaset(Full, k, m, complex(zero, 0), complex(zero, 0), r.Off(m-k, n-m))\n\tgolapack.Zlacpy(Upper, k, k, af.Off(m-k, n-k), r.Off(m-k, n-k))\n\n\t// Compute R(m-k+1:m,n-m+1:n) - A(m-k+1:m,1:n) * Q(n-m+1:n,1:n)'\n\tif err = r.Off(m-k, n-m).Gemm(NoTrans, ConjTrans, k, m, n, complex(-one, 0), a.Off(m-k, 0), q, complex(one, 0)); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Compute norm( R - A*Q' ) / ( N * norm(A) * EPS ) .\n\tanorm = golapack.Zlange('1', k, n, a.Off(m-k, 0), rwork)\n\tresid = golapack.Zlange('1', k, m, r.Off(m-k, n-m), rwork)\n\tif anorm > zero {\n\t\tresult.Set(0, ((resid/float64(max(1, n)))/anorm)/eps)\n\t} else {\n\t\tresult.Set(0, zero)\n\t}\n\n\t// Compute I - Q*Q'\n\tgolapack.Zlaset(Full, m, m, complex(zero, 0), complex(one, 0), r)\n\tif err = r.Herk(Upper, NoTrans, m, n, -one, q, one); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Compute norm( I - Q*Q' ) / ( N * EPS ) .\n\tresid = golapack.Zlansy('1', Upper, m, r, rwork)\n\n\tresult.Set(1, (resid/float64(max(1, n)))/eps)\n}", "func RORQ(ci, mr operand.Op) { ctx.RORQ(ci, mr) }", "func (i *Internal) Reject(err interface{}, messages ...string) {\n\ti.Rejector <- goerr.Trace(1, err, messages...)\n}", "func PEXTRQ(i, x, mr operand.Op) { ctx.PEXTRQ(i, x, mr) }", "func VRSQRTPS(mxy, xy operand.Op) { ctx.VRSQRTPS(mxy, xy) }", "func VPSRLDQ(i, mxyz, xyz operand.Op) { ctx.VPSRLDQ(i, mxyz, xyz) }", "func (a acknowledger) Reject(requeue bool) (err error) {\n\tastilog.Debugf(\"astiamqp: reject %v with requeue %v\", a.deliveryTag, requeue)\n\tif err = a.acknowledger.Reject(a.deliveryTag, requeue); err != nil {\n\t\terr = errors.Wrapf(err, \"astiamqp: reject %v with requeue %v failed\", a.deliveryTag, requeue)\n\t\treturn\n\t}\n\treturn\n}", "func (q *Queue) RequeueFailed() error {\n\tl := q.GetFailedLength()\n\t// TODO implement this in lua\n\tfor l > 0 {\n\t\terr := q.redisClient.RPopLPush(queueFailedKey(q.Name), queueInputKey(q.Name)).Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tq.incrRate(queueInputRateKey(q.Name), 1)\n\t\tl--\n\t}\n\treturn nil\n}", "func RejectTx(tx *btc.Tx, why byte) *OneTxRejected {\n\trec := new(OneTxRejected)\n\trec.Time = time.Now()\n\trec.Size = uint32(len(tx.Raw))\n\trec.Reason = why\n\n\t// TODO: only store tx for selected reasons\n\tif why >= 200 {\n\t\trec.Tx = tx\n\t\trec.Id = &tx.Hash\n\t\tTransactionsRejectedSize += uint64(rec.Size)\n\t} else {\n\t\trec.Id = new(btc.Uint256)\n\t\trec.Id.Hash = tx.Hash.Hash\n\t}\n\n\tbidx := tx.Hash.BIdx()\n\tTransactionsRejected[bidx] = rec\n\n\tLimitRejectedSize()\n\n\t// try to re-fetch the record from the map, in case it has been removed by LimitRejectedSize()\n\treturn TransactionsRejected[bidx]\n}", "func newPRReject() *prReject {\n\treturn &prReject{prCommon{Type: prTypeReject}}\n}", "func PUNPCKLQDQ(mx, x operand.Op) { ctx.PUNPCKLQDQ(mx, x) }", "func DECQ(mr operand.Op) { ctx.DECQ(mr) }", "func (l *ListHT) Recov(p, n uint64) ([]pb.Command, error) {\n\tif n < p {\n\t\treturn nil, errors.New(\"invalid interval request, 'n' must be >= 'p'\")\n\t}\n\tl.mu.RLock()\n\tdefer l.mu.RUnlock()\n\n\tif err := l.mayExecuteLazyReduce(p, n); err != nil {\n\t\treturn nil, err\n\t}\n\treturn l.retrieveLog()\n}", "func PINSRQ(i, mr, x operand.Op) { ctx.PINSRQ(i, mr, x) }", "func VPINSRQ(i, mr, x, x1 operand.Op) { ctx.VPINSRQ(i, mr, x, x1) }", "func VPUNPCKLQDQ(ops ...operand.Op) { ctx.VPUNPCKLQDQ(ops...) }", "func (p *Pattern) Exc(pred *Pattern) *Pattern {\n\treturn Seq(Not(pred), p)\n}", "func NewReject(requestBody io.Reader) *Reject {\n\ts, _ := ioutil.ReadAll(requestBody)\n\trequestBody = ioutil.NopCloser(bytes.NewBuffer(s))\n\tdecoder := json.NewDecoder(requestBody)\n\tvar t Reject\n\terr := decoder.Decode(&t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &t\n}", "func reparto(r [2]PaqueteCola)[2]PaqueteCola{ \r\n\taux := PaqueteCola{estado:1} //aux para verificar errores en paquetes\r\n\tnormal := \"normal\"\r\n\tprioritario := \"prioritario\"\r\n\tretail := \"retail\"\r\n\tfor iteracion,p := range r{\r\n\t\ttime.Sleep(time.Duration(sleeptime) * time.Second)\r\n\t\tif reflect.DeepEqual(p,aux){ //caso base reviso si esta vacio (estado en camino)\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t// cantidad de intentos son 3 (retail 3 si o si y pyme 1+2 reintentos si es valor positivo)\r\n\t\tfor k := 0 ; k < 4 ; k++{\r\n\t\t\tvar t int\r\n\t\t\tif k==3{ //paquete en intento numero 4\r\n\t\t\t\tp.estado = 3\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"No me quieren\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\tif p.tipo == normal{\r\n\t\t\t\tt = 1\r\n\t\t\t}\r\n\t\t\tif p.tipo == prioritario{\r\n\t\t\t\tt = 2\r\n\t\t\t}\r\n\t\t\tif p.tipo == retail{\r\n\t\t\t\tt = 3\r\n\t\t\t}\r\n\t\t\tif t<=2 && int64(k)*10>p.valor{ //condiciones para pyme\r\n\t\t\t\tp.estado = 3\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"No me quieren\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\t//abajo genero numero random entre 0-100 para el 80%\r\n\t\t\ts1 := rand.NewSource(time.Now().UnixNano())\r\n\t\t\tr1 := rand.New(s1)\r\n\t\t\texito := r1.Intn(101)\r\n\r\n\t\t\tif exito < 80{ //si el numero es entre 0-80 exito en la entrega\r\n\t\t\t\tp.estado = 2\r\n\t\t\t\tp.fecha = time.Now().Format(\"02-01-2006 15:04:05\")\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"Me recibieron\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\tr[iteracion]=p\r\n\t}\r\n\treturn r //retorno el mismo camion(array) que entro\r\n}", "func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper, isCounter, isRate bool) Vector {\n\tms := args[0].(*parser.MatrixSelector)\n\tvs := ms.VectorSelector.(*parser.VectorSelector)\n\tvar (\n\t\tsamples = vals[0].(Matrix)[0]\n\t\trangeStart = enh.Ts - durationMilliseconds(ms.Range+vs.Offset)\n\t\trangeEnd = enh.Ts - durationMilliseconds(vs.Offset)\n\t\tresultFloat float64\n\t\tresultHistogram *histogram.FloatHistogram\n\t\tfirstT, lastT int64\n\t\tnumSamplesMinusOne int\n\t)\n\n\t// We need either at least two Histograms and no Floats, or at least two\n\t// Floats and no Histograms to calculate a rate. Otherwise, drop this\n\t// Vector element.\n\tif len(samples.Histograms) > 0 && len(samples.Floats) > 0 {\n\t\t// Mix of histograms and floats. TODO(beorn7): Communicate this failure reason.\n\t\treturn enh.Out\n\t}\n\n\tswitch {\n\tcase len(samples.Histograms) > 1:\n\t\tnumSamplesMinusOne = len(samples.Histograms) - 1\n\t\tfirstT = samples.Histograms[0].T\n\t\tlastT = samples.Histograms[numSamplesMinusOne].T\n\t\tresultHistogram = histogramRate(samples.Histograms, isCounter)\n\t\tif resultHistogram == nil {\n\t\t\t// The histograms are not compatible with each other.\n\t\t\t// TODO(beorn7): Communicate this failure reason.\n\t\t\treturn enh.Out\n\t\t}\n\tcase len(samples.Floats) > 1:\n\t\tnumSamplesMinusOne = len(samples.Floats) - 1\n\t\tfirstT = samples.Floats[0].T\n\t\tlastT = samples.Floats[numSamplesMinusOne].T\n\t\tresultFloat = samples.Floats[numSamplesMinusOne].F - samples.Floats[0].F\n\t\tif !isCounter {\n\t\t\tbreak\n\t\t}\n\t\t// Handle counter resets:\n\t\tprevValue := samples.Floats[0].F\n\t\tfor _, currPoint := range samples.Floats[1:] {\n\t\t\tif currPoint.F < prevValue {\n\t\t\t\tresultFloat += prevValue\n\t\t\t}\n\t\t\tprevValue = currPoint.F\n\t\t}\n\tdefault:\n\t\t// Not enough samples. TODO(beorn7): Communicate this failure reason.\n\t\treturn enh.Out\n\t}\n\n\t// Duration between first/last samples and boundary of range.\n\tdurationToStart := float64(firstT-rangeStart) / 1000\n\tdurationToEnd := float64(rangeEnd-lastT) / 1000\n\n\tsampledInterval := float64(lastT-firstT) / 1000\n\taverageDurationBetweenSamples := sampledInterval / float64(numSamplesMinusOne)\n\n\t// TODO(beorn7): Do this for histograms, too.\n\tif isCounter && resultFloat > 0 && len(samples.Floats) > 0 && samples.Floats[0].F >= 0 {\n\t\t// Counters cannot be negative. If we have any slope at all\n\t\t// (i.e. resultFloat went up), we can extrapolate the zero point\n\t\t// of the counter. If the duration to the zero point is shorter\n\t\t// than the durationToStart, we take the zero point as the start\n\t\t// of the series, thereby avoiding extrapolation to negative\n\t\t// counter values.\n\t\tdurationToZero := sampledInterval * (samples.Floats[0].F / resultFloat)\n\t\tif durationToZero < durationToStart {\n\t\t\tdurationToStart = durationToZero\n\t\t}\n\t}\n\n\t// If the first/last samples are close to the boundaries of the range,\n\t// extrapolate the result. This is as we expect that another sample\n\t// will exist given the spacing between samples we've seen thus far,\n\t// with an allowance for noise.\n\textrapolationThreshold := averageDurationBetweenSamples * 1.1\n\textrapolateToInterval := sampledInterval\n\n\tif durationToStart < extrapolationThreshold {\n\t\textrapolateToInterval += durationToStart\n\t} else {\n\t\textrapolateToInterval += averageDurationBetweenSamples / 2\n\t}\n\tif durationToEnd < extrapolationThreshold {\n\t\textrapolateToInterval += durationToEnd\n\t} else {\n\t\textrapolateToInterval += averageDurationBetweenSamples / 2\n\t}\n\tfactor := extrapolateToInterval / sampledInterval\n\tif isRate {\n\t\tfactor /= ms.Range.Seconds()\n\t}\n\tif resultHistogram == nil {\n\t\tresultFloat *= factor\n\t} else {\n\t\tresultHistogram.Mul(factor)\n\t}\n\n\treturn append(enh.Out, Sample{F: resultFloat, H: resultHistogram})\n}", "func (queue *Queue) RequeueFailed() error {\n\tl := queue.GetFailedLength()\n\t// TODO implement this in lua\n\tfor l > 0 {\n\t\terr := queue.redisClient.RPopLPush(queueFailedKey(queue.Name), queueInputKey(queue.Name)).Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tqueue.incrRate(queueInputRateKey(queue.Name), 1)\n\t\tl--\n\t}\n\treturn nil\n}", "func (n *resPool) dequeue(\n\tqt QueueType,\n\tlimit int) ([]*resmgrsvc.Gang, error) {\n\tvar err error\n\tvar gangList []*resmgrsvc.Gang\n\n\tif limit <= 0 {\n\t\treturn gangList, nil\n\t}\n\n\tfor i := 0; i < limit; i++ {\n\t\tgangs, err := n.queue(qt).Peek(1)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(queue.ErrorQueueEmpty); ok {\n\t\t\t\t// queue is empty we are done\n\t\t\t\treturn gangList, nil\n\t\t\t}\n\t\t\tlog.WithError(err).Error(\"Failed to peek into queue\")\n\t\t\treturn gangList, err\n\t\t}\n\t\tgang := gangs[0]\n\t\terr = admission.TryAdmit(gang, n, qt)\n\t\tif err != nil {\n\t\t\tif err == errGangInvalid ||\n\t\t\t\terr == errSkipNonPreemptibleGang ||\n\t\t\t\terr == errSkipControllerGang ||\n\t\t\t\terr == errSkipRevocableGang {\n\t\t\t\t// the admission can fail :\n\t\t\t\t// 1. Because the gang is invalid.\n\t\t\t\t// In this case we move on to the next gang in the queue with the\n\t\t\t\t// expectation that the invalid gang is removed from the head of\n\t\t\t\t// the queue.\n\t\t\t\t// 2. Because the gang should be skipped (\n\t\t\t\t// revocable gang, controller gang or non-preemptible gang)\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"respool_id\": n.id,\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t}).Debug(\"skipping gang from admission\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tgangList = append(gangList, gang)\n\t}\n\treturn gangList, err\n}", "func (r *Resampler) Write(p []byte) (out []byte, err error) {\n\t//fmt.Println(\"Write channels:\", r.channels)\n\tif r.resampler == nil {\n\t\terr = errors.New(\"soxr resampler is nil\")\n\t\treturn\n\t}\n\tif len(p) == 0 {\n\t\treturn\n\t}\n\tframesIn := len(p) / r.frameSize / r.channels\n\tif framesIn == 0 {\n\t\terr = errors.New(\"Incomplete input frame data\")\n\t\treturn\n\t}\n\tif len(p)%(r.frameSize*r.channels) != 0 {\n\t\terr = errors.New(\"Fragmented last frame in input data\")\n\t\treturn\n\t}\n\tframesOut := int(float64(framesIn) * (r.outRate / r.inRate))\n\tif framesOut == 0 {\n\t\terr = errors.New(\"Not enough input to generate output\")\n\t\treturn\n\t}\n\n\tdataIn := C.CBytes(p)\n\tdataOut := C.malloc(C.size_t(framesOut*r.channels*r.frameSize + 4))\n\tvar soxErr C.soxr_error_t\n\tvar read1, read2, done1, done2 C.size_t = 0, 0, 0, 0\n\tbuf := make([]byte, 0)\n\tsoxErr = C.soxr_process(r.resampler, C.soxr_in_t(dataIn), C.size_t(framesIn), &read1, C.soxr_out_t(dataOut), C.size_t(framesOut), &done1)\n\tif C.GoString(soxErr) != \"\" && C.GoString(soxErr) != \"0\" {\n\t\terr = errors.New(C.GoString(soxErr))\n\t\tgoto cleanup\n\t}\n\n\tbuf = append(buf, C.GoBytes(dataOut, C.int(int(done1)*r.channels*r.frameSize))...)\n\t// Consume any data left in the resampling filter\n\tsoxErr = C.soxr_process(r.resampler, C.soxr_in_t(nil), C.size_t(0), &read2, C.soxr_out_t(dataOut), C.size_t(framesOut), &done2)\n\tif C.GoString(soxErr) != \"\" && C.GoString(soxErr) != \"0\" {\n\t\terr = errors.New(C.GoString(soxErr))\n\t\tgoto cleanup\n\t}\n\n\tbuf = append(buf, C.GoBytes(dataOut, C.int(int(done2)*r.channels*r.frameSize))...)\n\t// If we have read all input and flushed all output, avoid to report short writes due\n\t// to output frames missing because of downsampling or other odd reasons.\n\tout = r.toChannels(buf, len(buf), 2)\ncleanup:\n\tC.free(dataIn)\n\tC.free(dataOut)\n\tC.free(unsafe.Pointer(soxErr))\n\treturn\n}", "func (m Message) RepurchaseRate() (*field.RepurchaseRateField, quickfix.MessageRejectError) {\n\tf := &field.RepurchaseRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) RepurchaseRate() (*field.RepurchaseRateField, quickfix.MessageRejectError) {\n\tf := &field.RepurchaseRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) RepurchaseRate() (*field.RepurchaseRateField, quickfix.MessageRejectError) {\n\tf := &field.RepurchaseRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) RepurchaseRate() (*field.RepurchaseRateField, quickfix.MessageRejectError) {\n\tf := &field.RepurchaseRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func ROLQ(ci, mr operand.Op) { ctx.ROLQ(ci, mr) }", "func opt1d(m1 RegFitter, coeff float64, par Parameter, l1wgt float64, checkstep bool) float64 {\n\n\t// Quadratic approximation coefficients\n\tbv := make([]float64, 1)\n\tpar.SetCoeff([]float64{coeff})\n\tm1.Score(par, bv)\n\tb := -bv[0]\n\tcv := make([]float64, 1)\n\tm1.Hessian(par, ObsHess, cv)\n\tc := -cv[0]\n\n\t// The optimum point of the quadratic approximation\n\td := b - c*coeff\n\n\tif l1wgt > math.Abs(d) {\n\t\t// The optimum is achieved by hard thresholding to zero\n\t\treturn 0\n\t}\n\n\t// pj + h is the minimizer of Q(x) + L1_wt*abs(x)\n\tvar h float64\n\tif d >= 0 {\n\t\th = (l1wgt - b) / c\n\t} else if d < 0 {\n\t\th = -(l1wgt + b) / c\n\t} else {\n\t\tpanic(fmt.Sprintf(\"d=%f\\n\", d))\n\t}\n\n\tif !checkstep {\n\t\treturn coeff + h\n\t}\n\n\t// Check whether the new point improves the target function.\n\t// This check is a bit expensive and not necessary for OLS\n\tpar.SetCoeff([]float64{coeff})\n\tf0 := -m1.LogLike(par, false) + l1wgt*math.Abs(coeff)\n\tpar.SetCoeff([]float64{coeff + h})\n\tf1 := -m1.LogLike(par, false) + l1wgt*math.Abs(coeff+h)\n\tif f1 <= f0+1e-10 {\n\t\treturn coeff + h\n\t}\n\n\t// Wrap the log-likelihood so it takes a scalar argument.\n\tfw := func(z float64) float64 {\n\t\tpar.SetCoeff([]float64{z})\n\t\tf := -m1.LogLike(par, false) + l1wgt*math.Abs(z)\n\t\treturn f\n\t}\n\n\t// Fallback for models where the loss is not quadratic\n\tw := 1.0\n\tbtol := 1e-7\n\tnp := bisection(fw, coeff-w, coeff+w, btol)\n\treturn np\n}", "func VPEXTRQ(i, x, mr operand.Op) { ctx.VPEXTRQ(i, x, mr) }", "func (refreshProtocol *RefreshProtocol) Recode(ciphertext *ckks.Ciphertext, targetScale float64) {\n\tdckksContext := refreshProtocol.dckksContext\n\tringQ := refreshProtocol.dckksContext.ringQ\n\n\tinputScaleFlo := ring.NewFloat(ciphertext.Scale(), 256)\n\toutputScaleFlo := ring.NewFloat(targetScale, 256)\n\n\tinputScaleInt := new(big.Int)\n\toutputScaleInt := new(big.Int)\n\n\tinputScaleFlo.Int(inputScaleInt)\n\toutputScaleFlo.Int(outputScaleInt)\n\n\tringQ.InvNTTLvl(ciphertext.Level(), ciphertext.Value()[0], ciphertext.Value()[0])\n\n\tringQ.PolyToBigint(ciphertext.Value()[0], refreshProtocol.maskBigint)\n\n\tQStart := ring.NewUint(ringQ.Modulus[0])\n\tfor i := 1; i < ciphertext.Level()+1; i++ {\n\t\tQStart.Mul(QStart, ring.NewUint(ringQ.Modulus[i]))\n\t}\n\n\tQHalf := new(big.Int).Rsh(QStart, 1)\n\n\tfor ciphertext.Level() != dckksContext.params.MaxLevel() {\n\t\tciphertext.Value()[0].Coeffs = append(ciphertext.Value()[0].Coeffs, make([][]uint64, 1)...)\n\t\tciphertext.Value()[0].Coeffs[ciphertext.Level()] = make([]uint64, dckksContext.n)\n\t}\n\n\tvar sign int\n\tfor i := 0; i < dckksContext.n; i++ {\n\t\tsign = refreshProtocol.maskBigint[i].Cmp(QHalf)\n\t\tif sign == 1 || sign == 0 {\n\t\t\trefreshProtocol.maskBigint[i].Sub(refreshProtocol.maskBigint[i], QStart)\n\t\t}\n\n\t\trefreshProtocol.maskBigint[i].Mul(refreshProtocol.maskBigint[i], outputScaleInt)\n\t\trefreshProtocol.maskBigint[i].Quo(refreshProtocol.maskBigint[i], inputScaleInt)\n\t}\n\n\tringQ.SetCoefficientsBigintLvl(ciphertext.Level(), refreshProtocol.maskBigint, ciphertext.Value()[0])\n\n\tringQ.NTTLvl(ciphertext.Level(), ciphertext.Value()[0], ciphertext.Value()[0])\n\n\tciphertext.SetScale(targetScale)\n}", "func (f *Regressor) Fit(X [][]float64, Y []float64) {\n\tf.NSample = len(Y)\n\n\tf.nFeatures = len(X[0])\n\n\tf.Trees = make([]*tree.Regressor, f.NTrees)\n\n\tif f.MaxFeatures < 0 {\n\t\tf.MaxFeatures = int(math.Sqrt(float64(f.nFeatures)))\n\t}\n\n\tvar oob *oobRegCtr\n\tif f.computeOOB {\n\t\toob = newOOBRegCtr(len(Y))\n\t}\n\n\tin := make(chan *fitRegTree)\n\tout := make(chan *fitRegTree)\n\n\tnWorkers := f.nWorkers\n\tif nWorkers < 1 {\n\t\tnWorkers = 1\n\t}\n\n\t// start workers\n\tfor i := 0; i < nWorkers; i++ {\n\t\tgo func(id int) {\n\t\t\tfor w := range in {\n\t\t\t\treg := tree.NewRegressor(tree.MinSplit(f.MinSplit), tree.MinLeaf(f.MinLeaf),\n\t\t\t\t\ttree.MaxDepth(f.MaxDepth), tree.MaxFeatures(f.MaxFeatures),\n\t\t\t\t\ttree.RandState(int64(id)*time.Now().UnixNano()))\n\t\t\t\treg.FitInx(X, Y, w.inx)\n\n\t\t\t\tw.t = reg\n\n\t\t\t\tif f.computeOOB {\n\t\t\t\t\toob.update(X, w.inBag, w.t)\n\t\t\t\t}\n\n\t\t\t\tout <- w\n\t\t\t}\n\t\t}(i)\n\t}\n\n\t// fill the queue\n\tgo func() {\n\t\tfor _ = range f.Trees {\n\t\t\tinx, inBag := bootstrapInx(len(X))\n\t\t\tin <- &fitRegTree{inx: inx, inBag: inBag}\n\t\t}\n\t\tclose(in)\n\t}()\n\n\tfor i := range f.Trees {\n\t\tw := <-out\n\t\tf.Trees[i] = w.t\n\t}\n\n\tif f.computeOOB {\n\t\tf.MSE, f.RSquared = oob.compute(Y)\n\t}\n}", "func Reject(reason error) Promise {\n\treturn &rejected{reason}\n}", "func SARXQ(r, mr, r1 operand.Op) { ctx.SARXQ(r, mr, r1) }", "func zerrlqt(path string, _t *testing.T) {\n\tvar i, j, nmax int\n\tvar err error\n\n\tw := cvf(2)\n\ta := cmf(2, 2, opts)\n\tc := cmf(2, 2, opts)\n\tt := cmf(2, 2, opts)\n\n\tnmax = 2\n\terrt := &gltest.Common.Infoc.Errt\n\tok := &gltest.Common.Infoc.Ok\n\tsrnamt := &gltest.Common.Srnamc.Srnamt\n\n\t// Set the variables to innocuous values.\n\tfor j = 1; j <= nmax; j++ {\n\t\tfor i = 1; i <= nmax; i++ {\n\t\t\ta.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tc.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tt.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t}\n\t\tw.Set(j-1, 0.)\n\t}\n\t(*ok) = true\n\n\t// Error exits for LQT factorization\n\t//\n\t// Zgelqt\n\t*srnamt = \"Zgelqt\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgelqt(-1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Zgelqt(0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > min(m, n) && min(m, n) > 0): mb=0, m=0, n=0\")\n\terr = golapack.Zgelqt(0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Zgelqt(2, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Zgelqt(2, 2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\n\t// Zgelqt3\n\t*srnamt = \"Zgelqt3\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgelqt3(-1, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"n < m: m=0, n=-1\")\n\terr = golapack.Zgelqt3(0, -1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Zgelqt3(2, 2, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"t.Rows < max(1, m): t.Rows=1, m=2\")\n\terr = golapack.Zgelqt3(2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\n\t// Zgemlqt\n\t*srnamt = \"Zgemlqt\"\n\t*errt = fmt.Errorf(\"!left && !right: side=Unrecognized: /\")\n\terr = golapack.Zgemlqt('/', NoTrans, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"!tran && !notran: trans=Unrecognized: /\")\n\terr = golapack.Zgemlqt(Left, '/', 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, -1, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, -1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > k && k > 0): mb=0, k=0\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, 0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < max(1, k): v.Rows=1, k=2\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 2, 2, 2, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < max(1, k): v.Rows=1, k=2\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 2, 2, 2, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 1, 1, 2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"c.Rows < max(1, m): c.Rows=1, m=2\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 2, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\n\t// Print a summary line.\n\t// alaesm(path, *ok)\n\n\tif !(*ok) {\n\t\t_t.Fail()\n\t}\n}", "func (c *Context) PSRLDQ(i, x operand.Op) {\n\tc.addinstruction(x86.PSRLDQ(i, x))\n}", "func BLSIQ(mr, r operand.Op) { ctx.BLSIQ(mr, r) }", "func SHRXQ(r, mr, r1 operand.Op) { ctx.SHRXQ(r, mr, r1) }", "func (r *bufferingReaderAt) recycleBuf(b []byte) {\n\tif cap(b) != r.blockSize {\n\t\tpanic(\"trying to return a buffer not initially requested via grabBuf\")\n\t}\n\tif len(r.pool)+1 > cap(r.pool) {\n\t\tpanic(\"unexpected growth of byte buffer pool beyond capacity\")\n\t}\n\tr.pool = append(r.pool, b[:cap(b)])\n}", "func (u *Msg) RRsetUsedRdata(rr []RR) {\n\tif len(u.Question) == 0 {\n\t\tpanic(\"empty question section\")\n\t}\n\tu.Answer = make([]RR, len(rr))\n\tfor i, r := range rr {\n\t\tu.Answer[i] = r\n\t\tu.Answer[i].Header().Class = u.Question[0].Qclass\n\t}\n}", "func SUBQ(imr, mr operand.Op) { ctx.SUBQ(imr, mr) }", "func (p *promise) Reject(err error) {\n\tp.fulfill(false, nil, err)\n}", "func (rs *RuleSpec) fillRemaining() {\n\tlength := len(rs.RuleParameters)\n\tfor i, rp := range rs.RuleParameters {\n\t\trp.Remaining = length - i -1\n\t}\n}", "func NewPRReject() PolicyRequirement {\n\treturn newPRReject()\n}", "func (reader *Reader) Reject(line []byte) (int, error) {\n\treturn reader.bufReject.Write(line)\n}", "func ADCQ(imr, mr operand.Op) { ctx.ADCQ(imr, mr) }", "func (b Binomial) Rand() float64 {\n\t// NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)\n\t// p. 295-6\n\t// http://www.aip.de/groups/soe/local/numres/bookcpdf/c7-3.pdf\n\n\trunif := rand.Float64\n\trexp := rand.ExpFloat64\n\tif b.Src != nil {\n\t\trnd := rand.New(b.Src)\n\t\trunif = rnd.Float64\n\t\trexp = rnd.ExpFloat64\n\t}\n\n\tp := b.P\n\tif p > 0.5 {\n\t\tp = 1 - p\n\t}\n\tam := b.N * p\n\n\tif b.N < 25 {\n\t\t// Use direct method.\n\t\tbnl := 0.0\n\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\tif runif() < p {\n\t\t\t\tbnl++\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\n\tif am < 1 {\n\t\t// Use rejection method with Poisson proposal.\n\t\tconst logM = 2.6e-2 // constant for rejection sampling (https://en.wikipedia.org/wiki/Rejection_sampling)\n\t\tvar bnl float64\n\t\tz := -p\n\t\tpclog := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z) // Padé approximant of log(1 + x)\n\t\tfor {\n\t\t\tbnl = 0.0\n\t\t\tt := 0.0\n\t\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\t\tt += rexp()\n\t\t\t\tif t >= am {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tbnl++\n\t\t\t}\n\t\t\tbnlc := b.N - bnl\n\t\t\tz = -bnl / b.N\n\t\t\tlog1p := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z)\n\t\t\tt = (bnlc+0.5)*log1p + bnl - bnlc*pclog + 1/(12*bnlc) - am + logM // Uses Stirling's expansion of log(n!)\n\t\t\tif rexp() >= t {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\t// Original algorithm samples from a Poisson distribution with the\n\t// appropriate expected value. However, the Poisson approximation is\n\t// asymptotic such that the absolute deviation in probability is O(1/n).\n\t// Rejection sampling produces exact variates with at worst less than 3%\n\t// rejection with minimal additional computation.\n\n\t// Use rejection method with Cauchy proposal.\n\tg, _ := math.Lgamma(b.N + 1)\n\tplog := math.Log(p)\n\tpclog := math.Log1p(-p)\n\tsq := math.Sqrt(2 * am * (1 - p))\n\tfor {\n\t\tvar em, y float64\n\t\tfor {\n\t\t\ty = math.Tan(math.Pi * runif())\n\t\t\tem = sq*y + am\n\t\t\tif em >= 0 && em < b.N+1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tem = math.Floor(em)\n\t\tlg1, _ := math.Lgamma(em + 1)\n\t\tlg2, _ := math.Lgamma(b.N - em + 1)\n\t\tt := 1.2 * sq * (1 + y*y) * math.Exp(g-lg1-lg2+em*plog+(b.N-em)*pclog)\n\t\tif runif() <= t {\n\t\t\tif p != b.P {\n\t\t\t\treturn b.N - em\n\t\t\t}\n\t\t\treturn em\n\t\t}\n\t}\n}", "func (a *answer) queueCall(result *answer, transform []capnp.PipelineOp, call *capnp.Call) error {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\tif a.done {\n\t\tpanic(\"answer.queueCall called on resolved answer\")\n\t}\n\tif len(a.queue) == cap(a.queue) {\n\t\treturn errQueueFull\n\t}\n\tcc, err := call.Copy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.queue = append(a.queue, pcall{\n\t\ttransform: transform,\n\t\tqcall: qcall{\n\t\t\ta: result,\n\t\t\tcall: cc,\n\t\t},\n\t})\n\treturn nil\n}", "func (alice *Requester) GenerateBlindFactor(R, Q *ecdsa.PublicKey) {\n\n\tcrv := Secp256k1().Params()\n\t// generate F which is not equal to O (§4.2)\n\t// var err error\n\tF := new(ecdsa.PublicKey)\n\tfor F.X == nil && F.Y == nil {\n\t\t// requester calculates point F (§4.2)\n\t\t// F = (b^-1)R + a(b^-1)Q + cG\n\t\tabInv := new(big.Int).Mul(alice.a, alice.bInv)\n\t\tabInv.Mod(abInv, crv.N)\n\t\tbInvR := ScalarMult(alice.bInv, R)\n\t\tabInvQ := ScalarMult(abInv, Q)\n\t\tcG := ScalarBaseMult(alice.c)\n\t\tF = Add(bInvR, abInvQ)\n\t\tF = Add(F, cG)\n\t}\n\talice.F = F\n\n\treturn\n}", "func (rbm *RBM) Reconstruct(v []float64, numSteps int) ([]float64, []float64) {\n\t// Initial value is set to input visible\n\treconstructedVisible := make([]float64, len(v))\n\tcopy(reconstructedVisible, v)\n\treconstructedProb := make([]float64, len(v))\n\n\t// perform Gibbs-sampling\n\tfor t := 0; t < numSteps; t++ {\n\t\t// 1. sample hidden units\n\t\thiddenState := make([]float64, rbm.NumHiddenUnits)\n\t\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\t\tp := rbm.P_H_Given_V(i, reconstructedVisible)\n\t\t\tif p > rand.Float64() {\n\t\t\t\thiddenState[i] = 1.0\n\t\t\t} else {\n\t\t\t\thiddenState[i] = 0.0\n\t\t\t}\n\t\t}\n\t\t// 2. sample visible units\n\t\tfor j := 0; j < rbm.NumVisibleUnits; j++ {\n\t\t\tp := rbm.P_V_Given_H(j, hiddenState)\n\t\t\tif p > rand.Float64() {\n\t\t\t\treconstructedVisible[j] = 1.0\n\t\t\t} else {\n\t\t\t\treconstructedVisible[j] = 0.0\n\t\t\t}\n\t\t\t// keep probability\n\t\t\treconstructedProb[j] = p\n\t\t}\n\t}\n\n\treturn reconstructedVisible, reconstructedProb\n}", "func VPSRAQ(ops ...operand.Op) { ctx.VPSRAQ(ops...) }", "func qr_decoder_decode_image(p _QrDecoderHandle, src *_IplImage, adaptive_th_size, adaptive_th_delta int) int {\n\tv := C.qr_decoder_decode_image(C.QrDecoderHandle(p), (*C.IplImage)(src), C.int(adaptive_th_size), C.int(adaptive_th_delta))\n\treturn int(v)\n}", "func PCLMULQDQ(i, mx, x operand.Op) { ctx.PCLMULQDQ(i, mx, x) }", "func remez(des, grid, bands, wt []float64, ngrid int, iext []int, alpha []float64, nfcns, itrmax int, dimsize int) (float64, error) {\n\ta := make([]float64, dimsize+1)\n\tp := make([]float64, dimsize+1)\n\tq := make([]float64, dimsize+1)\n\tad := make([]float64, dimsize+1)\n\tx := make([]float64, dimsize+1)\n\ty := make([]float64, dimsize+1)\n\n\tdevl := -1.0\n\tnz := nfcns + 1\n\tnzz := nfcns + 2\n\n\tvar comp, dev, y1 float64\n\nIterationLoop:\n\tfor niter := 0; niter <= itrmax; niter++ {\n\t\tif niter == itrmax {\n\t\t\treturn dev, errors.New(\"remez: reached max iterations\")\n\t\t}\n\n\t\tiext[nzz] = ngrid + 1\n\n\t\tfor j := 1; j <= nz; j++ {\n\t\t\tx[j] = math.Cos(grid[iext[j]] * pi2)\n\t\t}\n\n\t\tjet := (nfcns-1)/15 + 1\n\t\tfor j := 1; j <= nz; j++ {\n\t\t\tad[j] = lagrangeInterp(j, nz, jet, x)\n\t\t}\n\n\t\tdnum, dden := 0.0, 0.0\n\t\tfor j, k := 1, 1.0; j <= nz; j, k = j+1, -k {\n\t\t\tl := iext[j]\n\t\t\tdnum += ad[j] * des[l]\n\t\t\tdden += k * ad[j] / wt[l]\n\t\t}\n\t\tdev = dnum / dden\n\n\t\t/* printf(\"DEVIATION = %lg\\n\",*dev); */\n\n\t\tnu := 1.0\n\t\tif dev > 0.0 {\n\t\t\tnu = -1.0\n\t\t}\n\t\tdev = math.Abs(dev) // dev = -nu * dev\n\t\tfor j, k := 1, nu; j <= nz; j, k = j+1, -k {\n\t\t\tl := iext[j]\n\t\t\ty[j] = des[l] + k*dev/wt[l]\n\t\t}\n\t\tif dev <= devl {\n\t\t\t/* finished */\n\t\t\treturn dev, errors.New(\"remez: deviation decreased\")\n\t\t}\n\t\tdevl = dev\n\n\t\tjchnge := 0\n\t\tk1 := iext[1]\n\t\tknz := iext[nz]\n\t\tklow := 0\n\t\tnut := -nu\n\n\t\tdown := func(l, j int) {\n\t\t\tfor {\n\t\t\t\tl--\n\t\t\t\tif l <= klow {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp <= 0.0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcomp = nut * e\n\t\t\t}\n\t\t\tklow = iext[j]\n\t\t\tiext[j] = l + 1\n\t\t\tjchnge++\n\t\t}\n\n\t\tup := func(l, j, kup int) {\n\t\t\tfor {\n\t\t\t\tl++\n\t\t\t\tif l >= kup {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp <= 0.0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcomp = nut * e\n\t\t\t}\n\t\t\tiext[j] = l - 1\n\t\t\tklow = l - 1\n\t\t\tjchnge++\n\t\t}\n\n\t\t/*\n\t\t * SEARCH FOR THE EXTREMAL FREQUENCIES OF THE BEST APPROXIMATION\n\t\t */\n\n\t\tfor j := 1; j < nzz; j++ {\n\t\t\tkup := iext[j+1]\n\t\t\tnut = -nut\n\t\t\tif j == 2 {\n\t\t\t\ty1 = comp\n\t\t\t}\n\t\t\tcomp = dev\n\n\t\t\tl := iext[j] + 1\n\t\t\tif l < kup {\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\tcomp = nut * e\n\t\t\t\t\tup(l, j, kup)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl--\n\n\t\t\tfor {\n\t\t\t\tl--\n\t\t\t\tif l <= klow {\n\t\t\t\t\tl = iext[j] + 1\n\t\t\t\t\tif jchnge > 0 {\n\t\t\t\t\t\tiext[j] = l - 1\n\t\t\t\t\t\tklow = l - 1\n\t\t\t\t\t\tjchnge++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\tl++\n\t\t\t\t\t\t\tif l >= kup {\n\t\t\t\t\t\t\t\tklow = iext[j]\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\t\t\t\tcomp = nut * e\n\t\t\t\t\t\t\t\tup(l, j, kup)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\t\tcomp = nut * e\n\t\t\t\t\tdown(l, j)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif jchnge > 0 {\n\t\t\t\t\tklow = iext[j]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif k1 > iext[1] {\n\t\t\tk1 = iext[1]\n\t\t}\n\t\tif knz < iext[nz] {\n\t\t\tknz = iext[nz]\n\t\t}\n\n\t\tluck := 6\n\t\tnut1 := nut\n\t\tnut = -nu\n\t\tcomp *= 1.00001\n\t\tj := nzz\n\n\t\tfor l := 1; l < k1; l++ {\n\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\tcomp = nut * e\n\t\t\t\tup(l, j, k1)\n\t\t\t\tj = nzz + 1\n\t\t\t\tluck = 1\n\n\t\t\t\tif comp > y1 {\n\t\t\t\t\ty1 = comp\n\t\t\t\t}\n\t\t\t\tk1 = iext[nzz]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tklow = knz\n\t\tnut = -nut1\n\t\tcomp = y1 * 1.00001\n\n\t\tfor l := ngrid; l > klow; l-- {\n\t\t\te := (freqEval(l, nz, grid, x, y, ad) - des[l]) * wt[l]\n\t\t\tif nut*e-comp > 0.0 {\n\t\t\t\tcomp = nut * e\n\t\t\t\tdown(l, j)\n\n\t\t\t\tkn := iext[nzz]\n\t\t\t\tfor i := 1; i <= nfcns; i++ {\n\t\t\t\t\tiext[i] = iext[i+1]\n\t\t\t\t}\n\t\t\t\tiext[nz] = kn\n\t\t\t\tcontinue IterationLoop\n\t\t\t}\n\t\t}\n\n\t\tif luck != 6 {\n\t\t\tfor i := 1; i <= nfcns; i++ {\n\t\t\t\tiext[nzz-i] = iext[nz-i]\n\t\t\t}\n\t\t\tiext[1] = k1\n\t\t} else if jchnge <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t/*\n\t * CALCULATION OF THE COEFFICIENTS OF THE BEST APPROXIMATION\n\t * USING THE INVERSE DISCRETE FOURIER TRANSFORM\n\t */\n\tnm1 := nfcns - 1\n\tfsh := 1.0e-06\n\tgtemp := grid[1]\n\tx[nzz] = -2.0\n\tcn := float64(2*nfcns - 1)\n\tdelf := 1.0 / cn\n\tl := 1\n\tkkk := 0\n\n\tif bands[0] == 0.0 && bands[len(bands)-1] == 0.5 {\n\t\tkkk = 1\n\t}\n\n\tif nfcns <= 3 {\n\t\tkkk = 1\n\t}\n\n\tvar aa, bb float64\n\tif kkk != 1 {\n\t\tdtemp := math.Cos(pi2 * grid[1])\n\t\tdnum := math.Cos(pi2 * grid[ngrid])\n\t\taa = 2.0 / (dtemp - dnum)\n\t\tbb = -(dtemp + dnum) / (dtemp - dnum)\n\t}\n\n\tfor j := 1; j <= nfcns; j++ {\n\t\tft := float64(j-1) * delf\n\t\txt := math.Cos(pi2 * ft)\n\t\tif kkk != 1 {\n\t\t\txt = (xt - bb) / aa\n\t\t\t// /*XX* ckeck up !! */\n\t\t\t// xt1 = sqrt(1.0-xt*xt);\n\t\t\t// ft = atan2(xt1,xt)/pi2;\n\n\t\t\tft = math.Acos(xt) / pi2\n\t\t}\n\t\tfor {\n\t\t\txe := x[l]\n\t\t\tif xt > xe {\n\t\t\t\tif (xt - xe) < fsh {\n\t\t\t\t\ta[j] = y[l]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tgrid[1] = ft\n\t\t\t\ta[j] = freqEval(1, nz, grid, x, y, ad)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (xe - xt) < fsh {\n\t\t\t\ta[j] = y[l]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl++\n\t\t}\n\t\tif l > 1 {\n\t\t\tl = l - 1\n\t\t}\n\t}\n\n\tgrid[1] = gtemp\n\tdden := pi2 / cn\n\tfor j := 1; j <= nfcns; j++ {\n\t\tdtemp := 0.0\n\t\tdnum := float64(j-1) * dden\n\t\tif nm1 >= 1 {\n\t\t\tfor k := 1; k <= nm1; k++ {\n\t\t\t\tdtemp += a[k+1] * math.Cos(dnum*float64(k))\n\t\t\t}\n\t\t}\n\t\talpha[j] = 2.0*dtemp + a[1]\n\t}\n\n\tfor j := 2; j <= nfcns; j++ {\n\t\talpha[j] *= 2.0 / cn\n\t}\n\talpha[1] /= cn\n\n\tif kkk != 1 {\n\t\tp[1] = 2.0*alpha[nfcns]*bb + alpha[nm1]\n\t\tp[2] = 2.0 * aa * alpha[nfcns]\n\t\tq[1] = alpha[nfcns-2] - alpha[nfcns]\n\t\tfor j := 2; j <= nm1; j++ {\n\t\t\tif j >= nm1 {\n\t\t\t\taa *= 0.5\n\t\t\t\tbb *= 0.5\n\t\t\t}\n\t\t\tp[j+1] = 0.0\n\t\t\tfor k := 1; k <= j; k++ {\n\t\t\t\ta[k] = p[k]\n\t\t\t\tp[k] = 2.0 * bb * a[k]\n\t\t\t}\n\t\t\tp[2] += a[1] * 2.0 * aa\n\t\t\tfor k := 1; k <= j-1; k++ {\n\t\t\t\tp[k] += q[k] + aa*a[k+1]\n\t\t\t}\n\t\t\tfor k := 3; k <= j+1; k++ {\n\t\t\t\tp[k] += aa * a[k-1]\n\t\t\t}\n\n\t\t\tif j != nm1 {\n\t\t\t\tfor k := 1; k <= j; k++ {\n\t\t\t\t\tq[k] = -a[k]\n\t\t\t\t}\n\t\t\t\tq[1] += alpha[nfcns-1-j]\n\t\t\t}\n\t\t}\n\t\tfor j := 1; j <= nfcns; j++ {\n\t\t\talpha[j] = p[j]\n\t\t}\n\t}\n\n\tif nfcns <= 3 {\n\t\talpha[nfcns+1] = 0.0\n\t\talpha[nfcns+2] = 0.0\n\t}\n\treturn dev, nil\n}", "func (c *Context) RCRQ(ci, mr operand.Op) {\n\tc.addinstruction(x86.RCRQ(ci, mr))\n}", "func zerrlqtp(path string, _t *testing.T) {\n\tvar i, j, nmax int\n\tvar err error\n\n\tw := cvf(2)\n\ta := cmf(2, 2, opts)\n\tb := cmf(2, 2, opts)\n\tc := cmf(2, 2, opts)\n\tt := cmf(2, 2, opts)\n\n\tnmax = 2\n\terrt := &gltest.Common.Infoc.Errt\n\tok := &gltest.Common.Infoc.Ok\n\tsrnamt := &gltest.Common.Srnamc.Srnamt\n\n\t// Set the variables to innocuous values.\n\tfor j = 1; j <= nmax; j++ {\n\t\tfor i = 1; i <= nmax; i++ {\n\t\t\ta.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tc.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tt.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t}\n\t\tw.Set(j-1, 0.0)\n\t}\n\t(*ok) = true\n\n\t// Error exits for TPLQT factorization\n\t//\n\t// Ztplqt\n\t*srnamt = \"Ztplqt\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztplqt(-1, 1, 0, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztplqt(1, -1, 0, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || (l > min(m, n) && min(m, n) >= 0): l=-1, m=0, n=1\")\n\terr = golapack.Ztplqt(0, 1, -1, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || (l > min(m, n) && min(m, n) >= 0): l=1, m=0, n=1\")\n\terr = golapack.Ztplqt(0, 1, 1, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > m && m > 0): mb=0, m=0\")\n\terr = golapack.Ztplqt(0, 1, 0, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > m && m > 0): mb=2, m=1\")\n\terr = golapack.Ztplqt(1, 1, 0, 2, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Ztplqt(2, 1, 0, 2, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztplqt(2, 1, 0, 1, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Ztplqt(2, 2, 1, 2, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\n\t// Ztplqt2\n\t*srnamt = \"Ztplqt2\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztplqt2(-1, 0, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztplqt2(0, -1, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"l < 0 || l > min(m, n): l=-1, m=0, n=0\")\n\terr = golapack.Ztplqt2(0, 0, -1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(2))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(2))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"t.Rows < max(1, m): t.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\n\t// Ztpmlqt\n\t*srnamt = \"Ztpmlqt\"\n\t*errt = fmt.Errorf(\"!left && !right: side=Unrecognized: /\")\n\terr = golapack.Ztpmlqt('/', NoTrans, 0, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"!tran && !notran: trans=Unrecognized: /\")\n\terr = golapack.Ztpmlqt(Left, '/', 0, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, -1, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, -1, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, -1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || l > k: l=-1, k=0\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > k && k > 0): mb=0, k=0\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, 0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < k: v.Rows=1, k=2\")\n\terr = golapack.Ztpmlqt(Right, NoTrans, 2, 2, 2, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t// *errt = fmt.Errorf(\"t.Rows < mb: t.Rows=0, mb=1\")\n\t// err = golapack.Ztpmlqt(Right, NoTrans, 1, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(0), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\t// chkxer2(\"Ztpmlqt\", err)\n\t// *errt = fmt.Errorf(\"a.Rows < ldaq: a.Rows=0, ldaq=1\")\n\t// err = golapack.Ztpmlqt(Left, NoTrans, 1, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(0), c.Off(0, 0).UpdateRows(1), w)\n\t// chkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 2, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\n\t// Print a summary line.\n\t// alaesm(path, *ok)\n\n\tif !(*ok) {\n\t\t_t.Fail()\n\t}\n}", "func CMOVQPL(mr, r operand.Op) { ctx.CMOVQPL(mr, r) }", "func (r *req) resender() {\n\n\tdefer r.w.Done()\n\tcq := r.sock.CloseChannel()\n\n\tfor {\n\t\tselect {\n\t\tcase <-r.waker.C:\n\t\tcase <-r.wakeq:\n\t\tcase <-cq:\n\t\t\treturn\n\t\t}\n\n\t\tr.Lock()\n\t\tm := r.reqmsg\n\t\tif m == nil {\n\t\t\tr.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\tm = m.Dup()\n\t\tr.Unlock()\n\n\t\tr.resend <- m\n\t\tr.Lock()\n\t\tif r.retry > 0 {\n\t\t\tr.waker.Reset(r.retry)\n\t\t} else {\n\t\t\tr.waker.Stop()\n\t\t}\n\t\tr.Unlock()\n\t}\n}", "func Zbdsqr(uplo mat.MatUplo, n, ncvt, nru, ncc int, d, e *mat.Vector, vt, u, c *mat.CMatrix, rwork *mat.Vector) (info int, err error) {\n\tvar lower, rotate bool\n\tvar abse, abss, cosl, cosr, cs, eps, f, g, h, hndrd, hndrth, meigth, mu, negone, oldcs, oldsn, one, r, shift, sigmn, sigmx, sinl, sinr, sll, smax, smin, sminl, sminoa, sn, ten, thresh, tol, tolmul, unfl, zero float64\n\tvar i, idir, isub, iter, j, ll, lll, m, maxit, maxitr, nm1, nm12, nm13, oldll, oldm int\n\n\tzero = 0.0\n\tone = 1.0\n\tnegone = -1.0\n\thndrth = 0.01\n\tten = 10.0\n\thndrd = 100.0\n\tmeigth = -0.125\n\tmaxitr = 6\n\n\t// Test the input parameters.\n\tlower = uplo == Lower\n\tif uplo != Upper && !lower {\n\t\terr = fmt.Errorf(\"uplo != Upper && !lower: uplo=%s\", uplo)\n\t} else if n < 0 {\n\t\terr = fmt.Errorf(\"n < 0: n=%v\", n)\n\t} else if ncvt < 0 {\n\t\terr = fmt.Errorf(\"ncvt < 0: ncvt=%v\", ncvt)\n\t} else if nru < 0 {\n\t\terr = fmt.Errorf(\"nru < 0: nru=%v\", nru)\n\t} else if ncc < 0 {\n\t\terr = fmt.Errorf(\"ncc < 0: ncc=%v\", ncc)\n\t} else if (ncvt == 0 && vt.Rows < 1) || (ncvt > 0 && vt.Rows < max(1, n)) {\n\t\terr = fmt.Errorf(\"(ncvt == 0 && vt.Rows < 1) || (ncvt > 0 && vt.Rows < max(1, n)): ncvt=%v, vt.Rows=%v, n=%v\", ncvt, vt.Rows, n)\n\t} else if u.Rows < max(1, nru) {\n\t\terr = fmt.Errorf(\"u.Rows < max(1, nru): u.Rows=%v, nru=%v\", u.Rows, nru)\n\t} else if (ncc == 0 && c.Rows < 1) || (ncc > 0 && c.Rows < max(1, n)) {\n\t\terr = fmt.Errorf(\"(ncc == 0 && c.Rows < 1) || (ncc > 0 && c.Rows < max(1, n)): ncc=%v, c.Rows=%v, n=%v\", ncc, c.Rows, n)\n\t}\n\tif err != nil {\n\t\tgltest.Xerbla2(\"Zbdsqr\", err)\n\t\treturn\n\t}\n\tif n == 0 {\n\t\treturn\n\t}\n\tif n == 1 {\n\t\tgoto label160\n\t}\n\n\t// ROTATE is true if any singular vectors desired, false otherwise\n\trotate = (ncvt > 0) || (nru > 0) || (ncc > 0)\n\n\t// If no singular vectors desired, use qd algorithm\n\tif !rotate {\n\t\tif info, err = Dlasq1(n, d, e, rwork); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// If INFO equals 2, dqds didn't finish, try to finish\n\t\tif info != 2 {\n\t\t\treturn\n\t\t}\n\t\tinfo = 0\n\t}\n\n\tnm1 = n - 1\n\tnm12 = nm1 + nm1\n\tnm13 = nm12 + nm1\n\tidir = 0\n\n\t// Get machine constants\n\teps = Dlamch(Epsilon)\n\tunfl = Dlamch(SafeMinimum)\n\n\t// If matrix lower bidiagonal, rotate to be upper bidiagonal\n\t// by applying Givens rotations on the left\n\tif lower {\n\t\tfor i = 1; i <= n-1; i++ {\n\t\t\tcs, sn, r = Dlartg(d.Get(i-1), e.Get(i-1))\n\t\t\td.Set(i-1, r)\n\t\t\te.Set(i-1, sn*d.Get(i))\n\t\t\td.Set(i, cs*d.Get(i))\n\t\t\trwork.Set(i-1, cs)\n\t\t\trwork.Set(nm1+i-1, sn)\n\t\t}\n\n\t\t// Update singular vectors if desired\n\t\tif nru > 0 {\n\t\t\tif err = Zlasr(Right, 'V', 'F', nru, n, rwork.Off(0), rwork.Off(n-1), u); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tif ncc > 0 {\n\t\t\tif err = Zlasr(Left, 'V', 'F', n, ncc, rwork.Off(0), rwork.Off(n-1), c); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute singular values to relative accuracy TOL\n\t// (By setting TOL to be negative, algorithm will compute\n\t// singular values to absolute accuracy ABS(TOL)*norm(input matrix))\n\ttolmul = math.Max(ten, math.Min(hndrd, math.Pow(eps, meigth)))\n\ttol = tolmul * eps\n\n\t// Compute approximate maximum, minimum singular values\n\tsmax = zero\n\tfor i = 1; i <= n; i++ {\n\t\tsmax = math.Max(smax, math.Abs(d.Get(i-1)))\n\t}\n\tfor i = 1; i <= n-1; i++ {\n\t\tsmax = math.Max(smax, math.Abs(e.Get(i-1)))\n\t}\n\tsminl = zero\n\tif tol >= zero {\n\t\t// Relative accuracy desired\n\t\tsminoa = math.Abs(d.Get(0))\n\t\tif sminoa == zero {\n\t\t\tgoto label50\n\t\t}\n\t\tmu = sminoa\n\t\tfor i = 2; i <= n; i++ {\n\t\t\tmu = math.Abs(d.Get(i-1)) * (mu / (mu + math.Abs(e.Get(i-1-1))))\n\t\t\tsminoa = math.Min(sminoa, mu)\n\t\t\tif sminoa == zero {\n\t\t\t\tgoto label50\n\t\t\t}\n\t\t}\n\tlabel50:\n\t\t;\n\t\tsminoa = sminoa / math.Sqrt(float64(n))\n\t\tthresh = math.Max(tol*sminoa, float64(maxitr*n*n)*unfl)\n\t} else {\n\t\t// Absolute accuracy desired\n\t\tthresh = math.Max(math.Abs(tol)*smax, float64(maxitr*n*n)*unfl)\n\t}\n\n\t// Prepare for main iteration loop for the singular values\n\t// (MAXIT is the maximum number of passes through the inner\n\t// loop permitted before nonconvergence signalled.)\n\tmaxit = maxitr * n * n\n\titer = 0\n\toldll = -1\n\toldm = -1\n\n\t// M points to last element of unconverged part of matrix\n\tm = n\n\n\t// Begin main iteration loop\nlabel60:\n\t;\n\n\t// Check for convergence or exceeding iteration count\n\tif m <= 1 {\n\t\tgoto label160\n\t}\n\tif iter > maxit {\n\t\tgoto label200\n\t}\n\n\t// Find diagonal block of matrix to work on\n\tif tol < zero && math.Abs(d.Get(m-1)) <= thresh {\n\t\td.Set(m-1, zero)\n\t}\n\tsmax = math.Abs(d.Get(m - 1))\n\tsmin = smax\n\tfor lll = 1; lll <= m-1; lll++ {\n\t\tll = m - lll\n\t\tabss = math.Abs(d.Get(ll - 1))\n\t\tabse = math.Abs(e.Get(ll - 1))\n\t\tif tol < zero && abss <= thresh {\n\t\t\td.Set(ll-1, zero)\n\t\t}\n\t\tif abse <= thresh {\n\t\t\tgoto label80\n\t\t}\n\t\tsmin = math.Min(smin, abss)\n\t\tsmax = math.Max(smax, math.Max(abss, abse))\n\t}\n\tll = 0\n\tgoto label90\nlabel80:\n\t;\n\te.Set(ll-1, zero)\n\n\t// Matrix splits since E(LL) = 0\n\tif ll == m-1 {\n\t\t// Convergence of bottom singular value, return to top of loop\n\t\tm = m - 1\n\t\tgoto label60\n\t}\nlabel90:\n\t;\n\tll = ll + 1\n\n\t// E(LL) through E(M-1) are nonzero, E(LL-1) is zero\n\tif ll == m-1 {\n\t\t// 2 by 2 block, handle separately\n\t\tsigmn, sigmx, sinr, cosr, sinl, cosl = Dlasv2(d.Get(m-1-1), e.Get(m-1-1), d.Get(m-1))\n\t\td.Set(m-1-1, sigmx)\n\t\te.Set(m-1-1, zero)\n\t\td.Set(m-1, sigmn)\n\n\t\t// Compute singular vectors, if desired\n\t\tif ncvt > 0 {\n\t\t\tvt.Off(m-1, 0).CVector().Drot(ncvt, vt.Off(m-1-1, 0).CVector(), vt.Rows, vt.Rows, cosr, sinr)\n\t\t}\n\t\tif nru > 0 {\n\t\t\tu.Off(0, m-1).CVector().Drot(nru, u.Off(0, m-1-1).CVector(), 1, 1, cosl, sinl)\n\t\t}\n\t\tif ncc > 0 {\n\t\t\tc.Off(m-1, 0).CVector().Drot(ncc, c.Off(m-1-1, 0).CVector(), c.Rows, c.Rows, cosl, sinl)\n\t\t}\n\t\tm = m - 2\n\t\tgoto label60\n\t}\n\n\t// If working on new submatrix, choose shift direction\n\t// (from larger end diagonal element towards smaller)\n\tif ll > oldm || m < oldll {\n\t\tif math.Abs(d.Get(ll-1)) >= math.Abs(d.Get(m-1)) {\n\t\t\t// Chase bulge from top (big end) to bottom (small end)\n\t\t\tidir = 1\n\t\t} else {\n\t\t\t// Chase bulge from bottom (big end) to top (small end)\n\t\t\tidir = 2\n\t\t}\n\t}\n\n\t// Apply convergence tests\n\tif idir == 1 {\n\t\t// Run convergence test in forward direction\n\t\t// First apply standard test to bottom of matrix\n\t\tif math.Abs(e.Get(m-1-1)) <= math.Abs(tol)*math.Abs(d.Get(m-1)) || (tol < zero && math.Abs(e.Get(m-1-1)) <= thresh) {\n\t\t\te.Set(m-1-1, zero)\n\t\t\tgoto label60\n\t\t}\n\n\t\tif tol >= zero {\n\t\t\t// If relative accuracy desired,\n\t\t\t// apply convergence criterion forward\n\t\t\tmu = math.Abs(d.Get(ll - 1))\n\t\t\tsminl = mu\n\t\t\tfor lll = ll; lll <= m-1; lll++ {\n\t\t\t\tif math.Abs(e.Get(lll-1)) <= tol*mu {\n\t\t\t\t\te.Set(lll-1, zero)\n\t\t\t\t\tgoto label60\n\t\t\t\t}\n\t\t\t\tmu = math.Abs(d.Get(lll)) * (mu / (mu + math.Abs(e.Get(lll-1))))\n\t\t\t\tsminl = math.Min(sminl, mu)\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t// Run convergence test in backward direction\n\t\t// First apply standard test to top of matrix\n\t\tif math.Abs(e.Get(ll-1)) <= math.Abs(tol)*math.Abs(d.Get(ll-1)) || (tol < zero && math.Abs(e.Get(ll-1)) <= thresh) {\n\t\t\te.Set(ll-1, zero)\n\t\t\tgoto label60\n\t\t}\n\n\t\tif tol >= zero {\n\t\t\t// If relative accuracy desired,\n\t\t\t// apply convergence criterion backward\n\t\t\tmu = math.Abs(d.Get(m - 1))\n\t\t\tsminl = mu\n\t\t\tfor lll = m - 1; lll >= ll; lll-- {\n\t\t\t\tif math.Abs(e.Get(lll-1)) <= tol*mu {\n\t\t\t\t\te.Set(lll-1, zero)\n\t\t\t\t\tgoto label60\n\t\t\t\t}\n\t\t\t\tmu = math.Abs(d.Get(lll-1)) * (mu / (mu + math.Abs(e.Get(lll-1))))\n\t\t\t\tsminl = math.Min(sminl, mu)\n\t\t\t}\n\t\t}\n\t}\n\toldll = ll\n\toldm = m\n\n\t// Compute shift. First, test if shifting would ruin relative\n\t// accuracy, and if so set the shift to zero.\n\tif tol >= zero && float64(n)*tol*(sminl/smax) <= math.Max(eps, hndrth*tol) {\n\t\t// Use a zero shift to avoid loss of relative accuracy\n\t\tshift = zero\n\t} else {\n\t\t// Compute the shift from 2-by-2 block at end of matrix\n\t\tif idir == 1 {\n\t\t\tsll = math.Abs(d.Get(ll - 1))\n\t\t\tshift, r = Dlas2(d.Get(m-1-1), e.Get(m-1-1), d.Get(m-1))\n\t\t} else {\n\t\t\tsll = math.Abs(d.Get(m - 1))\n\t\t\tshift, r = Dlas2(d.Get(ll-1), e.Get(ll-1), d.Get(ll))\n\t\t}\n\n\t\t// Test if shift negligible, and if so set to zero\n\t\tif sll > zero {\n\t\t\tif math.Pow(shift/sll, 2) < eps {\n\t\t\t\tshift = zero\n\t\t\t}\n\t\t}\n\t}\n\n\t// Increment iteration count\n\titer = iter + m - ll\n\n\t// If SHIFT = 0, do simplified QR iteration\n\tif shift == zero {\n\t\tif idir == 1 {\n\t\t\t// Chase bulge from top to bottom\n\t\t\t// Save cosines and sines for later singular vector updates\n\t\t\tcs = one\n\t\t\toldcs = one\n\t\t\tfor i = ll; i <= m-1; i++ {\n\t\t\t\tcs, sn, r = Dlartg(d.Get(i-1)*cs, e.Get(i-1))\n\t\t\t\tif i > ll {\n\t\t\t\t\te.Set(i-1-1, oldsn*r)\n\t\t\t\t}\n\t\t\t\toldcs, oldsn, *d.GetPtr(i - 1) = Dlartg(oldcs*r, d.Get(i)*sn)\n\t\t\t\trwork.Set(i-ll, cs)\n\t\t\t\trwork.Set(i-ll+1+nm1-1, sn)\n\t\t\t\trwork.Set(i-ll+1+nm12-1, oldcs)\n\t\t\t\trwork.Set(i-ll+1+nm13-1, oldsn)\n\t\t\t}\n\t\t\th = d.Get(m-1) * cs\n\t\t\td.Set(m-1, h*oldcs)\n\t\t\te.Set(m-1-1, h*oldsn)\n\n\t\t\t// Update singular vectors\n\t\t\tif ncvt > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'F', m-ll+1, ncvt, rwork.Off(0), rwork.Off(n-1), vt.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nru > 0 {\n\t\t\t\tif err = Zlasr(Right, 'V', 'F', nru, m-ll+1, rwork.Off(nm12), rwork.Off(nm13), u.Off(0, ll-1)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ncc > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'F', m-ll+1, ncc, rwork.Off(nm12), rwork.Off(nm13), c.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Test convergence\n\t\t\tif math.Abs(e.Get(m-1-1)) <= thresh {\n\t\t\t\te.Set(m-1-1, zero)\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Chase bulge from bottom to top\n\t\t\t// Save cosines and sines for later singular vector updates\n\t\t\tcs = one\n\t\t\toldcs = one\n\t\t\tfor i = m; i >= ll+1; i-- {\n\t\t\t\tcs, sn, r = Dlartg(d.Get(i-1)*cs, e.Get(i-1-1))\n\t\t\t\tif i < m {\n\t\t\t\t\te.Set(i-1, oldsn*r)\n\t\t\t\t}\n\t\t\t\toldcs, oldsn, *d.GetPtr(i - 1) = Dlartg(oldcs*r, d.Get(i-1-1)*sn)\n\t\t\t\trwork.Set(i-ll-1, cs)\n\t\t\t\trwork.Set(i-ll+nm1-1, -sn)\n\t\t\t\trwork.Set(i-ll+nm12-1, oldcs)\n\t\t\t\trwork.Set(i-ll+nm13-1, -oldsn)\n\t\t\t}\n\t\t\th = d.Get(ll-1) * cs\n\t\t\td.Set(ll-1, h*oldcs)\n\t\t\te.Set(ll-1, h*oldsn)\n\n\t\t\t// Update singular vectors\n\t\t\tif ncvt > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'B', m-ll+1, ncvt, rwork.Off(nm12), rwork.Off(nm13), vt.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nru > 0 {\n\t\t\t\tif err = Zlasr(Right, 'V', 'B', nru, m-ll+1, rwork.Off(0), rwork.Off(n-1), u.Off(0, ll-1)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ncc > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'B', m-ll+1, ncc, rwork.Off(0), rwork.Off(n-1), c.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Test convergence\n\t\t\tif math.Abs(e.Get(ll-1)) <= thresh {\n\t\t\t\te.Set(ll-1, zero)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Use nonzero shift\n\t\tif idir == 1 {\n\t\t\t// Chase bulge from top to bottom\n\t\t\t// Save cosines and sines for later singular vector updates\n\t\t\tf = (math.Abs(d.Get(ll-1)) - shift) * (math.Copysign(one, d.Get(ll-1)) + shift/d.Get(ll-1))\n\t\t\tg = e.Get(ll - 1)\n\t\t\tfor i = ll; i <= m-1; i++ {\n\t\t\t\tcosr, sinr, r = Dlartg(f, g)\n\t\t\t\tif i > ll {\n\t\t\t\t\te.Set(i-1-1, r)\n\t\t\t\t}\n\t\t\t\tf = cosr*d.Get(i-1) + sinr*e.Get(i-1)\n\t\t\t\te.Set(i-1, cosr*e.Get(i-1)-sinr*d.Get(i-1))\n\t\t\t\tg = sinr * d.Get(i)\n\t\t\t\td.Set(i, cosr*d.Get(i))\n\t\t\t\tcosl, sinl, r = Dlartg(f, g)\n\t\t\t\td.Set(i-1, r)\n\t\t\t\tf = cosl*e.Get(i-1) + sinl*d.Get(i)\n\t\t\t\td.Set(i, cosl*d.Get(i)-sinl*e.Get(i-1))\n\t\t\t\tif i < m-1 {\n\t\t\t\t\tg = sinl * e.Get(i)\n\t\t\t\t\te.Set(i, cosl*e.Get(i))\n\t\t\t\t}\n\t\t\t\trwork.Set(i-ll, cosr)\n\t\t\t\trwork.Set(i-ll+1+nm1-1, sinr)\n\t\t\t\trwork.Set(i-ll+1+nm12-1, cosl)\n\t\t\t\trwork.Set(i-ll+1+nm13-1, sinl)\n\t\t\t}\n\t\t\te.Set(m-1-1, f)\n\n\t\t\t// Update singular vectors\n\t\t\tif ncvt > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'F', m-ll+1, ncvt, rwork.Off(0), rwork.Off(n-1), vt.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nru > 0 {\n\t\t\t\tif err = Zlasr(Right, 'V', 'F', nru, m-ll+1, rwork.Off(nm12), rwork.Off(nm13), u.Off(0, ll-1)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ncc > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'F', m-ll+1, ncc, rwork.Off(nm12), rwork.Off(nm13), c.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Test convergence\n\t\t\tif math.Abs(e.Get(m-1-1)) <= thresh {\n\t\t\t\te.Set(m-1-1, zero)\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Chase bulge from bottom to top\n\t\t\t// Save cosines and sines for later singular vector updates\n\t\t\tf = (math.Abs(d.Get(m-1)) - shift) * (math.Copysign(one, d.Get(m-1)) + shift/d.Get(m-1))\n\t\t\tg = e.Get(m - 1 - 1)\n\t\t\tfor i = m; i >= ll+1; i-- {\n\t\t\t\tcosr, sinr, r = Dlartg(f, g)\n\t\t\t\tif i < m {\n\t\t\t\t\te.Set(i-1, r)\n\t\t\t\t}\n\t\t\t\tf = cosr*d.Get(i-1) + sinr*e.Get(i-1-1)\n\t\t\t\te.Set(i-1-1, cosr*e.Get(i-1-1)-sinr*d.Get(i-1))\n\t\t\t\tg = sinr * d.Get(i-1-1)\n\t\t\t\td.Set(i-1-1, cosr*d.Get(i-1-1))\n\t\t\t\tcosl, sinl, r = Dlartg(f, g)\n\t\t\t\td.Set(i-1, r)\n\t\t\t\tf = cosl*e.Get(i-1-1) + sinl*d.Get(i-1-1)\n\t\t\t\td.Set(i-1-1, cosl*d.Get(i-1-1)-sinl*e.Get(i-1-1))\n\t\t\t\tif i > ll+1 {\n\t\t\t\t\tg = sinl * e.Get(i-2-1)\n\t\t\t\t\te.Set(i-2-1, cosl*e.Get(i-2-1))\n\t\t\t\t}\n\t\t\t\trwork.Set(i-ll-1, cosr)\n\t\t\t\trwork.Set(i-ll+nm1-1, -sinr)\n\t\t\t\trwork.Set(i-ll+nm12-1, cosl)\n\t\t\t\trwork.Set(i-ll+nm13-1, -sinl)\n\t\t\t}\n\t\t\te.Set(ll-1, f)\n\n\t\t\t// Test convergence\n\t\t\tif math.Abs(e.Get(ll-1)) <= thresh {\n\t\t\t\te.Set(ll-1, zero)\n\t\t\t}\n\n\t\t\t// Update singular vectors if desired\n\t\t\tif ncvt > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'B', m-ll+1, ncvt, rwork.Off(nm12), rwork.Off(nm13), vt.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nru > 0 {\n\t\t\t\tif err = Zlasr(Right, 'V', 'B', nru, m-ll+1, rwork.Off(0), rwork.Off(n-1), u.Off(0, ll-1)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ncc > 0 {\n\t\t\t\tif err = Zlasr(Left, 'V', 'B', m-ll+1, ncc, rwork.Off(0), rwork.Off(n-1), c.Off(ll-1, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// QR iteration finished, go back and check convergence\n\tgoto label60\n\n\t// All singular values converged, so make them positive\nlabel160:\n\t;\n\tfor i = 1; i <= n; i++ {\n\t\tif d.Get(i-1) < zero {\n\t\t\td.Set(i-1, -d.Get(i-1))\n\n\t\t\t// Change sign of singular vectors, if desired\n\t\t\tif ncvt > 0 {\n\t\t\t\tvt.Off(i-1, 0).CVector().Dscal(ncvt, negone, vt.Rows)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Sort the singular values into decreasing order (insertion sort on\n\t// singular values, but only one transposition per singular vector)\n\tfor i = 1; i <= n-1; i++ {\n\t\t// Scan for smallest D(I)\n\t\tisub = 1\n\t\tsmin = d.Get(0)\n\t\tfor j = 2; j <= n+1-i; j++ {\n\t\t\tif d.Get(j-1) <= smin {\n\t\t\t\tisub = j\n\t\t\t\tsmin = d.Get(j - 1)\n\t\t\t}\n\t\t}\n\t\tif isub != n+1-i {\n\t\t\t// Swap singular values and vectors\n\t\t\td.Set(isub-1, d.Get(n+1-i-1))\n\t\t\td.Set(n+1-i-1, smin)\n\t\t\tif ncvt > 0 {\n\t\t\t\tvt.Off(n+1-i-1, 0).CVector().Swap(ncvt, vt.Off(isub-1, 0).CVector(), vt.Rows, vt.Rows)\n\t\t\t}\n\t\t\tif nru > 0 {\n\t\t\t\tu.Off(0, n+1-i-1).CVector().Swap(nru, u.Off(0, isub-1).CVector(), 1, 1)\n\t\t\t}\n\t\t\tif ncc > 0 {\n\t\t\t\tc.Off(n+1-i-1, 0).CVector().Swap(ncc, c.Off(isub-1, 0).CVector(), c.Rows, c.Rows)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n\n\t// Maximum number of iterations exceeded, failure to converge\nlabel200:\n\t;\n\tinfo = 0\n\tfor i = 1; i <= n-1; i++ {\n\t\tif e.Get(i-1) != zero {\n\t\t\tinfo = info + 1\n\t\t}\n\t}\n\n\treturn\n}", "func (g *GMRES) qr(k int, givs []givens, hk, s []float64) {\n\tbi := blas64.Implementation()\n\t// Apply previous Givens rotations to the k-th row of H.\n\tfor i := 0; i < k; i++ {\n\t\tbi.Drot(1, hk[i:], 1, hk[i+1:], 1, givs[i].c, givs[i].s)\n\t}\n\t// Compute the k-th Givens rotation that zeroes H[k+1,k].\n\tgivs[k].c, givs[k].s, _, _ = bi.Drotg(hk[k], hk[k+1])\n\t// Apply the k-th Givens rotation to (hk[k], hk[k+1]).\n\tbi.Drot(1, hk[k:], 1, hk[k+1:], 1, givs[k].c, givs[k].s)\n\t// Apply the k-th Givens rotation to (s[k], s[k+1]).\n\tbi.Drot(1, s[k:], 1, s[k+1:], 1, givs[k].c, givs[k].s)\n}", "func gaussEliminationGF256(system [][]uint8, constantTerms [][]uint8) (unknowns [][]uint8, solvedEquations []bool, err error) {\n\tif len(system) == 0 {\n\t\treturn nil, nil, nil\n\t}\n\tunknowns = make([][]uint8, len(system[0]))\n\tnEq := len(system)\n\tnUnknowns := len(unknowns)\n\tsolvedEquations = make([]bool, nEq)\n\tsortSystem(system, constantTerms)\n\tfor i := 0; i < nEq-1; i++ {\n\t\tfor k := i + 1; k < nEq; k++ {\n\t\t\tif k > i {\n\t\t\t\tmulnum := system[k][i]\n\t\t\t\tmuldenom := system[i][i]\n\t\t\t\t// term=a[k][i]/a[i][i]\n\t\t\t\tterm := gf256Div(mulnum, muldenom)\n\t\t\t\tfor j := 0; j < nUnknowns; j++ {\n\t\t\t\t\t// a[k][j] -= a[k][i]/a[i][i]*a[i][j]\n\t\t\t\t\t// // i < m-1 AND m <= n, -> i < n-1\n\t\t\t\t\tsystem[k][j] = gf256Sub(system[k][j], gf256Mul(term, system[i][j]))\n\t\t\t\t}\n\t\t\t\t// a[k][j] -= a[k][i]/a[i][i]*a[i][j] for the big, constant term\n\t\t\t\tsymbolSubScaled(constantTerms[k], term, constantTerms[i])\n\t\t\t}\n\t\t}\n\t}\n\tcandidate := nUnknowns - 1\n\t//Begin Back-substitution\n\n\tfor i := nEq - 1; i >= 0; i-- {\n\t\tfor candidate >= 0 && system[i][candidate] == 0 {\n\t\t\tunknowns[candidate] = nil\n\t\t\tcandidate--\n\t\t}\n\t\tif candidate >= 0 {\n\t\t\tunknowns[candidate] = make([]uint8, len(constantTerms[i]))\n\t\t\tcopy(unknowns[candidate], constantTerms[i])\n\t\t\tfor j := 0; j < candidate; j++ {\n\t\t\t\tif system[i][j] != 0 {\n\t\t\t\t\t// if this variable depends on another one with a smaller index, it is undefined, as we don't know the value of the one with a smaller index\n\t\t\t\t\tunknowns[candidate] = nil\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor j := candidate + 1; j < nUnknowns; j++ {\n\t\t\t\t// x[i]=x[i]-a[i][j]*x[j];\n\t\t\t\tif system[i][j] != 0 {\n\t\t\t\t\tif unknowns[j] == nil {\n\t\t\t\t\t\t// if the unknown depends on an undetermined unknown, this unknown is unknowns\n\t\t\t\t\t\tunknowns[candidate] = nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsymbolSubScaled(unknowns[candidate], system[i][j], unknowns[j])\n\t\t\t\t\t\tsystem[i][j] = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// i < n_eq <= n_unknowns, so a[i][i] is small\n\t\t\tif unknowns[candidate] != nil && symbolIsZero(unknowns[candidate]) || system[i][candidate] == 0 {\n\t\t\t\t// this solution is unknowns\n\t\t\t\tunknowns[candidate] = nil\n\t\t\t} else if unknowns[candidate] != nil {\n\t\t\t\t// x[i] = x[i]/a[i][i]\n\t\t\t\tsolvedEquations[i] = true\n\t\t\t\tsymbolDiv(unknowns[candidate], system[i][candidate])\n\t\t\t\tsystem[i][candidate] = gf256Div(system[i][candidate], system[i][candidate])\n\t\t\t}\n\t\t}\n\t\tcandidate--\n\t}\n\t// mark all the variables with an index <= candidate as unknowns\n\tfor i := candidate; i >= 0; i-- {\n\t\tunknowns[i] = nil\n\t}\n\treturn\n}", "func PUNPCKHQDQ(mx, x operand.Op) { ctx.PUNPCKHQDQ(mx, x) }", "func (r *Reconciler) fail(instance *gcpv1alpha1.Provider, reason, msg string) (reconcile.Result, error) {\n\tinstance.Status.UnsetAllDeprecatedConditions()\n\tinstance.Status.SetFailed(reason, msg)\n\treturn resultRequeue, r.Update(context.TODO(), instance)\n}", "func (_m *MockAcknowledger) Reject(ctx context.Context) error {\n\tret := _m.Called(ctx)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context) error); ok {\n\t\tr0 = rf(ctx)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func VPCONFLICTQ(ops ...operand.Op) { ctx.VPCONFLICTQ(ops...) }", "func ADCXQ(mr, r operand.Op) { ctx.ADCXQ(mr, r) }", "func asErrAbuseRateLimit(resp *http.Response, logger log.Logger, defaultSleep time.Duration) *ErrAbuseRateLimit {\n\tif resp.StatusCode != http.StatusForbidden {\n\t\treturn nil\n\t}\n\n\tretryInHeader := resp.Header.Get(\"Retry-After\")\n\tretryIn, err := strconv.Atoi(retryInHeader)\n\tif err == nil {\n\t\treturn &ErrAbuseRateLimit{\n\t\t\terrRetryLater{time.Now().Add(time.Duration(retryIn) * time.Second)},\n\t\t}\n\t}\n\n\terrorResponse := &apiErrorResponse{}\n\terr = readAPIErrorResponse(resp, errorResponse)\n\tif err == nil && errorResponse.isAbuseRateLimit() {\n\t\tlogger.Warningf(\"error reading 'Retry-After=%s' header from the '403 Forbidden' response, using default '%s': %s\",\n\t\t\tretryInHeader,\n\t\t\tdefaultSleep,\n\t\t\terr,\n\t\t)\n\n\t\treturn &ErrAbuseRateLimit{\n\t\t\terrRetryLater{time.Now().Add(defaultSleep)},\n\t\t}\n\t}\n\n\tlogger.Warningf(\"403 Forbidden response got, but could not be read as an Abuse Rate Limit response\")\n\treturn nil\n}", "func (c *Context) VPSRLDQ(i, mxyz, xyz operand.Op) {\n\tc.addinstruction(x86.VPSRLDQ(i, mxyz, xyz))\n}", "func realloc(b *ringBuf, before, newLen int) {\n\tnewBuf := make([]raftpb.Entry, reallocLen(newLen))\n\tif b.head+b.len > len(b.buf) {\n\t\tn := copy(newBuf[before:], b.buf[b.head:])\n\t\tcopy(newBuf[before+n:], b.buf[:(b.head+b.len)%len(b.buf)])\n\t} else {\n\t\tcopy(newBuf[before:], b.buf[b.head:b.head+b.len])\n\t}\n\tb.buf = newBuf\n\tb.head = 0\n\tb.len = newLen\n}", "func (b *BufferflowTinyg) OnIncomingDataQrApproach(data string) {\n\t//log.Printf(\"OnIncomingData() start. data:%v\\n\", data)\n\tlog.Printf(\"OnIncomingData() start\\n\", data)\n\t// we need to queue up data since it comes in fragmented\n\t// and wait until we see a newline to analyze if there\n\t// is a qr value\n\tb.LatestData += data\n\n\t// now split on newline\n\tarrLines := b.reNewline.Split(b.LatestData, -1)\n\t//log.Printf(\"arrLines:%v\\n\", arrLines)\n\tif len(arrLines) > 1 {\n\t\t// that means we found a newline and have 2 or greater array values\n\t\t// so we need to analyze our arrLines[] lines but keep last line\n\t\t// for next trip into OnIncomingData\n\t\tlog.Printf(\"We have data lines to analyze. numLines:%v\\n\", len(arrLines))\n\n\t} else {\n\t\t// we don't have a newline yet, so just exit and move on\n\t\t// we don't have to reset b.LatestData because we ended up\n\t\t// without any newlines so maybe we will next time into this method\n\t\tlog.Printf(\"Did not find newline yet, so nothing to analyze\\n\")\n\t\treturn\n\t}\n\n\t// if we made it here we have lines to analyze\n\t// so analyze all of them except the last line\n\tfor index, element := range arrLines[:len(arrLines)-1] {\n\t\tlog.Printf(\"Working on element:%v, index:%v\", element, index)\n\n\t\tif b.re.MatchString(element) {\n\t\t\t// we have a qr value\n\n\t\t\t// if we've actually seen a qr value that means the user\n\t\t\t// put the tinyg in qr reporting mode, so turn off BypassMode\n\t\t\t// this is essentially a cool/lazy way to turn off BypassMode\n\t\t\tb.BypassMode = false\n\n\t\t\t//log.Printf(\"Found a qr value:%v\", re)\n\t\t\tres := b.re.FindStringSubmatch(element)\n\t\t\tif len(res) > 1 {\n\t\t\t\tqr, err := strconv.Atoi(res[1])\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Got error converting qr value. huh? err:%v\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Printf(\"The qr val is:\\\"%v\\\"\\n\", qr)\n\n\t\t\t\t\t// print warning if we got super low on buffer planner\n\t\t\t\t\tif qr < 4 {\n\t\t\t\t\t\tlog.Printf(\"------------\\nGot qr less than 4!!!! Bad cuz we stop at 10. qr:%v\\n---------\\n\", qr)\n\t\t\t\t\t}\n\n\t\t\t\t\tif qr <= b.StopSending {\n\n\t\t\t\t\t\t// TinyG is below our planner buffer threshold, better\n\t\t\t\t\t\t// stop sending to it\n\t\t\t\t\t\tlog.Println(\"qr is below stopsending threshold, so simply setting b.Paused to true so BlockUntilReady() sees we are paused\")\n\t\t\t\t\t\tb.Paused = true\n\t\t\t\t\t\t//log.Println(\"Paused sending gcode\")\n\n\t\t\t\t\t} else if qr >= b.StartSending {\n\n\t\t\t\t\t\t// TinyG has room in its buffer, remove the pause and\n\t\t\t\t\t\t// start sending in commands again\n\t\t\t\t\t\tb.Paused = false\n\t\t\t\t\t\tlog.Println(\"qr is above startsending, so we will send signal to b.sem to unpause the BlockUntilReady() thread\")\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\t// this method is pretty key\n\t\t\t\t\t\t\t// we run this asychronously, i.e. it's own thread, that's why\n\t\t\t\t\t\t\t// you see go func() because that go keyword launches this\n\t\t\t\t\t\t\t// function as its own thread. we get to tell the BlockUntilReady()\n\t\t\t\t\t\t\t// method to stop blocking by sending b.sem <- 1 to it\n\t\t\t\t\t\t\t// if you think about it, because we can start sending, we\n\t\t\t\t\t\t\t// need to unblock the sending\n\t\t\t\t\t\t\tgcodeline := element\n\n\t\t\t\t\t\t\tlog.Printf(\"StartSending Semaphore goroutine created for qr gcodeline:%v\\n\", gcodeline)\n\t\t\t\t\t\t\t// this is an unbuffered channel, so we will\n\t\t\t\t\t\t\t// block here which is why this is a goroutine\n\t\t\t\t\t\t\tb.sem <- 1\n\t\t\t\t\t\t\t// when we get here that means a BlockUntilReady()\n\t\t\t\t\t\t\t// method consumed the signal, meaning we unblocked them\n\t\t\t\t\t\t\t// which is good because they're allowed to start sending\n\t\t\t\t\t\t\t// again\n\t\t\t\t\t\t\tdefer func() {\n\t\t\t\t\t\t\t\tgcodeline := gcodeline\n\t\t\t\t\t\t\t\tlog.Printf(\"StartSending Semaphore just got consumed by the BlockUntilReady() thread for the qr gcodeline:%v\\n\", gcodeline)\n\t\t\t\t\t\t\t}()\n\t\t\t\t\t\t}()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"In a middle state where paused is:%v, qr:%v, watching for the buffer planner to go high or low.\\n\", b.Paused, qr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Problem extracting qr value in regexp. Didn't get 2 array elements or greater. Huh??? res:%v\", res)\n\t\t\t}\n\t\t} else if b.BypassMode && b.reQrOn.MatchString(element) {\n\t\t\t// it looks like user turned on qr reports, so turn off bypass mode\n\t\t\tb.BypassMode = false\n\t\t\tm := BufferMsg{\"BypassModeOff\", b.Port, element}\n\t\t\tbm, err := json.Marshal(m)\n\t\t\tif err == nil {\n\t\t\t\th.broadcastSys <- bm\n\t\t\t}\n\t\t\tlog.Printf(\"User turned on qr reports, so activating buffer control. qr on line:%v\\n\", element)\n\t\t} else if b.BypassMode == false && b.reQrOff.MatchString(element) {\n\t\t\t// it looks like user turned off qr reports, so jump into bypass mode\n\t\t\tb.BypassMode = true\n\t\t\tm := BufferMsg{\"BypassModeOn\", b.Port, element}\n\t\t\tbm, err := json.Marshal(m)\n\t\t\tif err == nil {\n\t\t\t\th.broadcastSys <- bm\n\t\t\t}\n\t\t\tlog.Printf(\"User turned off qr reports, so bypassing buffer control. qr off line:%v\\n\", element)\n\t\t\tif b.sem != nil {\n\t\t\t\tb.sem <- 1 // send channel a val to trigger the unblocking in BlockUntilReady()\n\t\t\t\tclose(b.sem)\n\t\t\t}\n\t\t\tlog.Println(\"Sent semaphore unblock in case anything was waiting since user entered bypassmode\")\n\t\t}\n\n\t\t// if we are handling sending the broadcast back to the client\n\t\t// from our buffer flow implementation, rather than letting the base\n\t\t// implementation of serial port json server do it, then send that\n\t\t// broadcast here. however, make sure you told spjs that you were\n\t\t// handling the data instead\n\t\tm := DataPerLine{b.Port, element + \"\\n\"}\n\t\tbm, err := json.Marshal(m)\n\t\tif err == nil {\n\t\t\th.broadcastSys <- bm\n\t\t}\n\n\t} // for loop\n\n\t// now wipe the LatestData to only have the last line that we did not analyze\n\t// because we didn't know/think that was a full command yet\n\tb.LatestData = arrLines[len(arrLines)-1]\n\n\t//time.Sleep(3000 * time.Millisecond)\n\tlog.Printf(\"OnIncomingData() end.\\n\")\n}" ]
[ "0.53862345", "0.5044344", "0.48412782", "0.4794837", "0.47453588", "0.47388983", "0.47364616", "0.47197607", "0.4716813", "0.4708198", "0.46771842", "0.46505207", "0.46497667", "0.46201667", "0.4603604", "0.4591043", "0.45706075", "0.45650077", "0.45476255", "0.45234725", "0.4511247", "0.45062718", "0.45029765", "0.44970673", "0.44933853", "0.44911787", "0.44882026", "0.44827545", "0.44813615", "0.4480566", "0.44788754", "0.4470929", "0.44636658", "0.44580144", "0.4441781", "0.4438389", "0.44294456", "0.43948823", "0.4394515", "0.43909937", "0.438718", "0.43622977", "0.43238395", "0.43175638", "0.43020108", "0.42935196", "0.42900684", "0.4271344", "0.42691797", "0.4265888", "0.42650908", "0.42629573", "0.4252971", "0.42487833", "0.42487833", "0.42487833", "0.42487833", "0.42301506", "0.42274046", "0.42224857", "0.4221001", "0.4211466", "0.42092067", "0.42057028", "0.42008814", "0.41949672", "0.41915703", "0.4186315", "0.41821492", "0.4173034", "0.41715127", "0.41636246", "0.41504276", "0.413912", "0.41304445", "0.41256532", "0.4117648", "0.41161442", "0.41143227", "0.41092485", "0.41058338", "0.41030708", "0.41015363", "0.409806", "0.4094353", "0.4088311", "0.40855306", "0.40834844", "0.40791768", "0.4076822", "0.40711072", "0.40609005", "0.40583187", "0.40520614", "0.4051017", "0.4049896", "0.40407556", "0.40333313", "0.40322953", "0.4031034" ]
0.42342845
57
polyUniform samples a polynomial with coefs in [0, Q]
func polyUniform(rho []byte, nonce []byte) Poly { var outbuf [shake128Rate]byte state := sha3.NewShake128() state.Write(rho[:]) state.Write(nonce) state.Read(outbuf[:]) var a Poly ctr := rej(a[:], outbuf[:]) for ctr < n { state.Read(outbuf[:shake128Rate]) ctr += rej(a[ctr:], outbuf[:shake128Rate]) } return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func RandomPolynomial(r io.Reader, degree uint64) (*Polynomial, error) {\n\tcoefficients := []*big.Int{}\n\tfor i := uint64(0); i < degree+1; i++ {\n\t\tc, err := rand.Int(r, bn256.Order)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tcoefficients = append(coefficients, c)\n\t}\n\treturn NewPolynomial(coefficients)\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func PolyMpq(q []MpqT, t []TermT) TermT {\n\tcount := C.uint32_t(len(q))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpqp(count, (*C.mpq_t)(&q[0]), (*C.term_t)(&t[0])))\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func (p Polynomial) Eval(arg int) ed25519.Scalar {\n\tx := ed25519.New_scalar(*big.NewInt(int64(arg)))\n\tresult := p.coeffs[0].Add(p.coeffs[1].Mul(x))\n\tx_pow := x.Copy()\n\tfor i := 2; i < len(p.coeffs); i++ {\n\t\tx_pow = x_pow.Mul(x)\n\t\tresult = result.Add(p.coeffs[i].Mul(x_pow))\n\t}\n\treturn result\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func SetRandomPolynomial(dst *poly.Poly, degree int) {\n\t// Make all memory available to be accessed.\n\t*dst = (*dst)[:cap(*dst)]\n\n\t// Fill entire memory with random values, as even memory locations\n\t// beyond the degree can contain non zero values in practice.\n\tfor i := range *dst {\n\t\t(*dst)[i] = secp256k1.RandomFn()\n\t}\n\n\t// Ensure that the leading term is non-zero.\n\tfor dst.Coefficient(degree).IsZero() {\n\t\t(*dst)[degree] = secp256k1.RandomFn()\n\t}\n\n\t// Set degree.\n\t*dst = (*dst)[:degree+1]\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func Random(degree int) Polynomial {\n\tvar coeffs []ed25519.Scalar\n\tfor i := 0; i <= degree; i++ {\n\t\tcoeffs = append(coeffs, ed25519.Random())\n\t}\n\treturn Polynomial{coeffs}\n}", "func NewMaterialPolynomial(c ...float64) Material {\n\treturn MaterialPolynomial{factors: c}\n}", "func (poly *PolynomialFeatures) Fit(Xmatrix, Ymatrix mat.Matrix) base.Fiter {\n\tX := base.ToDense(Xmatrix)\n\t_, nFeatures := X.Dims()\n\tpoly.Powers = make([][]int, 0)\n\tcomb := combinationsWithReplacement\n\tif poly.InteractionOnly {\n\t\tcomb = combinations\n\t}\n\tstart := 0\n\tif !poly.IncludeBias {\n\t\tstart = 1\n\t}\n\tfor i := start; i <= poly.Degree; i++ {\n\t\tfor c := range comb(intrange(nFeatures), i) {\n\t\t\tpoly.Powers = append(poly.Powers, bincount(c, nFeatures))\n\t\t}\n\t}\n\treturn poly\n}", "func NewPolynomialFeatures(degree int) *PolynomialFeatures {\n\treturn &PolynomialFeatures{Degree: degree, InteractionOnly: false, IncludeBias: true}\n\n}", "func (p Poly64) Minus(q Poly64) Poly64 {\n\treturn p ^ q\n}", "func NewCyclicPoly(n int) *CyclicPoly {\n\tif n < 1 {\n\t\tpanic(\"argument n must be positive\")\n\t}\n\treturn &CyclicPoly{p: make([]uint64, 0, n)}\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func Poly(p *sdf.Polygon, path string) error {\n\n\tvlist := p.Vertices()\n\tif vlist == nil {\n\t\treturn errors.New(\"no vertices\")\n\t}\n\n\tfmt.Printf(\"rendering %s\\n\", path)\n\td := NewDXF(path)\n\n\tfor i := 0; i < len(vlist)-1; i++ {\n\t\tp0 := vlist[i]\n\t\tp1 := vlist[i+1]\n\t\td.Line(p0, p1)\n\t}\n\n\tif p.Closed() {\n\t\tp0 := vlist[len(vlist)-1]\n\t\tp1 := vlist[0]\n\t\tif !p0.Equals(p1, tolerance) {\n\t\t\td.Line(p0, p1)\n\t\t}\n\t}\n\n\treturn d.Save()\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func NewPolynomialGenerator(b, step float64, a ...float64) *Euclidean {\n\tx := []float64{b}\n\tx = append(x, a...)\n\treturn &Euclidean{\n\t\tNewLinearSequence(0, step),\n\t\tF{f: []Y{\n\t\t\t// x coordinate :\n\t\t\tfunc(x ...float64) float64 {\n\t\t\t\treturn x[0]\n\t\t\t},\n\t\t\t// y coordinate\n\t\t\tpolynomialFunction(x...),\n\t\t}}}\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func makeRenderablePoly(name string, n int, drawType uint, color vec4) *Renderable {\n\t// build poly verts\n\tvertex := makePoly(n)\n\tr := &Renderable{\n\t\tworld.Transform(),\n\t\tworld.Operation(name, &world.Poly{Points: vertex}),\n\t\tworld.MaterialComponent{\n\t\t\tDrawType: drawType,\n\t\t\tProps: map[string]interface{}{\n\t\t\t\t\"color\": world.Color(color),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn r\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func PolyRational32(num []int32, den []uint32, t []TermT) TermT {\n\tcount := C.uint32_t(len(num))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_rational32(count, (*C.int32_t)(&num[0]), (*C.uint32_t)(&den[0]), (*C.term_t)(&t[0])))\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func QuadAxpy(c, b []float64, s float64, ci, bi int)", "func hornerPolyEval(poly []*big.Int, x *big.Int) *big.Int {\n\tresult := big.NewInt(0)\n\tresult.Add(result, poly[0])\n\tfor i := 1; i < len(poly); i++ {\n\t\tresult = result.Mul(result, x).Add(result, poly[i])\n\t}\n\treturn result.Mod(result, baseN)\n}", "func (p Poly) Generate(_ *rand.Rand, size int) reflect.Value {\n\tpoly := make(Poly, size)\n\tfor i := range poly {\n\t\tpoly[i] = secp256k1.RandomFn()\n\t}\n\treturn reflect.ValueOf(poly)\n}", "func (p thinPoly) Zero() thinPoly {\n\tfor i := range p {\n\t\tp[i] = 0\n\t}\n\treturn p\n}", "func polyGetNoise(eta int, seed []byte, nonce byte) Poly {\n\toutbuf := make([]byte, eta*n/4)\n\tstate := sha3.NewShake256()\n\tstate.Write(seed[:])\n\tstate.Write([]byte{nonce})\n\tstate.Read(outbuf[:])\n\tvar p Poly\n\tif eta == 3 {\n\t\tp = polyCBD3(outbuf)\n\t}\n\tif eta == 2 {\n\t\tp = polyCBD2(outbuf)\n\t}\n\treturn p\n}", "func (p *CubicPolynomial) Set(y0, y1, D0, D1 float64) {\n\tp.a = y0\n\tp.b = D0\n\tp.c = 3*(y1-y0) - 2*D0 - D1\n\tp.d = 2*(y0-y1) + D0 + D1\n\t// Zero out any coefficients that are small relative to the others.\n\tsum := math.Abs(p.a) + math.Abs(p.b) + math.Abs(p.c) + math.Abs(p.d)\n\tp.a = ZeroSmall(p.a, sum, epsilon)\n\tp.b = ZeroSmall(p.b, sum, epsilon)\n\tp.c = ZeroSmall(p.c, sum, epsilon)\n\tp.d = ZeroSmall(p.d, sum, epsilon)\n}", "func toomInterpolate(points [][]int32, param []int32) []int32 {\n\tt := make(thinPoly, 256)\n\tu := make(thinPoly, 256)\n\n\tfor i := range points {\n\t\tt.Inc(u.Mul(param[i], points[i]))\n\t}\n\n\treturn t.Freeze()\n}", "func lagrangeInterpolate(points map[int]*big.Int, x int, curve elliptic.Curve) *big.Int {\n\tlog.Printf(\"The points is: %v\", points)\n\n\t// 通过这些坐标点来恢复出多项式\n\tpolynomialClient := polynomial.New(curve.Params().N)\n\tresult := polynomialClient.GetPolynomialByPoints(points)\n\n\t// 秘密就是常数项\n\tsecret := result[len(result)-1]\n\n\tlog.Printf(\"The coefficients of the polynomial is: %v\", result)\n\treturn secret\n}", "func PolyInt32(a []int32, t []TermT) TermT {\n\tcount := C.uint32_t(len(a))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_int32(count, (*C.int32_t)(&a[0]), (*C.term_t)(&t[0])))\n}", "func PolyRational64(num []int64, den []uint64, t []TermT) TermT {\n\tcount := C.uint32_t(len(num))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_rational64(count, (*C.int64_t)(&num[0]), (*C.uint64_t)(&den[0]), (*C.term_t)(&t[0])))\n}", "func (p *Polynomial) Eval(x *big.Int) *big.Int {\n\t// uses Horner's method\n\tres := new(big.Int).Set((*p)[p.Degree()])\n\tfor i := int(p.Degree()) - 1; i >= 0; i-- {\n\t\tres.Mul(res, x)\n\t\tres.Add(res, (*p)[i])\n\t\tres.Mod(res, bn256.Order)\n\t}\n\treturn res\n}", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func (p thinPoly) Mul(c int32, v []int32) thinPoly {\n\tfor i := range v {\n\t\tp[i] = c * v[i]\n\t}\n\treturn p.Freeze()\n}", "func NewUniformSample(reservoirSize int) gometrics.Sample {\n\treturn &UniformSample{\n\t\treservoirSize: reservoirSize,\n\t\tvalues: make([]int64, 0, reservoirSize),\n\t}\n}", "func PolyMin(k float64) MinFunc {\n\treturn func(a, b float64) float64 {\n\t\treturn poly(a, b, k)\n\t}\n}", "func GetPolynomialValue(x *big.Int) *big.Int {\n\tx2 := new(big.Int).Mul(x, x)\n\tx3 := new(big.Int).Mul(x2, x)\n\taX2 := new(big.Int).Mul(A, x2)\n\tx3.Add(x3, new(big.Int).Add(aX2, x))\n\tx3.Mod(x3, P)\n\treturn x3\n}", "func UniformQuantize(scope *Scope, input tf.Output, scales tf.Output, zero_points tf.Output, Tout tf.DataType, quantization_min_val int64, quantization_max_val int64, optional ...UniformQuantizeAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"Tout\": Tout, \"quantization_min_val\": quantization_min_val, \"quantization_max_val\": quantization_max_val}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"UniformQuantize\",\n\t\tInput: []tf.Input{\n\t\t\tinput, scales, zero_points,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func GetUniformfv(program uint32, location int32, params *float32) {\n\tsyscall.Syscall(gpGetUniformfv, 3, uintptr(program), uintptr(location), uintptr(unsafe.Pointer(params)))\n}", "func quadform(Q quadForm, w Point) (sum float64) {\n\tv := [3]float64{w.X, w.Y, 1}\n\tfor i := 0; i < 3; i++ {\n\t\tfor j := 0; j < 3; j++ {\n\t\t\tsum += v[i] * Q[i][j] * v[j]\n\t\t}\n\t}\n\treturn sum\n}", "func (z *polyGF2) Mul(a, b *polyGF2) *polyGF2 {\n\tvar out *polyGF2\n\tif z != a && z != b {\n\t\tout = z\n\t} else {\n\t\tout = &polyGF2{}\n\t}\n\n\tdx := a.Degree()\n\tvar bs big.Int\n\tfor i := 0; i <= dx; i++ {\n\t\tif a.coeff.Bit(i) != 0 {\n\t\t\tbs.Lsh(&b.coeff, uint(i))\n\t\t\tout.coeff.Xor(&out.coeff, &bs)\n\t\t}\n\t}\n\n\tif z != out {\n\t\tz.coeff.Set(&out.coeff)\n\t}\n\treturn z\n}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func (p Poly64) Times(q Poly64) Poly64 {\n\tvar prod Poly64\n\tfor p != 0 && q != 0 {\n\t\tif q&1 != 0 {\n\t\t\tprod ^= p\n\t\t}\n\t\tq >>= 1\n\t\tp <<= 1\n\t}\n\treturn prod\n}", "func dividePolynomial(nn []float64 , dd []float64) (q, r []float64, ok bool) {\n \n if degree(dd) < 0 {\n return\n }\n\n nnfloat := append(r, nn...)\n \n if degree(nnfloat) >= degree(dd) {\n\n q = make([]float64, degree(nnfloat)-degree(dd)+1)\n\n for degree(nnfloat) >= degree(dd) {\n d := make([]float64, degree(nnfloat)+1)\n copy(d[degree(nnfloat)-degree(dd):], dd)\n q[degree(nnfloat)-degree(dd)] = nnfloat[degree(nnfloat)] / d[degree(d)]\n for i := range d {\n d[i] *= q[degree(nnfloat)-degree(dd)]\n nnfloat[i] -= d[i]\n }\n }\n }\n\n return q, nnfloat, true\n\n}", "func UniformQuantizedAdd(scope *Scope, lhs tf.Output, rhs tf.Output, lhs_scales tf.Output, lhs_zero_points tf.Output, rhs_scales tf.Output, rhs_zero_points tf.Output, output_scales tf.Output, output_zero_points tf.Output, lhs_quantization_min_val int64, lhs_quantization_max_val int64, rhs_quantization_min_val int64, rhs_quantization_max_val int64, output_quantization_min_val int64, output_quantization_max_val int64, optional ...UniformQuantizedAddAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"lhs_quantization_min_val\": lhs_quantization_min_val, \"lhs_quantization_max_val\": lhs_quantization_max_val, \"rhs_quantization_min_val\": rhs_quantization_min_val, \"rhs_quantization_max_val\": rhs_quantization_max_val, \"output_quantization_min_val\": output_quantization_min_val, \"output_quantization_max_val\": output_quantization_max_val}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"UniformQuantizedAdd\",\n\t\tInput: []tf.Input{\n\t\t\tlhs, rhs, lhs_scales, lhs_zero_points, rhs_scales, rhs_zero_points, output_scales, output_zero_points,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func PolyInt64(a []int64, t []TermT) TermT {\n\tcount := C.uint32_t(len(a))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_int64(count, (*C.int64_t)(&a[0]), (*C.term_t)(&t[0])))\n}", "func (q Quaternion) SquareSum() float64 {\n\treturn math.Pow(q.Q0, 2) + math.Pow(q.Q1, 2) + math.Pow(q.Q2, 2) + math.Pow(q.Q3, 2)\n}", "func ProgramUniform4fv(program uint32, location int32, count int32, value *float32) {\n\tsyscall.Syscall6(gpProgramUniform4fv, 4, uintptr(program), uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)), 0, 0)\n}", "func (z *polyGF2) MulX(a *polyGF2, n int) *polyGF2 {\n\tif n < 0 {\n\t\tpanic(\"power must be >= 0\")\n\t}\n\tz.coeff.Lsh(&a.coeff, uint(n))\n\treturn z\n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func interpolate(u []byte, v []byte) byte {\n\tvar r byte\n\tfor i, m := 0, len(u); i < m; i++ {\n\t\tr = add(r, mul(poly(i, u), v[i]))\n\t}\n\treturn r\n}", "func ProgramUniform4uiv(program uint32, location int32, count int32, value *uint32) {\n\tsyscall.Syscall6(gpProgramUniform4uiv, 4, uintptr(program), uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)), 0, 0)\n}", "func ProgramUniform1fv(program uint32, location int32, count int32, value *float32) {\n\tsyscall.Syscall6(gpProgramUniform1fv, 4, uintptr(program), uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)), 0, 0)\n}", "func (params *KeyParameters) Sample() (*big.Int, error) {\n\t// Choose a random exponent in [0,Q-1).\n\tR, err := rand.Int(rand.Reader, params.qMinusOne)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Add 1 so that the exponent is in [1,Q-1].\n\tR.Add(R, params.one)\n\treturn R, nil\n}", "func (z *Perplex) Quad() *big.Int {\n\tquad := new(big.Int)\n\treturn quad.Sub(\n\t\tquad.Mul(&z.l, &z.l),\n\t\tnew(big.Int).Mul(&z.r, &z.r),\n\t)\n}", "func rationalp0(x float64) float64 {\n\tconst (\n\t\ta0 = 1\n\t\ta1 = 5.931375839364438\n\t\ta2 = 11.39220550532913\n\t\ta3 = 7.33888339911111\n\t\ta4 = 0.653449016991959\n\n\t\tb0 = 1\n\t\tb1 = 6.931373689597704\n\t\tb2 = 16.82349461388016\n\t\tb3 = 16.43072324143226\n\t\tb4 = 5.115235195211697\n\t)\n\tnum := a0 + x*(a1+x*(a2+x*(a3+x*a4)))\n\tden := b0 + x*(b1+x*(b2+x*(b3+x*b4)))\n\treturn x * num / den\n}", "func sub(a, b Poly) Poly {\n\tvar c Poly\n\tfor i := 0; i < n; i++ {\n\t\tc[i] = a[i] - b[i]\n\t}\n\treturn c\n}", "func (p Poly64) Plus(q Poly64) Poly64 {\n\treturn p ^ q\n}", "func ProgramUniform1uiv(program uint32, location int32, count int32, value *uint32) {\n\tsyscall.Syscall6(gpProgramUniform1uiv, 4, uintptr(program), uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)), 0, 0)\n}", "func PSRLQ(imx, x operand.Op) { ctx.PSRLQ(imx, x) }", "func toomEval(p int, f, g *[768]int32) []int32 {\n\ta := make(thinPoly, 128)\n\tb := make(thinPoly, 128)\n\tt := make(thinPoly, 128)\n\n\tfor i,v := range toomEvalCoeffs[p] {\n\t\ta.Inc(t.Mul(v, f[i*128:(i+1)*128]))\n\t\tb.Inc(t.Mul(v, g[i*128:(i+1)*128]))\n\t}\n\n\treturn make(thinPoly, 256).Karatsuba1(a.Freeze(), b.Freeze())\n}", "func newPolyGF2(coeffs uint64) *polyGF2 {\n\tvar p polyGF2\n\tp.coeff.SetUint64(coeffs)\n\treturn &p\n}", "func PSUBQ(mx, x operand.Op) { ctx.PSUBQ(mx, x) }", "func (el *Fill) Polyline() {}", "func ProgramUniform4i(program uint32, location int32, v0 int32, v1 int32, v2 int32, v3 int32) {\n\tsyscall.Syscall6(gpProgramUniform4i, 6, uintptr(program), uintptr(location), uintptr(v0), uintptr(v1), uintptr(v2), uintptr(v3))\n}", "func Polyfill(gp GeoPolygon, res int) []H3Index {\n\tcgp := geoPolygonToC(gp)\n\tdefer freeCGeoPolygon(&cgp)\n\n\tmaxSize := C.maxPolyfillSize(&cgp, C.int(res))\n\tcout := make([]C.H3Index, maxSize)\n\tC.polyfill(&cgp, C.int(res), &cout[0])\n\n\treturn h3SliceFromC(cout)\n}", "func (p *CubicPolynomial) f0(t float64) float64 {\n\treturn p.a + t*(p.b+t*(p.c+p.d*t))\n}", "func Pow(base []uint8, exp uint64) []uint8 {\n\tvar result []uint8 = base\n\n\tfor i := exp - 1; i != 0; i-- {\n\t\tresult = Product(result, base)\n\t}\n\treturn result\n}", "func ProgramUniform4f(program uint32, location int32, v0 float32, v1 float32, v2 float32, v3 float32) {\n\tsyscall.Syscall6(gpProgramUniform4f, 6, uintptr(program), uintptr(location), uintptr(math.Float32bits(v0)), uintptr(math.Float32bits(v1)), uintptr(math.Float32bits(v2)), uintptr(math.Float32bits(v3)))\n}", "func MakeTable(poly uint32) *Table {}", "func (rng RandomGenerator) MakeUniformVector(size int, low, high float64) []float64 {\n\tret := make([]float64, size)\n\tscale := high - low\n\tfor i := 0; i < len(ret); i++ {\n\t\tret[i] = rng.Float64()*scale + low\n\t}\n\treturn ret\n}", "func FactorBerlekamp(f []int64, char int64) [][]int64 {\n\tn := len(f) - 1\n\tmatrix := createMatrix(n)\n\tunit := []int64{0, 1}\n\n\t// Compute Q - I where I is the unit matrix\n\t// The kth row is x^(kp) mod f. We skip the first row because Q - I is always 0.\n\tfor k := 1; k < n; k++ {\n\t\tt := make([]int64, n)\n\t\tp := PolynomialModExp(unit, int64(k)*char, f, char)\n\t\tcopy(t, p)\n\t\tmatrix[k] = t\n\t\tmatrix[k][k] = (matrix[k][k] + char - int64(1)) % char\n\t}\n\n\t// Find null space for Q - I\n\tvecs, numSolutions := computeNullSpace(matrix, n, char)\n\n\t// Polynomial is irreducible\n\tif numSolutions == 1 {\n\t\treturn [][]int64{}\n\t}\n\n\t// For each vector, compute GCD for u(x), vec - s for 0 <= s < p.\n\t// The result gives a nontrivial factorization of u.\n\t// We push each nontrivial factorization of u onto a list and\n\t// then continue to reduce.\n\tfactorization := make([][]int64, numSolutions)\n\tfactorization[0] = f\n\tfoundFactors := 1\n\n\t// Invariant: factors is always a factorization of f.\n\tfor _, vec := range vecs {\n\tFactor:\n\t\tfor i := 0; i < foundFactors; i++ {\n\t\t\tfactor := factorization[i]\n\t\t\tfor s := int64(0); s < char; s++ {\n\t\t\t\tunit := []int64{char - s}\n\t\t\t\tp1 := PolynomialAdd(vec, unit, char)\n\t\t\t\tp := PolynomialGcd(p1, factor, char)\n\n\t\t\t\tif len(p) > 1 {\n\t\t\t\t\tq, _ := PolynomialDivide(p, factor, char)\n\n\t\t\t\t\t// p + q is a non-trivial breakdown of the\n\t\t\t\t\tif len(q) > 1 {\n\t\t\t\t\t\tfactorization[i] = p\n\t\t\t\t\t\tfactorization[foundFactors] = q\n\t\t\t\t\t\tfoundFactors++\n\n\t\t\t\t\t\tcontinue Factor\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif foundFactors == numSolutions {\n\t\treturn factorization\n\t}\n\n\tpanic(\"Bug in factorization, should never get here\")\n}", "func Uniform1fv(location int32, count int32, value *float32) {\n\tsyscall.Syscall(gpUniform1fv, 3, uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)))\n}", "func (p *Poly) reduce() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = barretReduce(p[i])\n\t}\n}", "func PolygonOffset(factor, units float32) {\n\tgl.PolygonOffset(factor, units)\n}", "func NewPolyDataMapper(nOriFeatures, iFeature, jFeature, order int) (o *PolyDataMapper) {\n\n\t// check\n\tif order < 2 {\n\t\tchk.Panic(\"PolyDataMapper is useful for order >= 2. order = %d is invalid\\n\", order)\n\t}\n\tif iFeature > nOriFeatures-1 {\n\t\tchk.Panic(\"iFeature must be within [0, %d]. iFeature = %d is invalid\\n\", nOriFeatures-1, iFeature)\n\t}\n\tif jFeature > nOriFeatures {\n\t\tchk.Panic(\"jFeature must be within [0, %d]. jFeature = %d is invalid\\n\", nOriFeatures-1, jFeature)\n\t}\n\n\t// input data\n\to = new(PolyDataMapper)\n\to.nOriFeatures = nOriFeatures\n\to.iFeature = iFeature\n\to.jFeature = jFeature\n\to.order = order\n\n\t// derived\n\tp := o.order + 1 // auxiliary\n\tnPascal := p*(p+1)/2 - 1 // -1 because first row in Pascal triangle is neglected\n\to.nExtraFeatures = nPascal - 2 // -2 because iFeature and jFeatureare were considered in nPascal already\n\treturn\n}", "func (poly *PolynomialFeatures) Transform(X, Y mat.Matrix) (Xout, Yout *mat.Dense) {\n\tnSamples, _ := X.Dims()\n\tXout = mat.NewDense(nSamples, len(poly.Powers), nil)\n\txi, xo := base.ToDense(X).RawMatrix(), Xout.RawMatrix()\n\tfor i, ipos, opos := 0, 0, 0; i < nSamples; i, ipos, opos = i+1, ipos+xi.Stride, opos+xo.Stride {\n\t\tfor ioutput, p := range poly.Powers {\n\t\t\tv := 1.\n\t\t\tfor j, pj := range p {\n\t\t\t\tv *= math.Pow(xi.Data[ipos+j], float(pj))\n\t\t\t}\n\t\t\txo.Data[opos+ioutput] = v\n\t\t}\n\t}\n\treturn Xout, base.ToDense(Y)\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func p256Sqr(res, in []uint64, n int)", "func (phi *isogeny4) GenerateCurve(p *ProjectivePoint) CurveCoefficientsEquiv {\n\tvar coefEq CurveCoefficientsEquiv\n\tvar xp4, zp4 = &p.X, &p.Z\n\tvar K1, K2, K3 = &phi.K1, &phi.K2, &phi.K3\n\n\top := phi.Field\n\top.Sub(K2, xp4, zp4)\n\top.Add(K3, xp4, zp4)\n\top.Square(K1, zp4)\n\top.Add(K1, K1, K1)\n\top.Square(&coefEq.C, K1)\n\top.Add(K1, K1, K1)\n\top.Square(&coefEq.A, xp4)\n\top.Add(&coefEq.A, &coefEq.A, &coefEq.A)\n\top.Square(&coefEq.A, &coefEq.A)\n\treturn coefEq\n}", "func newPowGen(e float64) func() float64 {\n\tvar i float64\n\treturn func() (r float64) {\n\t\tr = math.Pow(i, e)\n\t\ti++\n\t\treturn\n\t}\n}", "func p256Sqr(res, in []uint64)", "func NewUniform1fv(name string, count int) *Uniform1fv {\n\n\tuni := new(Uniform1fv)\n\tuni.Init(name, count)\n\treturn uni\n}", "func Uniform4fv(location int32, count int32, value *float32) {\n\tsyscall.Syscall(gpUniform4fv, 3, uintptr(location), uintptr(count), uintptr(unsafe.Pointer(value)))\n}", "func ProgramUniform4i(program uint32, location int32, v0 int32, v1 int32, v2 int32, v3 int32) {\n C.glowProgramUniform4i(gpProgramUniform4i, (C.GLuint)(program), (C.GLint)(location), (C.GLint)(v0), (C.GLint)(v1), (C.GLint)(v2), (C.GLint)(v3))\n}", "func Uniform4i(location int32, v0 int32, v1 int32, v2 int32, v3 int32) {\n\tsyscall.Syscall6(gpUniform4i, 5, uintptr(location), uintptr(v0), uintptr(v1), uintptr(v2), uintptr(v3), 0)\n}", "func ProgramUniform4uiv(program uint32, location int32, count int32, value *uint32) {\n\tC.glowProgramUniform4uiv(gpProgramUniform4uiv, (C.GLuint)(program), (C.GLint)(location), (C.GLsizei)(count), (*C.GLuint)(unsafe.Pointer(value)))\n}", "func ProgramUniform4uiv(program uint32, location int32, count int32, value *uint32) {\n\tC.glowProgramUniform4uiv(gpProgramUniform4uiv, (C.GLuint)(program), (C.GLint)(location), (C.GLsizei)(count), (*C.GLuint)(unsafe.Pointer(value)))\n}", "func ProgramUniform1f(program uint32, location int32, v0 float32) {\n\tsyscall.Syscall(gpProgramUniform1f, 3, uintptr(program), uintptr(location), uintptr(math.Float32bits(v0)))\n}", "func Point_from_uniform(data []byte) (Point,error) { // TODO:check if it return valid point in test\n\tfor i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 { // reversal of bytes\n\t\tdata[i], data[j] = data[j], data[i]\n\t}\n\tfor len(data)<32 { // TODO: Ouput error on len< 32 or add zeros\n\t\tdata = append(data,0)\n\t}\n\ttemp := Raw_point()\n\tif C.crypto_core_ed25519_from_uniform((*C.uchar)(&temp.Val[0]), (*C.uchar)(&data[0])) == 0 {\n\t\treturn temp,nil\n\t}\n\treturn temp,errors.New(\"from uniform op not working\")\n \n}" ]
[ "0.5968619", "0.58332783", "0.57192487", "0.5673166", "0.5486337", "0.54848266", "0.5362569", "0.5302037", "0.5252298", "0.51827276", "0.51822376", "0.51009536", "0.50639194", "0.5056258", "0.5029839", "0.4984477", "0.4947015", "0.4942746", "0.4882782", "0.48416886", "0.4835946", "0.4821843", "0.48101836", "0.48079184", "0.4804868", "0.47876775", "0.4730663", "0.47072804", "0.47061083", "0.4690971", "0.4612279", "0.45689824", "0.45320597", "0.45041403", "0.44790658", "0.44486085", "0.4446429", "0.44213492", "0.44115898", "0.44049677", "0.4376399", "0.43516812", "0.43462062", "0.43288782", "0.43263593", "0.43254992", "0.43020254", "0.42946216", "0.4293749", "0.42933905", "0.42757463", "0.4261526", "0.42601123", "0.4254425", "0.42514", "0.425128", "0.42478964", "0.4227093", "0.42268425", "0.42179847", "0.421005", "0.4189747", "0.4183872", "0.4179216", "0.4179188", "0.4178153", "0.4177744", "0.4176313", "0.41604382", "0.41594043", "0.4156341", "0.4154441", "0.41512102", "0.41390413", "0.41303506", "0.41194186", "0.41151246", "0.4113483", "0.41050747", "0.41048354", "0.41037387", "0.4103198", "0.41014618", "0.4086584", "0.4085052", "0.40680945", "0.40665442", "0.40619263", "0.40615055", "0.40609348", "0.40598908", "0.4053335", "0.40520653", "0.40505645", "0.40439218", "0.40406623", "0.4035633", "0.4035633", "0.40318897", "0.40282312" ]
0.70174384
0
polyGetNoise samples a polynomial with coefs in [Qeta, Q+eta]
func polyGetNoise(eta int, seed []byte, nonce byte) Poly { outbuf := make([]byte, eta*n/4) state := sha3.NewShake256() state.Write(seed[:]) state.Write([]byte{nonce}) state.Read(outbuf[:]) var p Poly if eta == 3 { p = polyCBD3(outbuf) } if eta == 2 { p = polyCBD2(outbuf) } return p }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func (honest *Honest) requestNoise(iterationCount int) ([]float64, error) {\n\n\truntime.LockOSThread()\n\n\t_gstate := python.PyGILState_Ensure()\n\n\t// Either use full GD or SGD here\n\tvar result *python.PyObject\n\tresult = pyNoiseFunc.CallFunction(python.PyInt_FromLong(iterationCount))\n\n\t// Convert the resulting array to a go byte array\n\tpyByteArray := python.PyByteArray_FromObject(result)\n\tgoByteArray := python.PyByteArray_AsBytes(pyByteArray)\n\n\tpython.PyGILState_Release(_gstate)\n\n\tvar goFloatArray []float64\n\tsize := len(goByteArray) / 8\n\n\tfor i := 0; i < size; i++ {\n\t\tcurrIndex := i * 8\n\t\tbits := binary.LittleEndian.Uint64(goByteArray[currIndex : currIndex+8])\n\t\taFloat := math.Float64frombits(bits)\n\t\tgoFloatArray = append(goFloatArray, aFloat)\n\t}\n\n\treturn goFloatArray, nil\n\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func newNoise(eng *engine, eid uint64) *noise {\n\treturn &noise{eng: eng, eid: eid}\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func NSEpow(o, s []float64, p float64) float64 {\n\tvar n, d float64\n\tom, _ := Meansd(o)\n\tif len(o) != len(s) {\n\t\tlog.Fatalf(\"NSEpow array lengths not matching %d %d\\n\", len(o), len(s))\n\t}\n\tfor i := range o {\n\t\tif !math.IsNaN(s[i]) && !math.IsNaN(o[i]) {\n\t\t\tn += math.Pow(s[i]-o[i], p)\n\t\t\td += math.Pow(o[i]-om, p)\n\t\t}\n\t}\n\treturn 1. - n/d\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func NewZeroNoise(q, r int) Noise {\n\tnse := Noise{\n\t\tQ: mat.NewDense(q, q, nil),\n\t\tR: mat.NewDense(r, r, nil),\n\t}\n\treturn nse\n}", "func (kf *HybridKF) GetNoise() Noise {\n\treturn kf.Noise\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func genSineProfile(samplePeriod float64, frequency float64, ampScale float64) ([]int32) {\n\tvar (\n\t\tsamplesPerSecond\tfloat64 = 1 / float64(samplePeriod) \n\t\tphase \t\t\t\tfloat64\n\t\tradiansPerSample \tfloat64 = float64(frequency * 2 * math.Pi / float64(samplesPerSecond))\n\t\t//Number of samples just enough to generate one period\n\t\tnumberOfSamples\t\tuint32 = uint32(2 * math.Pi / float64(radiansPerSample))\n\t\twaveform\t\t\t[]int32 = make([]int32, numberOfSamples)\n\t)\n\n\tfor sample := uint32(0); sample < numberOfSamples; sample++ {\n\t\tsampleValue := float64(ampScale) * 0.5 * float64( 1 + math.Sin(phase) + 0.1)//0.1 is needed to avoid a divide by zero in boomer\n\t\twaveform[sample] = int32(sampleValue)\n\t\tphase += radiansPerSample\n\t}\n\n\treturn waveform\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func RandomPolynomial(r io.Reader, degree uint64) (*Polynomial, error) {\n\tcoefficients := []*big.Int{}\n\tfor i := uint64(0); i < degree+1; i++ {\n\t\tc, err := rand.Int(r, bn256.Order)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tcoefficients = append(coefficients, c)\n\t}\n\treturn NewPolynomial(coefficients)\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func (p *Perlin) Noise3D(x, y, z float64) float64 {\n\t// Calculate the unit cube around the coordinates\n\txi := int(x) & 255\n\tyi := int(y) & 255\n\tzi := int(z) & 255\n\n\txf := x - math.Floor(x)\n\tyf := y - math.Floor(y)\n\tzf := z - math.Floor(z)\n\n\tu := fade(xf)\n\tv := fade(yf)\n\tw := fade(zf)\n\n\taaa := p.p[p.p[p.p[xi]+yi]+zi]\n\taba := p.p[p.p[p.p[xi]+inc(yi)]+zi]\n\taab := p.p[p.p[p.p[xi]+yi]+inc(zi)]\n\tabb := p.p[p.p[p.p[xi]+inc(yi)]+inc(zi)]\n\tbaa := p.p[p.p[p.p[inc(xi)]+yi]+zi]\n\tbba := p.p[p.p[p.p[inc(xi)]+inc(yi)]+zi]\n\tbab := p.p[p.p[p.p[inc(xi)]+yi]+inc(zi)]\n\tbbb := p.p[p.p[p.p[inc(xi)]+inc(yi)]+inc(zi)]\n\n\tvar x1, x2, y1, y2 float64\n\tx1 = lerp(\n\t\tgrad(aaa, xf, yf, zf),\n\t\tgrad(baa, xf-1, yf, zf), u)\n\tx2 = lerp(\n\t\tgrad(aba, xf, yf-1, zf),\n\t\tgrad(bba, xf-1, yf-1, zf), u)\n\ty1 = lerp(x1, x2, v)\n\tx1 = lerp(\n\t\tgrad(aab, xf, yf, zf-1),\n\t\tgrad(bab, xf-1, yf, zf-1), u)\n\tx2 = lerp(\n\t\tgrad(abb, xf, yf-1, zf-1),\n\t\tgrad(bbb, xf-1, yf-1, zf-1), u)\n\ty2 = lerp(x1, x2, v)\n\n\treturn (lerp(y1, y2, w) + 1) / 2\n}", "func NSE(o, s []float64) float64 {\n\treturn NSEpow(o, s, 2.)\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func drawNoise(noise []float32, gradient []rgba, pixels []byte) {\n\tfor i := range noise {\n\t\tc := gradient[clamp(0, 255, int(noise[i]))]\n\t\tp := i * 4\n\t\tpixels[p] = c.r\n\t\tpixels[p+1] = c.g\n\t\tpixels[p+2] = c.b\n\t}\n}", "func PCMPISTRI(i, mx, x operand.Op) { ctx.PCMPISTRI(i, mx, x) }", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func NewPolynomialFeatures(degree int) *PolynomialFeatures {\n\treturn &PolynomialFeatures{Degree: degree, InteractionOnly: false, IncludeBias: true}\n\n}", "func handler(w http.ResponseWriter, _ *http.Request) {\n\tsignal, _ := dsp.ReadSignalFile(\"examples/signals/example-noisy-signal_31_hz.txt\", 31)\n\n\tplot1 := plotSignal(signal, opts.Title{\n\t\tTitle: \"Original signal\",\n\t\tSubtitle: signal.String(),\n\t})\n\n\tpage := components.NewPage()\n\tpage.AddCharts(plot1)\n\n\tsplit := 10\n\tparts := signal.Split(time.Duration(split) * time.Second)\n\n\tduration := 0.0\n\n\tfor i := 0; i < len(parts); i++ {\n\t\tpart := parts[i]\n\n\t\tfrom := i * split\n\t\tto := from + int(part.Duration())\n\n\t\tpage.AddCharts(plotSignal(part, opts.Title{\n\t\t\tTitle: fmt.Sprintf(\"Signal %vs to %vs\", i*split, (i+1)*split),\n\t\t\tSubtitle: part.String(),\n\t\t}))\n\n\t\t// Normalize the signal around -1 and 1\n\t\tsignalNormalized, err := part.Normalize()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tpage.AddCharts(plotSignal(signalNormalized, opts.Title{\n\t\t\tTitle: fmt.Sprintf(\"Normalized signal %vs to %vs\", from, to),\n\t\t\tSubtitle: signalNormalized.String(),\n\t\t}))\n\n\t\t// 4. Frequency spectrum of the signal\n\t\tfrequencySpectrum, err := signalNormalized.FrequencySpectrum()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tpage.AddCharts(plotSpectrum(frequencySpectrum, opts.Title{\n\t\t\tTitle: fmt.Sprintf(\"Frequency spectrum %vs to %vs\", from, to),\n\t\t\tSubtitle: frequencySpectrum.String(),\n\t\t}))\n\n\t\t// Some example calculations\n\t\tfor j, frequency := range frequencySpectrum.Frequencies {\n\t\t\t// Only care frequencies above 2hz\n\t\t\tif frequency > 2 {\n\t\t\t\tif frequencySpectrum.Spectrum[j] > 0.3 {\n\t\t\t\t\t// More than 30%, it's considered noisy\n\t\t\t\t\tduration += part.Duration()\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"noisy %vs, percentage %.1f%%\\n\", duration, 100*duration/signal.Duration())\n\n\tpage.Render(w)\n}", "func (p *Perlin) OctaveNoise2D(x, y float64) float64 {\n\ttotal := 0.0\n\tfrequency := 1.0\n\tamplitude := 1.0\n\tmaxValue := 0.0\n\t// Add up to Octaves different variations of noise and return the sum\n\tfor i:=0.0; i<p.Octaves; i++ {\n\t\ttotal += amplitude * p.Noise2D(x * frequency, y * frequency)\n\n\t\tmaxValue += amplitude\n\t\tamplitude *= p.Persistence\n\t\tfrequency *= 2\n\t}\n\n\treturn total/maxValue\n}", "func (p* Perlin) OctaveNoise3D(x, y, z float64) float64 {\n\ttotal := 0.0\n\tfrequency := 1.0\n\tamplitude := 1.0\n\tmaxValue := 0.0\n\n\tfor i:=0.0; i<p.Octaves; i++ {\n\t\ttotal += amplitude * p.Noise3D(x * frequency, y * frequency, z * frequency)\n\n\t\tmaxValue += amplitude\n\t\tamplitude *= p.Persistence\n\t\tfrequency *= 2\n\t}\n\n\treturn total/maxValue\n}", "func (p *Noise) addNoise(value interface{}) interface{} {\n\tn := p.generator.Rand()\n\tswitch v := value.(type) {\n\tcase int:\n\tcase int8:\n\tcase int16:\n\tcase int32:\n\tcase int64:\n\t\tif v > 0 && (n > math.Nextafter(float64(math.MaxInt64), 0) || int64(n) > math.MaxInt64-v) {\n\t\t\tp.Log.Debug(\"Int64 overflow, setting value to MaxInt64\")\n\t\t\treturn int64(math.MaxInt64)\n\t\t}\n\t\tif v < 0 && (n < math.Nextafter(float64(math.MinInt64), 0) || int64(n) < math.MinInt64-v) {\n\t\t\tp.Log.Debug(\"Int64 (negative) overflow, setting value to MinInt64\")\n\t\t\treturn int64(math.MinInt64)\n\t\t}\n\t\treturn v + int64(n)\n\tcase uint:\n\tcase uint8:\n\tcase uint16:\n\tcase uint32:\n\tcase uint64:\n\t\tif n < 0 {\n\t\t\tif uint64(-n) > v {\n\t\t\t\tp.Log.Debug(\"Uint64 (negative) overflow, setting value to 0\")\n\t\t\t\treturn uint64(0)\n\t\t\t}\n\t\t\treturn v - uint64(-n)\n\t\t}\n\t\tif n > math.Nextafter(float64(math.MaxUint64), 0) || uint64(n) > math.MaxUint64-v {\n\t\t\tp.Log.Debug(\"Uint64 overflow, setting value to MaxUint64\")\n\t\t\treturn uint64(math.MaxUint64)\n\t\t}\n\t\treturn v + uint64(n)\n\tcase float32:\n\t\treturn v + float32(n)\n\tcase float64:\n\t\treturn v + n\n\tdefault:\n\t\tp.Log.Debugf(\"Value (%v) type invalid: [%v] is not an int, uint or float\", v, reflect.TypeOf(value))\n\t}\n\treturn value\n}", "func monoCubicInterpolate(xs []float64, ys []float64) func(float64) float64 {\n\tlength := len(xs)\n\n\t// Dealing with length issues\n\tswitch {\n\tcase length != len(ys):\n\t\tpanic(errors.New(\"need an equal count of xs and ys\"))\n\tcase length == 0:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn 0\n\t\t}\n\tcase length == 1:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn ys[0]\n\t\t}\n\t}\n\n\t// Get consecutive differences and slopes\n\tdys := make([]float64, length-1)\n\tdxs := make([]float64, length-1)\n\tms := make([]float64, length-1)\n\tfor i := 0; i < length-1; i++ {\n\t\tdx := xs[i+1] - xs[i]\n\t\tdy := ys[i+1] - ys[i]\n\t\tdxs[i], dys[i], ms[i] = dx, dy, dy/dx\n\t}\n\n\t// Get degree-1 coefficients\n\tc1s := make([]float64, length)\n\tc1s[0] = ms[0]\n\tfor i := 1; i < len(dxs); i++ {\n\t\tm, mNext := ms[i-1], ms[i]\n\t\tif m * mNext <= 0 {\n\t\t\tc1s[i] = 0\n\t\t} else {\n\t\t\tdx_, dxNext := dxs[i-1], dxs[i]\n\t\t\tcommon := dx_ + dxNext\n\t\t\tc1s[i] = 3 * common / ((common + dxNext)/m + (common + dx_)/mNext)\n\t\t}\n\t}\n\tc1s[length-1] = ms[len(ms)-1]\n\n\t// Get degree-2 and degree-3 coefficients\n\tc2s := make([]float64, length-1)\n\tc3s := make([]float64, length-1)\n\tfor i := 0; i < len(c1s)-1; i++ {\n\t\tc1, m_ := c1s[i], ms[i]\n\t\tinvDx, common_ := 1/dxs[i], c1 + c1s[i+1] - m_ - m_\n\t\tc2s[i] = (m_ - c1 - common_) * invDx\n\t\tc3s[i] = common_ * invDx * invDx\n\t}\n\n\t// Return interpolant function\n\treturn func(x float64) float64 {\n\t\t// The rightmost point in the dataset should give an exact result\n\t\ti := len(xs) - 1\n\t\tif x == xs[i] {\n\t\t\treturn ys[i]\n\t\t}\n\n\t\t// Search for the interval x is in, returning the corresponding y if x is one of the original xs\n\t\tlow, mid, high := 0, len(c3s)-1, len(c3s)-1\n\t\tfor low <= high {\n\t\t\tmid = int(math.Floor(0.5 * float64(low + high)))\n\t\t\txHere := xs[mid]\n\t\t\tif xHere < x {\n\t\t\t\tlow = mid + 1\n\t\t\t} else if xHere > x {\n\t\t\t\thigh = mid - 1\n\t\t\t} else {\n\t\t\t\treturn ys[mid]\n\t\t\t}\n\t\t}\n\t\ti = int(math.Max(0, float64(high)))\n\n\t\t// Interpolate\n\t\tdiff := x - xs[i]\n\t\tdiffSq := diff*diff\n\t\treturn ys[i] + c1s[i]*diff + c2s[i]*diffSq + c3s[i]*diff*diffSq\n\t}\n\n}", "func (p thinPoly) Zero() thinPoly {\n\tfor i := range p {\n\t\tp[i] = 0\n\t}\n\treturn p\n}", "func newNCO(w float64, n int) []complex128 {\n\tnco := make([]complex128, n)\n\tfor i := range nco {\n\t\tnco[i] = complex128(cmplx.Exp(complex(0, 2*math.Pi*w*float64(i))))\n\t}\n\treturn nco\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func PCMPESTRI(i, mx, x operand.Op) { ctx.PCMPESTRI(i, mx, x) }", "func RandomNoise() float64 {\n\trand.Seed(time.Now().UnixNano())\n\tmin := 0.00005\n\tnumber := (rand.Float64() * 10)\n\tif number < min {\n\t\tnumber = min\n\t}\n\tdivisor := float64(10000)\n\n\tif rand.Float64() >= 0.5 {\n\t\treturn number / divisor\n\t}\n\n\treturn number / divisor * -1\n}", "func generateNoise(responseChannel chan OscResponse) {\n doLog( \"generating audio\" )\n var t float64 = 0\n file := os.Stdout\n data := new(bytes.Buffer)\n sample := 0\n for {\n //TODO: check for UDP packets and send data in response\n l := (int16) ( 16000 * math.Sin(t) )\n r := (int16) ( 16000 * math.Cos(2*t) )\n binary.Write(data, binary.LittleEndian, l)\n binary.Write(data, binary.LittleEndian, r)\n if sample == 255 {\n file.Write(data.Bytes())\n sample = -1\n file.Sync()\n data.Reset()\n }\n t = t + 0.01\n sample = sample + 1\n }\n}", "func sineInputs() []float64 {\n\tvar res []float64\n\n\tfor i := 0; i < 200; i++ {\n\t\tv := math.Sin(float64(i) / 100 * math.Pi)\n\t\tres = append(res, v)\n\t}\n\treturn res\n}", "func PolyInt64(a []int64, t []TermT) TermT {\n\tcount := C.uint32_t(len(a))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_int64(count, (*C.int64_t)(&a[0]), (*C.term_t)(&t[0])))\n}", "func GetPolynomialValue(x *big.Int) *big.Int {\n\tx2 := new(big.Int).Mul(x, x)\n\tx3 := new(big.Int).Mul(x2, x)\n\taX2 := new(big.Int).Mul(A, x2)\n\tx3.Add(x3, new(big.Int).Add(aX2, x))\n\tx3.Mod(x3, P)\n\treturn x3\n}", "func New(seed int64) *Noise {\n\treturn &Noise{gfx.NewSimplexNoise(seed)}\n}", "func (this *NurbsCurve) regularSample(numSamples int) []CurvePoint {\n\treturn this.regularSampleRange(\n\t\tthis.knots[0], this.knots[len(this.knots)-1],\n\t\tnumSamples,\n\t)\n}", "func Pow(base []uint8, exp uint64) []uint8 {\n\tvar result []uint8 = base\n\n\tfor i := exp - 1; i != 0; i-- {\n\t\tresult = Product(result, base)\n\t}\n\treturn result\n}", "func Random(degree int) Polynomial {\n\tvar coeffs []ed25519.Scalar\n\tfor i := 0; i <= degree; i++ {\n\t\tcoeffs = append(coeffs, ed25519.Random())\n\t}\n\treturn Polynomial{coeffs}\n}", "func toomInterpolate(points [][]int32, param []int32) []int32 {\n\tt := make(thinPoly, 256)\n\tu := make(thinPoly, 256)\n\n\tfor i := range points {\n\t\tt.Inc(u.Mul(param[i], points[i]))\n\t}\n\n\treturn t.Freeze()\n}", "func (el *Fill) Polyline() {}", "func (p Polynomial) Eval(arg int) ed25519.Scalar {\n\tx := ed25519.New_scalar(*big.NewInt(int64(arg)))\n\tresult := p.coeffs[0].Add(p.coeffs[1].Mul(x))\n\tx_pow := x.Copy()\n\tfor i := 2; i < len(p.coeffs); i++ {\n\t\tx_pow = x_pow.Mul(x)\n\t\tresult = result.Add(p.coeffs[i].Mul(x_pow))\n\t}\n\treturn result\n}", "func PolyRational64(num []int64, den []uint64, t []TermT) TermT {\n\tcount := C.uint32_t(len(num))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_rational64(count, (*C.int64_t)(&num[0]), (*C.uint64_t)(&den[0]), (*C.term_t)(&t[0])))\n}", "func (ooc *MockOpenoltClient) GetPonRxPower(ctx context.Context, in *openolt.Onu, opts ...grpc.CallOption) (*openolt.PonRxPowerData, error) {\n\treturn &openolt.PonRxPowerData{}, nil\n}", "func linearRegression(samples []FPoint, interceptTime int64) (slope, intercept float64) {\n\tvar (\n\t\tn float64\n\t\tsumX, cX float64\n\t\tsumY, cY float64\n\t\tsumXY, cXY float64\n\t\tsumX2, cX2 float64\n\t\tinitY float64\n\t\tconstY bool\n\t)\n\tinitY = samples[0].F\n\tconstY = true\n\tfor i, sample := range samples {\n\t\t// Set constY to false if any new y values are encountered.\n\t\tif constY && i > 0 && sample.F != initY {\n\t\t\tconstY = false\n\t\t}\n\t\tn += 1.0\n\t\tx := float64(sample.T-interceptTime) / 1e3\n\t\tsumX, cX = kahanSumInc(x, sumX, cX)\n\t\tsumY, cY = kahanSumInc(sample.F, sumY, cY)\n\t\tsumXY, cXY = kahanSumInc(x*sample.F, sumXY, cXY)\n\t\tsumX2, cX2 = kahanSumInc(x*x, sumX2, cX2)\n\t}\n\tif constY {\n\t\tif math.IsInf(initY, 0) {\n\t\t\treturn math.NaN(), math.NaN()\n\t\t}\n\t\treturn 0, initY\n\t}\n\tsumX += cX\n\tsumY += cY\n\tsumXY += cXY\n\tsumX2 += cX2\n\n\tcovXY := sumXY - sumX*sumY/n\n\tvarX := sumX2 - sumX*sumX/n\n\n\tslope = covXY / varX\n\tintercept = sumY/n - slope*sumX/n\n\treturn slope, intercept\n}", "func SetRandomPolynomial(dst *poly.Poly, degree int) {\n\t// Make all memory available to be accessed.\n\t*dst = (*dst)[:cap(*dst)]\n\n\t// Fill entire memory with random values, as even memory locations\n\t// beyond the degree can contain non zero values in practice.\n\tfor i := range *dst {\n\t\t(*dst)[i] = secp256k1.RandomFn()\n\t}\n\n\t// Ensure that the leading term is non-zero.\n\tfor dst.Coefficient(degree).IsZero() {\n\t\t(*dst)[degree] = secp256k1.RandomFn()\n\t}\n\n\t// Set degree.\n\t*dst = (*dst)[:degree+1]\n}", "func (p *Perlin) Noise1D(x float64) float64 {\n\t// Todo: rewrite Noise3D to 1D (lesser calculations -> faster)\n\treturn p.Noise3D(x, 0, 0)\n}", "func dividePolynomial(nn []float64 , dd []float64) (q, r []float64, ok bool) {\n \n if degree(dd) < 0 {\n return\n }\n\n nnfloat := append(r, nn...)\n \n if degree(nnfloat) >= degree(dd) {\n\n q = make([]float64, degree(nnfloat)-degree(dd)+1)\n\n for degree(nnfloat) >= degree(dd) {\n d := make([]float64, degree(nnfloat)+1)\n copy(d[degree(nnfloat)-degree(dd):], dd)\n q[degree(nnfloat)-degree(dd)] = nnfloat[degree(nnfloat)] / d[degree(d)]\n for i := range d {\n d[i] *= q[degree(nnfloat)-degree(dd)]\n nnfloat[i] -= d[i]\n }\n }\n }\n\n return q, nnfloat, true\n\n}", "func (c *Context) PCMPISTRI(i, mx, x operand.Op) {\n\tc.addinstruction(x86.PCMPISTRI(i, mx, x))\n}", "func hornerPolyEval(poly []*big.Int, x *big.Int) *big.Int {\n\tresult := big.NewInt(0)\n\tresult.Add(result, poly[0])\n\tfor i := 1; i < len(poly); i++ {\n\t\tresult = result.Mul(result, x).Add(result, poly[i])\n\t}\n\treturn result.Mod(result, baseN)\n}", "func XORPS(mx, x operand.Op) { ctx.XORPS(mx, x) }", "func (t Wald) Power(s Sample) float64 {\n\testimate := s.Estimator()\n\tstdError := StandardError(s)\n\tz := t.z()\n\tx := (t.NullValue - estimate) / stdError\n\treturn 1 - stdNormal.Cdf(x+z) + stdNormal.Cdf(x-z)\n}", "func (p Poly64) Minus(q Poly64) Poly64 {\n\treturn p ^ q\n}", "func (z *polyGF2) MulX(a *polyGF2, n int) *polyGF2 {\n\tif n < 0 {\n\t\tpanic(\"power must be >= 0\")\n\t}\n\tz.coeff.Lsh(&a.coeff, uint(n))\n\treturn z\n}", "func VPCMPISTRI(i, mx, x operand.Op) { ctx.VPCMPISTRI(i, mx, x) }", "func p256Sqr(res, in []uint64, n int)", "func ZPIY(inp string) (string, []byte) {\n\tif match := Submatch(inp, `^\\((.+)\\),y$`); match != nil {\n\t\tif _, value := ZP(match[1]); value != nil {\n\t\t\treturn lang.ZPIY, value\n\t\t}\n\t}\n\treturn \"\", nil\n}", "func newPowGen(e float64) func() float64 {\n\tvar i float64\n\treturn func() (r float64) {\n\t\tr = math.Pow(i, e)\n\t\ti++\n\t\treturn\n\t}\n}", "func (dw *DrawingWand) Polyline(coordinates []PointInfo) {\n\tccoordinates := [1 << 16]C.PointInfo{}\n\tfor k, v := range coordinates {\n\t\tccoordinates[k] = C.PointInfo{C.double(v.X), C.double(v.Y)}\n\t}\n\tC.MagickDrawPolyline(dw.dw, C.ulong(len(coordinates)), (*C.PointInfo)(&ccoordinates[0]))\n}", "func (parser *Parser) pow() (*SubExpr, error) {\n\tparser.trace(\"POW\")\n\tdefer parser.untrace()\n\n\tnot_expr, err := parser.not_expr()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpow_op, op, err := parser.pow_op()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pow_op == nil {\n\t\treturn not_expr, nil\n\t}\n\n\treturn NewExprSubExpr(NewExpr(op, not_expr, pow_op)), nil\n}", "func (p *Poly) reduce() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = barretReduce(p[i])\n\t}\n}", "func sub(a, b Poly) Poly {\n\tvar c Poly\n\tfor i := 0; i < n; i++ {\n\t\tc[i] = a[i] - b[i]\n\t}\n\treturn c\n}", "func PCMPEQW(mx, x operand.Op) { ctx.PCMPEQW(mx, x) }", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func polynomialPollardsRho(x1, x2, c *nt.Integer) *nt.Integer {\n\ttwo := nt.FromInt64(2)\n\tz := new(nt.Integer).Exp(x1, two, x2) // x1^2 mod x2\n\tz.Add(z, c) // (x1^2 mod x2) + 1\n\tz.Mod(z, x2) // (x1^2 + 1) mod x2\n\treturn z\n}", "func Poly(p *sdf.Polygon, path string) error {\n\n\tvlist := p.Vertices()\n\tif vlist == nil {\n\t\treturn errors.New(\"no vertices\")\n\t}\n\n\tfmt.Printf(\"rendering %s\\n\", path)\n\td := NewDXF(path)\n\n\tfor i := 0; i < len(vlist)-1; i++ {\n\t\tp0 := vlist[i]\n\t\tp1 := vlist[i+1]\n\t\td.Line(p0, p1)\n\t}\n\n\tif p.Closed() {\n\t\tp0 := vlist[len(vlist)-1]\n\t\tp1 := vlist[0]\n\t\tif !p0.Equals(p1, tolerance) {\n\t\t\td.Line(p0, p1)\n\t\t}\n\t}\n\n\treturn d.Save()\n}", "func (z *polyGF2) Mul(a, b *polyGF2) *polyGF2 {\n\tvar out *polyGF2\n\tif z != a && z != b {\n\t\tout = z\n\t} else {\n\t\tout = &polyGF2{}\n\t}\n\n\tdx := a.Degree()\n\tvar bs big.Int\n\tfor i := 0; i <= dx; i++ {\n\t\tif a.coeff.Bit(i) != 0 {\n\t\t\tbs.Lsh(&b.coeff, uint(i))\n\t\t\tout.coeff.Xor(&out.coeff, &bs)\n\t\t}\n\t}\n\n\tif z != out {\n\t\tz.coeff.Set(&out.coeff)\n\t}\n\treturn z\n}", "func (s *CubicSplineSDF2) Polygonize(n int) *Polygon {\n\tp := NewPolygon()\n\tdt := float64(len(s.spline)) / float64(n-1)\n\tt := 0.0\n\tfor i := 0; i < n; i++ {\n\t\tp.AddV2(s.f0(t))\n\t\tt += dt\n\t}\n\treturn p\n}", "func ExtractGlimpseNoise(value string) ExtractGlimpseAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"noise\"] = value\n\t}\n}", "func (p *Perlin) Noise2D(x, y float64) float64 {\n\t// Todo: rewrite Noise3D to 2D (lesser calculations -> faster)\n\treturn p.Noise3D(x, y, 0)\n}", "func linearMap() {\n\tdt := 1.0\n\talpha := 0.01\n\tn := 1000\n\tN := make([]float64, n)\n\n\tN[0] = 0.0001\n\n\tfor i := 1; i < n; i++ {\n\t\tN[i] = N[i-1] * (1 + alpha*dt)\n\t}\n\n\twrite(N)\n}", "func (p Poly) Generate(_ *rand.Rand, size int) reflect.Value {\n\tpoly := make(Poly, size)\n\tfor i := range poly {\n\t\tpoly[i] = secp256k1.RandomFn()\n\t}\n\treturn reflect.ValueOf(poly)\n}", "func EXTRACTPS(i, x, mr operand.Op) { ctx.EXTRACTPS(i, x, mr) }", "func PCMPEQQ(mx, x operand.Op) { ctx.PCMPEQQ(mx, x) }", "func Power(items []int) functional.Stream {\n len := len(items)\n if len == 0 {\n return functional.Slice(ess, 0, 1)\n }\n return functional.Concat(\n Power(items[:len-1]),\n functional.Deferred(func() functional.Stream {\n return functional.Filter(\n appendFilterer(items[len-1]),\n Power(items[:len-1]))\n }))\n}", "func (phi *isogeny3) GenerateCurve(p *ProjectivePoint) CurveCoefficientsEquiv {\n\tvar t0, t1, t2, t3, t4 Fp2Element\n\tvar coefEq CurveCoefficientsEquiv\n\tvar K1, K2 = &phi.K1, &phi.K2\n\n\top := phi.Field\n\top.Sub(K1, &p.X, &p.Z) // K1 = XP3 - ZP3\n\top.Square(&t0, K1) // t0 = K1^2\n\top.Add(K2, &p.X, &p.Z) // K2 = XP3 + ZP3\n\top.Square(&t1, K2) // t1 = K2^2\n\top.Add(&t2, &t0, &t1) // t2 = t0 + t1\n\top.Add(&t3, K1, K2) // t3 = K1 + K2\n\top.Square(&t3, &t3) // t3 = t3^2\n\top.Sub(&t3, &t3, &t2) // t3 = t3 - t2\n\top.Add(&t2, &t1, &t3) // t2 = t1 + t3\n\top.Add(&t3, &t3, &t0) // t3 = t3 + t0\n\top.Add(&t4, &t3, &t0) // t4 = t3 + t0\n\top.Add(&t4, &t4, &t4) // t4 = t4 + t4\n\top.Add(&t4, &t1, &t4) // t4 = t1 + t4\n\top.Mul(&coefEq.C, &t2, &t4) // A24m = t2 * t4\n\top.Add(&t4, &t1, &t2) // t4 = t1 + t2\n\top.Add(&t4, &t4, &t4) // t4 = t4 + t4\n\top.Add(&t4, &t0, &t4) // t4 = t0 + t4\n\top.Mul(&t4, &t3, &t4) // t4 = t3 * t4\n\top.Sub(&t0, &t4, &coefEq.C) // t0 = t4 - A24m\n\top.Add(&coefEq.A, &coefEq.C, &t0) // A24p = A24m + t0\n\treturn coefEq\n}", "func Sqr(z, x *Elt)", "func (w *wire) interceptPoints(o wire) []point {\n\tvar interceptPoints []point\n\tfor i := 1; i < len(w.points); i++ {\n\t\tv1 := segment{\n\t\t\tfrom: w.points[i-1],\n\t\t\tto: w.points[i],\n\t\t}\n\t\tfor u := 1; u < len(o.points); u++ {\n\t\t\tv2 := segment{\n\t\t\t\tfrom: o.points[u-1],\n\t\t\t\tto: o.points[u],\n\t\t\t}\n\t\t\tintercept := v1.intercepts(v2)\n\t\t\tif intercept.x != 0 && intercept.y != 0 {\n\t\t\t\t// Calculate total wire length (both wires combined)\n\t\t\t\tintercept.wireLen = v1.from.wireLen + intercept.distanceToPoint(v1.from) +\n\t\t\t\t\tv2.from.wireLen + intercept.distanceToPoint(v2.from)\n\t\t\t\tinterceptPoints = append(interceptPoints, intercept)\n\t\t\t}\n\t\t}\n\t}\n\treturn interceptPoints\n}", "func PolyMpq(q []MpqT, t []TermT) TermT {\n\tcount := C.uint32_t(len(q))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpqp(count, (*C.mpq_t)(&q[0]), (*C.term_t)(&t[0])))\n}", "func p256Sqr(res, in []uint64)", "func (n *Noise) Call() *Noise {\n\treturn n\n}", "func lagrangeInterpolate(points map[int]*big.Int, x int, curve elliptic.Curve) *big.Int {\n\tlog.Printf(\"The points is: %v\", points)\n\n\t// 通过这些坐标点来恢复出多项式\n\tpolynomialClient := polynomial.New(curve.Params().N)\n\tresult := polynomialClient.GetPolynomialByPoints(points)\n\n\t// 秘密就是常数项\n\tsecret := result[len(result)-1]\n\n\tlog.Printf(\"The coefficients of the polynomial is: %v\", result)\n\treturn secret\n}", "func PeelTwist() model2d.Curve {\n\treturn model2d.JoinedCurve{\n\t\tmodel2d.BezierCurve{\n\t\t\tmodel2d.XY(-1.0, 0.0),\n\t\t\tmodel2d.XY(-0.2, 0.0),\n\t\t},\n\t\tmodel2d.BezierCurve{\n\t\t\tmodel2d.XY(-0.2, 0.0),\n\t\t\tmodel2d.XY(-0.05, 0.0),\n\t\t\tmodel2d.XY(0.05, math.Pi),\n\t\t\tmodel2d.XY(0.2, math.Pi),\n\t\t},\n\t\tmodel2d.BezierCurve{\n\t\t\tmodel2d.XY(0.2, math.Pi),\n\t\t\tmodel2d.XY(1.0, math.Pi),\n\t\t},\n\t}\n}", "func New(seed int64, size int) *NoiseTable {\n\tr := rand.New(rand.NewSource(seed))\n\ttable := make([]float64, size)\n\tfor i := 0; i < size; i++ {\n\t\ttable[i] = r.NormFloat64()\n\t}\n\treturn &NoiseTable{\n\t\tnoise: anyvec64.MakeVectorData(anyvec64.MakeNumericList(table)),\n\t}\n}", "func pow(x, n int8) int8 {\n\tif n == 0 {\n\t\treturn 1\n\t} else {\n\t\treturn x * pow(x, n-1)\n\t}\n}", "func (p Poly64) Plus(q Poly64) Poly64 {\n\treturn p ^ q\n}", "func VPCMPESTRI(i, mx, x operand.Op) { ctx.VPCMPESTRI(i, mx, x) }", "func (poly *PolynomialFeatures) InverseTransform(X, Y *mat.Dense) (Xout, Yout *mat.Dense) {\n\tif X == nil {\n\t\treturn X, Y\n\t}\n\ttype jt struct{ jorig, jpoly int }\n\tvar jts []jt\n\tnSamples, _ := X.Dims()\n\tXoutCols := 0\n\n\tintsum := func(a []int) int {\n\t\tvar s int\n\t\tfor _, v := range a {\n\t\t\ts += v\n\t\t}\n\t\treturn s\n\t}\n\tintmaxidx := func(a []int) int {\n\t\ti := 0\n\t\tfor j, v := range a {\n\t\t\tif v > a[i] {\n\t\t\t\ti = j\n\t\t\t}\n\t\t}\n\t\treturn i\n\t}\n\tfor ioutput, p := range poly.Powers {\n\t\tvar jMax = intmaxidx(p)\n\t\tvar sumpj = intsum(p)\n\t\tif sumpj == 1 {\n\t\t\t//fmt.Println(ioutput, \"p\", p, \"sumpj\", sumpj, \"jWith1\", jMax)\n\t\t\tjts = append(jts, jt{jMax, ioutput})\n\t\t\tif jMax >= XoutCols {\n\t\t\t\tXoutCols = jMax + 1\n\t\t\t}\n\t\t}\n\t}\n\tXout = mat.NewDense(nSamples, XoutCols, nil)\n\n\tfor _, pair := range jts {\n\t\t//fmt.Println(jts)\n\t\tfor i := 0; i < nSamples; i++ {\n\t\t\tXout.Set(i, pair.jorig, X.At(i, pair.jpoly))\n\t\t}\n\t}\n\treturn\n}", "func (poly *PolynomialFeatures) Fit(Xmatrix, Ymatrix mat.Matrix) base.Fiter {\n\tX := base.ToDense(Xmatrix)\n\t_, nFeatures := X.Dims()\n\tpoly.Powers = make([][]int, 0)\n\tcomb := combinationsWithReplacement\n\tif poly.InteractionOnly {\n\t\tcomb = combinations\n\t}\n\tstart := 0\n\tif !poly.IncludeBias {\n\t\tstart = 1\n\t}\n\tfor i := start; i <= poly.Degree; i++ {\n\t\tfor c := range comb(intrange(nFeatures), i) {\n\t\t\tpoly.Powers = append(poly.Powers, bincount(c, nFeatures))\n\t\t}\n\t}\n\treturn poly\n}", "func (self *State)Pow(a,b any)any{\n self.IncOperations(self.coeff[\"pow\"]+self.off[\"pow\"])\n return wrap2(a,b,math.Pow)\n}", "func PauliY() *Gate {\n\treturn newOneQubitGate([4]complex128{\n\t\t0, complex(0, -1),\n\t\tcomplex(0, 1), 0})\n}", "func poisson(q model.Quadrilateral, r float64) []model.Vector {\n\tx0, y0 := float64(q.P1.X), float64(q.P1.Y)\n\tx1, y1 := float64(q.P3.X), float64(q.P3.Y)\n\tk := 30\n\tpoints := poissondisc.Sample(x0, y0, x1, y1, r, k, nil)\n\tvectors := make([]model.Vector, len(points))\n\tfor i, p := range points {\n\t\tvectors[i] = model.Vector{float32(p.X), float32(p.Y), 0.0}\n\t}\n\treturn vectors\n}" ]
[ "0.5449011", "0.53609854", "0.532913", "0.5157759", "0.49809927", "0.4944963", "0.48186973", "0.47992346", "0.4718558", "0.46882093", "0.46483457", "0.464402", "0.4627494", "0.46132982", "0.46044943", "0.459655", "0.45211676", "0.4510853", "0.44707513", "0.44705918", "0.44443122", "0.443178", "0.4412737", "0.44083345", "0.4391546", "0.43856534", "0.43517977", "0.432165", "0.43017533", "0.43006983", "0.4258863", "0.42484626", "0.42432424", "0.42304027", "0.42245448", "0.42041913", "0.42024678", "0.42014605", "0.4199055", "0.41844752", "0.418377", "0.41733673", "0.4172127", "0.41586658", "0.4155279", "0.41535392", "0.409806", "0.40963134", "0.4078926", "0.40742597", "0.406097", "0.40597835", "0.4056919", "0.40385172", "0.4028976", "0.40239394", "0.40206316", "0.4015558", "0.40121883", "0.40103176", "0.40080968", "0.40039787", "0.399992", "0.3998268", "0.39915016", "0.39652935", "0.3964977", "0.3960425", "0.39570633", "0.3955844", "0.39425695", "0.39376795", "0.39297184", "0.39274406", "0.3925907", "0.39245653", "0.39212933", "0.3918652", "0.39067626", "0.39048427", "0.38929176", "0.38810882", "0.38732874", "0.3867926", "0.38658226", "0.38551855", "0.38529465", "0.3850904", "0.38497466", "0.3847187", "0.384158", "0.38246298", "0.380094", "0.37980643", "0.3798015", "0.3795946", "0.37928846", "0.37926486", "0.37911656", "0.3789291" ]
0.7775223
0
polyCBD2 samples a poly using a centered binomial distribution
func polyCBD2(outbuf []byte) Poly { var t, d uint32 var a, b int16 var p Poly for i := 0; i < n/8; i++ { t = load32LE(outbuf[4*i:]) d = t & 0x55555555 d += (t >> 1) & 0x55555555 for j := 0; j < 8; j++ { a = int16((d >> (4*j + 0)) & 0x3) b = int16((d >> (4*j + 2)) & 0x3) p[8*i+j] = a - b } } return p }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func (z *Int) Binomial(n, k int64) *Int {}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func newPolyGF2(coeffs uint64) *polyGF2 {\n\tvar p polyGF2\n\tp.coeff.SetUint64(coeffs)\n\treturn &p\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func polyGetNoise(eta int, seed []byte, nonce byte) Poly {\n\toutbuf := make([]byte, eta*n/4)\n\tstate := sha3.NewShake256()\n\tstate.Write(seed[:])\n\tstate.Write([]byte{nonce})\n\tstate.Read(outbuf[:])\n\tvar p Poly\n\tif eta == 3 {\n\t\tp = polyCBD3(outbuf)\n\t}\n\tif eta == 2 {\n\t\tp = polyCBD2(outbuf)\n\t}\n\treturn p\n}", "func binomCoeff(n, k float64) float64 {\n\treturn fact(n) / (fact(k) * fact(n-k))\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func ConfBinomial(a int64, b int64) int {\n\tif b > a {\n\t\tfmt.Printf(\"\\033[31mX\\033[0m Error: the second number : %v is greater than %v\\n\", b, a)\n\t\treturn 84\n\t}\n\tres := new(big.Int)\n\tfmt.Printf(\"%v-combination of a set of size %v:\\n%v\\n\", uint64(b), uint64(a), res.Binomial(a, b))\n\treturn 0\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func wbbKeyGen(curve *math.Curve, rng io.Reader) (*math.Zr, *math.G2) {\n\t// sample sk uniform from Zq\n\tsk := curve.NewRandomZr(rng)\n\t// set pk = g2^sk\n\tpk := curve.GenG2.Mul(sk)\n\treturn sk, pk\n}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func RandomPolynomial(r io.Reader, degree uint64) (*Polynomial, error) {\n\tcoefficients := []*big.Int{}\n\tfor i := uint64(0); i < degree+1; i++ {\n\t\tc, err := rand.Int(r, bn256.Order)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tcoefficients = append(coefficients, c)\n\t}\n\treturn NewPolynomial(coefficients)\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func NewPolynomialGenerator(b, step float64, a ...float64) *Euclidean {\n\tx := []float64{b}\n\tx = append(x, a...)\n\treturn &Euclidean{\n\t\tNewLinearSequence(0, step),\n\t\tF{f: []Y{\n\t\t\t// x coordinate :\n\t\t\tfunc(x ...float64) float64 {\n\t\t\t\treturn x[0]\n\t\t\t},\n\t\t\t// y coordinate\n\t\t\tpolynomialFunction(x...),\n\t\t}}}\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func boxToPoly(b Box2d) polygon {\n\tcen_x, cen_y := b.Position()\n\twidth, height := b.Size()\n\tangle := b.AngleDegrees()\n\n\tpoints := [4]point{}\n\n\tpoints[0] = point{X: getX(-width/2, -height/2, angle) + cen_x,\n\t\tY: getY(-width/2, -height/2, angle) + cen_y}\n\n\tpoints[1] = point{X: getX(width/2, -height/2, angle) + cen_x,\n\t\tY: getY(width/2, -height/2, angle) + cen_y}\n\n\tpoints[2] = point{X: getX(-width/2, height/2, angle) + cen_x,\n\t\tY: getY(-width/2, height/2, angle) + cen_y}\n\n\tpoints[3] = point{X: getX(width/2, height/2, angle) + cen_x,\n\t\tY: getY(width/2, height/2, angle) + cen_y}\n\tz := boxPoly{points: points[:4]}\n\n\treturn z\n}", "func IntBinomial(z *big.Int, n, k int64) *big.Int", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func NegativeBinomialCDF(ρ float64, r int64) func(k int64) float64 {\n\treturn func(k int64) float64 {\n\t\tIP := BetaCDFAt(float64(k+1), float64(r), ρ)\n\t\treturn 1 - IP\n\t}\n}", "func BinomialDist(nb float64) int {\n\tfmt.Printf(\"Binomial distribution:\\n\")\n\tstart := time.Now()\n\t//\n\toverload := new(big.Float)\n\toverload.SetFloat64(1)\n\thundred := new(big.Float).SetFloat64(100)\n\tp := float64(nb / (8 * 60 * 60))\n\n\tfor k := float64(0); k != 51; k++ {\n\t\tfmt.Printf(\"%.0f -> %.3f\", k, BinomialAlgo(k, p))\n\n\t\tif (int(k+1) % 5) == 0 {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t} else if k != 50 {\n\t\t\tfmt.Printf(\"\\t\")\n\t\t}\n\t\tif k <= 25 {\n\t\t\toverload.Sub(overload, BinomialAlgo(k, p))\n\t\t}\n\t}\n\t//\n\tduration := time.Since(start)\n\tfmt.Printf(\"\\nOverload: %.1f%%\", overload.Mul(overload, hundred))\n\tfmt.Printf(\"\\nComputation time: %.2f ms\\n\\n\",\n\t\tfloat64(duration.Nanoseconds())/1000000)\n\treturn 0\n}", "func (s *CubicSplineSDF2) PolySpline2D(n int) (SDF2, error) {\n\tp := s.Polygonize(n)\n\treturn Polygon2D(p.Vertices())\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func NewCyclicPoly(n int) *CyclicPoly {\n\tif n < 1 {\n\t\tpanic(\"argument n must be positive\")\n\t}\n\treturn &CyclicPoly{p: make([]uint64, 0, n)}\n}", "func (c *curve) init(self kyber.Group, p *Param, fullGroup bool,\n\tnull, base point) *curve {\n\tc.self = self\n\tc.Param = *p\n\tc.full = fullGroup\n\tc.null = null\n\n\t// Edwards curve parameters as ModInts for convenience\n\tc.a.Init(&p.A, &p.P)\n\tc.d.Init(&p.D, &p.P)\n\n\t// Cofactor\n\tc.cofact.Init64(int64(p.R), &c.P)\n\n\t// Determine the modulus for scalars on this curve.\n\t// Note that we do NOT initialize c.order with Init(),\n\t// as that would normalize to the modulus, resulting in zero.\n\t// Just to be sure it's never used, we leave c.order.M set to nil.\n\t// We want it to be in a ModInt so we can pass it to P.Mul(),\n\t// but the scalar's modulus isn't needed for point multiplication.\n\tif fullGroup {\n\t\t// Scalar modulus is prime-order times the ccofactor\n\t\tc.order.V.SetInt64(int64(p.R)).Mul(&c.order.V, &p.Q)\n\t} else {\n\t\tc.order.V.Set(&p.Q) // Prime-order subgroup\n\t}\n\n\t// Useful ModInt constants for this curve\n\tc.zero.Init64(0, &c.P)\n\tc.one.Init64(1, &c.P)\n\n\t// Identity element is (0,1)\n\tnull.initXY(zero, one, self)\n\n\t// Base point B\n\tvar bx, by *big.Int\n\tif !fullGroup {\n\t\tbx, by = &p.PBX, &p.PBY\n\t} else {\n\t\tbx, by = &p.FBX, &p.FBY\n\t\tbase.initXY(&p.FBX, &p.FBY, self)\n\t}\n\tif by.Sign() == 0 {\n\t\t// No standard base point was defined, so pick one.\n\t\t// Find the lowest-numbered y-coordinate that works.\n\t\t//println(\"Picking base point:\")\n\t\tvar x, y mod.Int\n\t\tfor y.Init64(2, &c.P); ; y.Add(&y, &c.one) {\n\t\t\tif !c.solveForX(&x, &y) {\n\t\t\t\tcontinue // try another y\n\t\t\t}\n\t\t\tif c.coordSign(&x) != 0 {\n\t\t\t\tx.Neg(&x) // try positive x first\n\t\t\t}\n\t\t\tbase.initXY(&x.V, &y.V, self)\n\t\t\tif c.validPoint(base) {\n\t\t\t\tbreak // got one\n\t\t\t}\n\t\t\tx.Neg(&x) // try -bx\n\t\t\tif c.validPoint(base) {\n\t\t\t\tbreak // got one\n\t\t\t}\n\t\t}\n\t\t//println(\"BX: \"+x.V.String())\n\t\t//println(\"BY: \"+y.V.String())\n\t\tbx, by = &x.V, &y.V\n\t}\n\tbase.initXY(bx, by, self)\n\n\t// Uniform representation encoding methods,\n\t// only useful when using the full group.\n\t// (Points taken from the subgroup would be trivially recognizable.)\n\tif fullGroup {\n\t\tif p.Elligator1s.Sign() != 0 {\n\t\t\tc.hide = new(el1param).init(c, &p.Elligator1s)\n\t\t} else if p.Elligator2u.Sign() != 0 {\n\t\t\tc.hide = new(el2param).init(c, &p.Elligator2u)\n\t\t}\n\t}\n\n\t// Sanity checks\n\tif !c.validPoint(null) {\n\t\tpanic(\"invalid identity point \" + null.String())\n\t}\n\tif !c.validPoint(base) {\n\t\tpanic(\"invalid base point \" + base.String())\n\t}\n\n\treturn c\n}", "func binomial(n, x int) float64 {\n\ti, f := new(big.Int), new(big.Float)\n\tbinom, _ := f.SetInt(i.Binomial(int64(n), int64(x))).Float64()\n\treturn binom\n}", "func (z *polyGF2) Mul(a, b *polyGF2) *polyGF2 {\n\tvar out *polyGF2\n\tif z != a && z != b {\n\t\tout = z\n\t} else {\n\t\tout = &polyGF2{}\n\t}\n\n\tdx := a.Degree()\n\tvar bs big.Int\n\tfor i := 0; i <= dx; i++ {\n\t\tif a.coeff.Bit(i) != 0 {\n\t\t\tbs.Lsh(&b.coeff, uint(i))\n\t\t\tout.coeff.Xor(&out.coeff, &bs)\n\t\t}\n\t}\n\n\tif z != out {\n\t\tz.coeff.Set(&out.coeff)\n\t}\n\treturn z\n}", "func BinDist(prob float64, n int, k1 int, k2 int) float64 {\n\tsum := 0.0\n\tfor k := k1; k <= k2; k++ {\n\t\tsum += BinProb(prob, n, k)\n\t}\n\treturn sum\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func (b Binomial) Rand() float64 {\n\t// NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)\n\t// p. 295-6\n\t// http://www.aip.de/groups/soe/local/numres/bookcpdf/c7-3.pdf\n\n\trunif := rand.Float64\n\trexp := rand.ExpFloat64\n\tif b.Src != nil {\n\t\trnd := rand.New(b.Src)\n\t\trunif = rnd.Float64\n\t\trexp = rnd.ExpFloat64\n\t}\n\n\tp := b.P\n\tif p > 0.5 {\n\t\tp = 1 - p\n\t}\n\tam := b.N * p\n\n\tif b.N < 25 {\n\t\t// Use direct method.\n\t\tbnl := 0.0\n\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\tif runif() < p {\n\t\t\t\tbnl++\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\n\tif am < 1 {\n\t\t// Use rejection method with Poisson proposal.\n\t\tconst logM = 2.6e-2 // constant for rejection sampling (https://en.wikipedia.org/wiki/Rejection_sampling)\n\t\tvar bnl float64\n\t\tz := -p\n\t\tpclog := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z) // Padé approximant of log(1 + x)\n\t\tfor {\n\t\t\tbnl = 0.0\n\t\t\tt := 0.0\n\t\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\t\tt += rexp()\n\t\t\t\tif t >= am {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tbnl++\n\t\t\t}\n\t\t\tbnlc := b.N - bnl\n\t\t\tz = -bnl / b.N\n\t\t\tlog1p := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z)\n\t\t\tt = (bnlc+0.5)*log1p + bnl - bnlc*pclog + 1/(12*bnlc) - am + logM // Uses Stirling's expansion of log(n!)\n\t\t\tif rexp() >= t {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\t// Original algorithm samples from a Poisson distribution with the\n\t// appropriate expected value. However, the Poisson approximation is\n\t// asymptotic such that the absolute deviation in probability is O(1/n).\n\t// Rejection sampling produces exact variates with at worst less than 3%\n\t// rejection with minimal additional computation.\n\n\t// Use rejection method with Cauchy proposal.\n\tg, _ := math.Lgamma(b.N + 1)\n\tplog := math.Log(p)\n\tpclog := math.Log1p(-p)\n\tsq := math.Sqrt(2 * am * (1 - p))\n\tfor {\n\t\tvar em, y float64\n\t\tfor {\n\t\t\ty = math.Tan(math.Pi * runif())\n\t\t\tem = sq*y + am\n\t\t\tif em >= 0 && em < b.N+1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tem = math.Floor(em)\n\t\tlg1, _ := math.Lgamma(em + 1)\n\t\tlg2, _ := math.Lgamma(b.N - em + 1)\n\t\tt := 1.2 * sq * (1 + y*y) * math.Exp(g-lg1-lg2+em*plog+(b.N-em)*pclog)\n\t\tif runif() <= t {\n\t\t\tif p != b.P {\n\t\t\t\treturn b.N - em\n\t\t\t}\n\t\t\treturn em\n\t\t}\n\t}\n}", "func sub(a, b Poly) Poly {\n\tvar c Poly\n\tfor i := 0; i < n; i++ {\n\t\tc[i] = a[i] - b[i]\n\t}\n\treturn c\n}", "func (ks *KZG1Settings) CommitToPoly(coeffs []gmcl.Fr) *gmcl.G1 {\n\tvar out gmcl.G1\n\tgmcl.G1MulVec(&out, ks.PK[:len(coeffs)], coeffs)\n\treturn &out\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func (s *CubicSplineSDF2) Polygonize(n int) *Polygon {\n\tp := NewPolygon()\n\tdt := float64(len(s.spline)) / float64(n-1)\n\tt := 0.0\n\tfor i := 0; i < n; i++ {\n\t\tp.AddV2(s.f0(t))\n\t\tt += dt\n\t}\n\treturn p\n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func binomdist(x, n, p float64) float64 {\n\treturn binomCoeff(n, x) * math.Pow(p, x) * math.Pow(1-p, n-x)\n}", "func Keygen(pub *BswabePub,msk *BswabeMsk, attrs []string) *BswabePrv {\n\t//attrs := strings.Split(attr, \" \")\n\n\tprv := new(BswabePrv)\n\tvar g_r, r, beta_inv *pbc.Element\n\tvar pairing *pbc.Pairing\n\n\t/* initialize */\n\tpairing = pub.p\n\tprv.d = pairing.NewG2()\n\tg_r = pairing.NewG2()\n\tr = pairing.NewZr()\n\tbeta_inv = pairing.NewZr()\n\n\t/* compute */\n\tr.Rand()\n\tprv.r = r.NewFieldElement().Set(r)\n\tg_r = pub.gp.NewFieldElement().Set(pub.gp)\n\t//g_r = pub.g.NewFieldElement().Set(pub.g)\n\tg_r.PowZn(g_r, r)\n\n\tprv.d = msk.g_alpha.NewFieldElement().Set(msk.g_alpha)\n\tprv.d.Mul(prv.d, g_r)\n\tbeta_inv = msk.beta.NewFieldElement().Set(msk.beta)\n\tbeta_inv.Invert(beta_inv)\n\tprv.d.PowZn(prv.d, beta_inv)\n\n\tlen := len(attrs)\n\tfor i := 0; i < len; i++ {\n\t\tcomp := new(BswabePrvComp)\n\t\tvar h_rp, rp *pbc.Element\n\n\t\tcomp.attr = attrs[i]\n\t\tcomp.d = pairing.NewG2()\n\t\tcomp.dp = pairing.NewG1()\n\t\th_rp = pairing.NewG2()\n\t\trp = pairing.NewZr()\n\n\t\telementFromString(h_rp, comp.attr)\n\t\trp.Rand()\n\n\t\th_rp.PowZn(h_rp, rp)\n\n\t\tcomp.d = g_r.NewFieldElement().Set(g_r)\n\t\tcomp.d.Mul(comp.d, h_rp)\n\t\tcomp.dp = pub.g.NewFieldElement().Set(pub.g)\n\t\tcomp.dp.PowZn(comp.dp, rp)\n\n\t\tprv.comps = append(prv.comps, comp)\n\t}\n\treturn prv\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func newBSpline(n int, t, y []Num) *BSpline {\r\n\ts := new(BSpline)\r\n\ts.a = make([]Num, n+1)\r\n\ts.h = make([]Num, n+1)\r\n\ts.a, s.h = coef(n, t, y)\r\n\r\n\treturn s\r\n}", "func KUNPCKBW(k, k1, k2 operand.Op) { ctx.KUNPCKBW(k, k1, k2) }", "func (fn *formulaFuncs) besselY2(x, n formulaArg) float64 {\n\ttox, bym, by, byp := 2/x.Number, fn.besselY0(x), fn.besselY1(x), 0.0\n\tfor i := 1.0; i < n.Number; i++ {\n\t\tbyp = i*tox*by - bym\n\t\tbym = by\n\t\tby = byp\n\t}\n\treturn by\n}", "func Binomial(n, k int64) *big.Int {\n\treturn new(big.Int).Binomial(n, k)\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func KXORB(k, k1, k2 operand.Op) { ctx.KXORB(k, k1, k2) }", "func makeRenderablePoly(name string, n int, drawType uint, color vec4) *Renderable {\n\t// build poly verts\n\tvertex := makePoly(n)\n\tr := &Renderable{\n\t\tworld.Transform(),\n\t\tworld.Operation(name, &world.Poly{Points: vertex}),\n\t\tworld.MaterialComponent{\n\t\t\tDrawType: drawType,\n\t\t\tProps: map[string]interface{}{\n\t\t\t\t\"color\": world.Color(color),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn r\n}", "func lookupPoly(blockSizeLength int) int {\n\tswitch (blockSizeLength * 8) {\n\tcase 64: return 0x1B;\n\tcase 128: return 0x87;\n\tcase 160: return 0x2D;\n\tcase 192: return 0x87;\n\tcase 224: return 0x309;\n\tcase 256: return 0x425;\n\tcase 320: return 0x1B;\n\tcase 384: return 0x100D;\n\tcase 448: return 0x851;\n\tcase 512: return 0x125;\n\tcase 768: return 0xA0011;\n\tcase 1024: return 0x80043;\n\tcase 2048: return 0x86001;\n }\n\treturn -1\n}", "func MakeTable(poly uint64) *Table {}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func ExampleFacettedPolygon() {\n\tf := FacettedNib{LineNib: LineNib{unitX, unitY}}\n\tPrintGraph(f.Polygon([][2]x{{0, 0}, {5 * unitX, 5 * unitX}, {5 * unitX, -5 * unitX}}...), -10*unitX, 10*unitX, -10*unitX, 10*unitX, unitX)\n\t// Output:\n\t/*\n\t\tGraph\n\t\t -10\t---------------------\n\t\t -9\t---------------------\n\t\t -8\t---------------------\n\t\t -7\t---------------------\n\t\t -6\t---------------------\n\t\t -5\t---------------X-----\n\t\t -4\t--------------XX-----\n\t\t -3\t-------------X-X-----\n\t\t -2\t------------X--X-----\n\t\t -1\t-----------X---X-----\n\t\t 0\t----------X----X-----\n\t\t 1\t-----------X---X-----\n\t\t 2\t------------X--X-----\n\t\t 3\t-------------X-X-----\n\t\t 4\t--------------XX-----\n\t\t 5\t---------------X-----\n\t\t 6\t---------------------\n\t\t 7\t---------------------\n\t\t 8\t---------------------\n\t\t 9\t---------------------\n\t\t 10\t---------------------\n\t*/\n}", "func NewBinaryChop(algo Algorithm) *BinaryChop {\n\tbinaryChop := new(BinaryChop)\n\tbinaryChop.algorithm = algo\n\treturn binaryChop\n}", "func r2(d []complex128, tw *twiddles, sc bool) {\n\tN := len(d)\n\tM := 2\n\tif !is2pow(N) {\n\t\tpanic(\"length not power of 2\")\n\t}\n\tif N == 1 {\n\t\treturn\n\t}\n\tif N == 2 {\n\t\t// problem with twiddles or something, treat explicitly.\n\t\te := d[0]\n\t\tco := d[1]\n\t\td[0] = e + co\n\t\td[1] = e - co\n\t\tif sc {\n\t\t\tscale(d)\n\t\t}\n\t\treturn\n\t}\n\trevBinPermute(d)\n\tvar q, r, a, b, H int\n\tvar c, e, co complex128\n\tfor M <= N {\n\t\tH = M / 2\n\t\tfor q = 0; q < N; q += M {\n\t\t\tfor r = 0; r < H; r++ {\n\t\t\t\ta = q + r\n\t\t\t\tb = a + H\n\t\t\t\tc = tw.cmplxQ(r, M)\n\t\t\t\te, co = d[a], d[b]*c\n\t\t\t\td[a], d[b] = e+co, e-co\n\t\t\t}\n\t\t}\n\t\tM *= 2\n\t}\n\tif sc {\n\t\tscale(d)\n\t}\n}", "func (p thinPoly) Karatsuba2(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 64)\n\tvar z = make(thinPoly, 128)\n\tf0, f1 := f[:32], f[32:]\n\tg0, g1 := g[:32], g[32:]\n\n\tt.Karatsuba3(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba3(f1, g1)\n\tz[32:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[32:].Inc(z.Mul(-1, z)[:96])\n\tt.Karatsuba3(z.Add(f0, f1), z[32:].Add(g0, g1))\n\tp[32:].Inc(t)\n\n\treturn p\n}", "func toYCbCr(m image.Image, p image.Point, yBlock, cbBlock, crBlock *block) {\n\tb := m.Bounds()\n\txmax := b.Max.X - 1\n\tymax := b.Max.Y - 1\n\tfor j := 0; j < 8; j++ {\n\t\tfor i := 0; i < 8; i++ {\n\t\t\tr, g, b, _ := m.At(min(p.X+i, xmax), min(p.Y+j, ymax)).RGBA()\n\t\t\tyy, cb, cr := color.RGBToYCbCr(uint8(r>>8), uint8(g>>8), uint8(b>>8))\n\t\t\tyBlock[8*j+i] = int32(yy)\n\t\t\tcbBlock[8*j+i] = int32(cb)\n\t\t\tcrBlock[8*j+i] = int32(cr)\n\t\t}\n\t}\n}", "func MakeTable(poly uint32) *Table {}", "func NewPolyDataMapper(nOriFeatures, iFeature, jFeature, order int) (o *PolyDataMapper) {\n\n\t// check\n\tif order < 2 {\n\t\tchk.Panic(\"PolyDataMapper is useful for order >= 2. order = %d is invalid\\n\", order)\n\t}\n\tif iFeature > nOriFeatures-1 {\n\t\tchk.Panic(\"iFeature must be within [0, %d]. iFeature = %d is invalid\\n\", nOriFeatures-1, iFeature)\n\t}\n\tif jFeature > nOriFeatures {\n\t\tchk.Panic(\"jFeature must be within [0, %d]. jFeature = %d is invalid\\n\", nOriFeatures-1, jFeature)\n\t}\n\n\t// input data\n\to = new(PolyDataMapper)\n\to.nOriFeatures = nOriFeatures\n\to.iFeature = iFeature\n\to.jFeature = jFeature\n\to.order = order\n\n\t// derived\n\tp := o.order + 1 // auxiliary\n\tnPascal := p*(p+1)/2 - 1 // -1 because first row in Pascal triangle is neglected\n\to.nExtraFeatures = nPascal - 2 // -2 because iFeature and jFeatureare were considered in nPascal already\n\treturn\n}", "func lagrangeInterpolate(points map[int]*big.Int, x int, curve elliptic.Curve) *big.Int {\n\tlog.Printf(\"The points is: %v\", points)\n\n\t// 通过这些坐标点来恢复出多项式\n\tpolynomialClient := polynomial.New(curve.Params().N)\n\tresult := polynomialClient.GetPolynomialByPoints(points)\n\n\t// 秘密就是常数项\n\tsecret := result[len(result)-1]\n\n\tlog.Printf(\"The coefficients of the polynomial is: %v\", result)\n\treturn secret\n}", "func bzPoints(L, d int) []vec.Vector {\n\tcachedL, okL := pointsCache[L]\n\tif okL {\n\t\tcachedD, okD := cachedL[d]\n\t\tif okD {\n\t\t\treturn cachedD\n\t\t}\n\t} else {\n\t\tpointsCache[L] = make(map[int][]vec.Vector)\n\t}\n\tpoints := make([]vec.Vector, pow(L, d))\n\t// start is the minumum value of any component of a point\n\tstart := -math.Pi\n\t// (finish - step) is the maximum value of any component of a point\n\tfinish := -start\n\t// step is the separation between point components\n\tstep := (finish - start) / float64(L)\n\tk := vec.ZeroVector(d)\n\tkIndex := make([]int, d)\n\t// set initial value for k\n\tfor i := 0; i < d; i++ {\n\t\tk[i] = start\n\t\tkIndex[i] = 0\n\t}\n\t// iterate over Brillouin zone\n\tdone := false\n\tfor i := 0; !done; i++ {\n\t\tpoints[i] = vec.ZeroVector(len(k))\n\t\tcopy(points[i], k)\n\t\tdone = bzAdvance(k, kIndex, start, step, L, d)\n\t}\n\tpointsCache[L][d] = points\n\treturn points\n}", "func (c *CurveOperations) Fp2FromBytes(fp2 *Fp2Element, input []byte) {\n\tif len(input) < 2*c.Params.Bytelen {\n\t\tpanic(\"input byte slice too short\")\n\t}\n\n\tfor i := 0; i < c.Params.Bytelen; i++ {\n\t\tj := i / 8\n\t\tk := uint64(i % 8)\n\t\tfp2.A[j] |= uint64(input[i]) << (8 * k)\n\t\tfp2.B[j] |= uint64(input[i+c.Params.Bytelen]) << (8 * k)\n\t}\n\tc.Params.Op.ToMontgomery(fp2)\n}", "func main() {\n // Parameters begin\n message := []byte(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\")\n n := 5\n // Parameters end\n \n fmt.Printf(\"{\\n\")\n // Generate key pairs\n var privates []kyber.Scalar\n var publics []kyber.Point\n for i := 0; i < n; i++ {\n // kp := key.NewKeyPair(testSuite)\n private := testSuite.Scalar().Pick(random.Stream)\n public := testSuite.Point().Mul(expand(private), nil)\n privates = append(privates, private)\n publics = append(publics, public)\n }\n\n fmt.Printf(\" privKeys: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(privates[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n fmt.Printf(\" pubKeys: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032s\\\")\", publics[i].String())\n }\n fmt.Printf(\"],\\n\")\n\n // Init masks\n var masks []*cosi.Mask\n var byteMasks [][]byte\n for i := 0; i < n; i++ {\n m, err := cosi.NewMask(testSuite, publics, publics[i])\n if err != nil {\n panic(err.Error())\n }\n masks = append(masks, m)\n byteMasks = append(byteMasks, masks[i].Mask())\n }\n\n // Compute commitments\n var v []kyber.Scalar // random\n var V []kyber.Point // commitment\n for i := 0; i < n; i++ {\n x, X := cosi.Commit(testSuite, nil)\n v = append(v, x)\n V = append(V, X)\n }\n\n fmt.Printf(\" secrets: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(v[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n fmt.Printf(\" commitments: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032s\\\")\", V[i].String())\n }\n fmt.Printf(\"],\\n\")\n\n // Aggregate commitments\n aggV, aggMask, err := cosi.AggregateCommitments(testSuite, V, byteMasks)\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\" aggCommitment: BufferUtils.fromHex(\\\"%032s\\\"),\\n\", aggV.String())\n\n // Set aggregate mask in nodes\n for i := 0; i < n; i++ {\n masks[i].SetMask(aggMask)\n }\n\n // Compute challenge\n var c []kyber.Scalar\n for i := 0; i < n; i++ {\n ci, err := cosi.Challenge(testSuite, aggV, masks[i].AggregatePublic, message)\n if err != nil {\n panic(err.Error())\n }\n c = append(c, ci)\n }\n fmt.Printf(\" aggPubKey: BufferUtils.fromHex(\\\"%032s\\\"),\\n\", masks[0].AggregatePublic.String())\n\n // Compute responses\n var r []kyber.Scalar\n for i := 0; i < n; i++ {\n ri, _ := cosi.Response(testSuite, expand(privates[i]), v[i], c[i])\n r = append(r, ri)\n }\n\n fmt.Printf(\" partialSignatures: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(r[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n // Aggregate responses\n aggr, err := cosi.AggregateResponses(testSuite, r)\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\" aggSignature: BufferUtils.fromHex(\\\"%032x\\\"),\\n\", reverse(aggr.Bytes()))\n\n for i := 0; i < n; i++ {\n // Sign\n sig, err := cosi.Sign(testSuite, aggV, aggr, masks[i])\n if err != nil {\n panic(err.Error())\n }\n // Verify (using default policy)\n if err := cosi.Verify(testSuite, publics, message, sig, nil); err != nil {\n panic(err.Error())\n }\n }\n\n fmt.Printf(\" signature: BufferUtils.fromHex(\\\"%032s%032x\\\"),\\n\", aggV.String(), reverse(aggr.Bytes()))\n fmt.Printf(\" message: BufferUtils.fromAscii(\\\"%032s\\\")\\n\", message)\n fmt.Printf(\"}\\n\")\n}", "func toomInterpolate(points [][]int32, param []int32) []int32 {\n\tt := make(thinPoly, 256)\n\tu := make(thinPoly, 256)\n\n\tfor i := range points {\n\t\tt.Inc(u.Mul(param[i], points[i]))\n\t}\n\n\treturn t.Freeze()\n}", "func newbloom(n uint64, p float64) (b Bloom) {\n\tm := math.Ceil(-float64(n) * math.Log(p) / math.Ln2 / math.Ln2)\n\tk := math.Ceil(-math.Log(p) / math.Ln2)\n\t// fmt.Printf(\"MiB %v keys %v\\n\", m/8/1024/1024, k)\n\tarrsize := (uint64(m) + 8) / 8\n\tb.bitarray = make([]uint8, arrsize)\n\tb.size = uint64(m)\n\tb.keys = make([][16]byte, int(k))\n\tfor i := 0; i < len(b.keys); i++ {\n\t\tfor j := 0; j < len(b.keys[i]); j++ {\n\t\t\tb.keys[i][j] = byte(rand.Int31n(256))\n\t\t}\n\t}\n\treturn\n}", "func hornerPolyEval(poly []*big.Int, x *big.Int) *big.Int {\n\tresult := big.NewInt(0)\n\tresult.Add(result, poly[0])\n\tfor i := 1; i < len(poly); i++ {\n\t\tresult = result.Mul(result, x).Add(result, poly[i])\n\t}\n\treturn result.Mod(result, baseN)\n}", "func Rbinomial(x, y float64) float64 {\n\tif x < 0 || y < 0 {\n\t\tchk.Panic(\"Rbinomial requires x and y to be non-negative, at this moment\")\n\t}\n\ta := math.Gamma(x + 1.0)\n\tb := math.Gamma(y + 1.0)\n\tc := math.Gamma(x - y + 1.0)\n\treturn a / (b * c)\n}", "func (el *Fill) Polyline() {}", "func NextNegativeBinomial(ρ float64, r int64) int64 {\n\tk := iZero\n\tfor r >= 0 {\n\t\ti := NextBernoulli(ρ)\n\t\tr -= i\n\t\tk += (1 - i)\n\t}\n\treturn k\n}", "func VPERMI2B(ops ...operand.Op) { ctx.VPERMI2B(ops...) }", "func Poly(p *sdf.Polygon, path string) error {\n\n\tvlist := p.Vertices()\n\tif vlist == nil {\n\t\treturn errors.New(\"no vertices\")\n\t}\n\n\tfmt.Printf(\"rendering %s\\n\", path)\n\td := NewDXF(path)\n\n\tfor i := 0; i < len(vlist)-1; i++ {\n\t\tp0 := vlist[i]\n\t\tp1 := vlist[i+1]\n\t\td.Line(p0, p1)\n\t}\n\n\tif p.Closed() {\n\t\tp0 := vlist[len(vlist)-1]\n\t\tp1 := vlist[0]\n\t\tif !p0.Equals(p1, tolerance) {\n\t\t\td.Line(p0, p1)\n\t\t}\n\t}\n\n\treturn d.Save()\n}", "func KORB(k, k1, k2 operand.Op) { ctx.KORB(k, k1, k2) }", "func bobKeyGenSlow(secretKey *SIDHSecretKeyBob) SIDHPublicKeyBob {\n\tvar xP, xQ, xQmP, xR, xS ProjectivePoint\n\n\txP.FromAffinePrimeField(&Affine_xPA) // = ( x_P : 1) = x(P_A)\n\txQ.FromAffinePrimeField(&Affine_xPA) //\n\txQ.X.Neg(&xQ.X) // = (-x_P : 1) = x(Q_A)\n\txQmP = DistortAndDifference(&Affine_xPA) // = x(Q_B - P_B)\n\n\txR = SecretPoint(&Affine_xPB, &Affine_yPB, secretKey.Scalar[:])\n\n\tvar currentCurve ProjectiveCurveParameters\n\t// Starting curve has a = 0, so (A:C) = (0,1)\n\tcurrentCurve.A.Zero()\n\tcurrentCurve.C.One()\n\n\tvar phi ThreeIsogeny\n\tfor e := 238; e >= 0; e-- {\n\t\txS.Pow3k(&currentCurve, &xR, uint32(e))\n\t\tcurrentCurve, phi = ComputeThreeIsogeny(&xS)\n\t\txR = phi.Eval(&xR)\n\t\txP = phi.Eval(&xP)\n\t\txQ = phi.Eval(&xQ)\n\t\txQmP = phi.Eval(&xQmP)\n\t}\n\n\tvar invZP, invZQ, invZQmP ExtensionFieldElement\n\tExtensionFieldBatch3Inv(&xP.Z, &xQ.Z, &xQmP.Z, &invZP, &invZQ, &invZQmP)\n\n\tvar publicKey SIDHPublicKeyBob\n\tpublicKey.affine_xP.Mul(&xP.X, &invZP)\n\tpublicKey.affine_xQ.Mul(&xQ.X, &invZQ)\n\tpublicKey.affine_xQmP.Mul(&xQmP.X, &invZQmP)\n\n\treturn publicKey\n}", "func StatelessRandomBinomial(scope *Scope, shape tf.Output, seed tf.Output, counts tf.Output, probs tf.Output, optional ...StatelessRandomBinomialAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"StatelessRandomBinomial\",\n\t\tInput: []tf.Input{\n\t\t\tshape, seed, counts, probs,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (p *YCbCr) COffset(x, y int) int {\n\tswitch p.SubsampleRatio {\n\tcase YCbCrSubsampleRatio422:\n\t\treturn (y-p.Rect.Min.Y)*p.CStride + (x/2 - p.Rect.Min.X/2)\n\tcase YCbCrSubsampleRatio420:\n\t\treturn (y/2-p.Rect.Min.Y/2)*p.CStride + (x/2 - p.Rect.Min.X/2)\n\tcase YCbCrSubsampleRatio440:\n\t\treturn (y/2-p.Rect.Min.Y/2)*p.CStride + (x - p.Rect.Min.X)\n\tcase YCbCrSubsampleRatio411:\n\t\treturn (y-p.Rect.Min.Y)*p.CStride + (x/4 - p.Rect.Min.X/4)\n\tcase YCbCrSubsampleRatio410:\n\t\treturn (y/2-p.Rect.Min.Y/2)*p.CStride + (x/4 - p.Rect.Min.X/4)\n\t}\n\t// Default to 4:4:4 subsampling.\n\treturn (y-p.Rect.Min.Y)*p.CStride + (x - p.Rect.Min.X)\n}", "func create(bins uint64) *cmap {\n\tif bins == 0 {\n\t\tpanic(\"tried to create empty cuckoo map\")\n\t}\n\n\tif bins&(bins-1) != 0 {\n\t\t// unless explicitly told otherwise, we'll create a decently\n\t\t// sized table by default\n\t\tvar shift uint64 = 1 << 10\n\t\tfor bins > shift {\n\t\t\tshift <<= 1\n\t\t}\n\t\tbins = shift\n\t}\n\n\t// since each bin can hold ASSOCIATIVITY elements\n\t// we don't need as many bins\n\tbins >>= ASSOCIATIVITY_E\n\n\tif bins == 0 {\n\t\tbins = 1\n\t}\n\tfmt.Fprintln(os.Stderr, \"will initialize with\", bins, \"bins\")\n\n\tm := new(cmap)\n\tm.bins = make([]cbin, bins)\n\tm.hashes = 2\n\treturn m\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func dividePolynomial(nn []float64 , dd []float64) (q, r []float64, ok bool) {\n \n if degree(dd) < 0 {\n return\n }\n\n nnfloat := append(r, nn...)\n \n if degree(nnfloat) >= degree(dd) {\n\n q = make([]float64, degree(nnfloat)-degree(dd)+1)\n\n for degree(nnfloat) >= degree(dd) {\n d := make([]float64, degree(nnfloat)+1)\n copy(d[degree(nnfloat)-degree(dd):], dd)\n q[degree(nnfloat)-degree(dd)] = nnfloat[degree(nnfloat)] / d[degree(d)]\n for i := range d {\n d[i] *= q[degree(nnfloat)-degree(dd)]\n nnfloat[i] -= d[i]\n }\n }\n }\n\n return q, nnfloat, true\n\n}", "func Constructor() TwoSum {\n\treturn TwoSum{data: map[int]int{}}\n}", "func polynomialPollardsRho(x1, x2, c *nt.Integer) *nt.Integer {\n\ttwo := nt.FromInt64(2)\n\tz := new(nt.Integer).Exp(x1, two, x2) // x1^2 mod x2\n\tz.Add(z, c) // (x1^2 mod x2) + 1\n\tz.Mod(z, x2) // (x1^2 + 1) mod x2\n\treturn z\n}", "func NewCCollisionPoly(anchor *CLocation, points ...pixel.Vec) ecs.Component {\n\tvar angles []float64\n\tvar uniqueEdges []edge\n\tvar pointA, pointB pixel.Vec\n\tvar pointAptr, pointBptr *pixel.Vec\nFINDNORMALS:\n\tfor i := range points {\n\t\tpointA = points[i]\n\t\tpointAptr = &points[i]\n\t\tif i == len(points)-1 {\n\t\t\tpointB = points[0]\n\t\t\tpointBptr = &points[0]\n\t\t} else {\n\t\t\tpointB = points[i+1]\n\t\t\tpointBptr = &points[i+1]\n\t\t}\n\t\tangle := pointA.Sub(pointB).Angle()\n\t\tfor _, a := range angles {\n\t\t\tif a == angle || a == angle-math.Pi || a == angle+math.Pi {\n\t\t\t\tcontinue FINDNORMALS\n\t\t\t}\n\t\t}\n\t\tangles = append(angles, angle)\n\t\tuniqueEdges = append(uniqueEdges, edge{\n\t\t\tpointA: pointAptr,\n\t\t\tpointB: pointBptr,\n\t\t})\n\t}\n\treturn &CCollisionPoly{\n\t\ttag: CPTAG,\n\t\tAnchor: anchor,\n\t\tPoints: points,\n\t\tUniqueEdges: uniqueEdges,\n\t}\n}", "func TestNegativeBinomial_PMF_CDF(t *testing.T) {\n\tvar (\n\t\tρ float64\n\t\ti, n int64\n\t)\n\n\t// edit the following values: >>>\n\tρ = 0.5\n\tn = 20\n\n\tk := []int64{10, 11, 12, 16, 25, 40}\n\tpmf := []float64{0.0186544004827737808228, 0.025437818840146064758, 0.0328571826685220003128, 0.05907974191359244287, 0.04004139896255765052, 0.00121194851197753156874}\n\tcdf := []float64{0.0493685733526945114136, 0.074806392192840576172, 0.1076635748613625764847, 0.30885965851484797895, 0.81435098276449480181, 0.9968911986703366647292}\n\n\t// <<<\n\n\tfmt.Println(\"test of NegativeBinomial PMF\")\n\tfor i = 0; i < int64(len(k)); i++ {\n\t\tprob := NegBinomialPMFAt(ρ, n, k[i])\n\t\tif !check(prob, pmf[i]) {\n\t\t\tt.Error()\n\t\t\tfmt.Println(k[i], prob, pmf[i])\n\n\t\t}\n\t}\n\n\tfmt.Println(\"test of NegativeBinomial CDF\")\n\tfor i = 0; i < int64(len(k)); i++ {\n\t\tprob := NegBinomialCDFAt(ρ, n, k[i])\n\t\tif !check(prob, cdf[i]) {\n\t\t\tt.Error()\n\t\t\tfmt.Println(k[i], prob, cdf[i])\n\t\t}\n\t}\n}", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func (p *G2Jac) pippenger(curve *Curve, points []G2Jac, scalars []fr.Element, s, b uint64, T []G2Jac, computeT func(T []G2Jac, t0 *G2Jac)) *G2Jac {\n\tvar t, selectorIndex, ks int\n\tvar selectorMask, selectorShift, selector uint64\n\n\tt = fr.ElementLimbs * 64 / int(s) // t from Bootle, equal to (scalar bit length) / s\n\tselectorMask = (1 << b) - 1 // low b bits are 1\n\tmorePoints := make([]G2Jac, t) // morePoints is the set of G'_k points from Bootle\n\tfor k := 0; k < t; k++ {\n\t\tmorePoints[k].Set(&curve.g2Infinity)\n\t}\n\tfor i := 0; i < len(points); i++ {\n\t\t// compute the set T_i from Bootle: all possible combinations of elements from S_i from Bootle\n\t\tcomputeT(T, &points[i])\n\t\t// for each morePoints: find the right T element and add it\n\t\tfor k := 0; k < t; k++ {\n\t\t\tks = k * int(s)\n\t\t\tselectorIndex = ks / 64\n\t\t\tselectorShift = uint64(ks - (selectorIndex * 64))\n\t\t\tselector = (scalars[i][selectorIndex] & (selectorMask << selectorShift)) >> selectorShift\n\t\t\tif selector != 0 {\n\t\t\t\tmorePoints[k].Add(curve, &T[selector-1])\n\t\t\t}\n\t\t}\n\t}\n\t// combine morePoints to get the final result\n\tp.Set(&morePoints[t-1])\n\tfor k := t - 2; k >= 0; k-- {\n\t\tfor j := uint64(0); j < s; j++ {\n\t\t\tp.Double()\n\t\t}\n\t\tp.Add(curve, &morePoints[k])\n\t}\n\treturn p\n}", "func Jacobi(x, y *big.Int,) int", "func penalty(b board) (p float64) {\n\tfor k := range pen {\n\t\tp += pen[k] * freq[b[k]]\n\t}\n\treturn\n}", "func (cc *CouponChaincode) cbDto2Cb(cbDto *CouponBatchDto) *CouponBatch {\n\tcb := &CouponBatch{Id: cbDto.Id, Sn: cbDto.BatchSn, Name: cbDto.BatchName,\n\t\tBatchType: cbDto.BatchType, Denomination: cbDto.Money,\n\t\tEffectiveDate: cbDto.EffectiveStartTime, ExpiringDate: cbDto.EffectiveEndTime,\n\t\tPublishDate: cbDto.PublishTime, Desc: cbDto.Description, ShopId: cbDto.ShopId,\n\t\tPicture: cbDto.Picture, Status: cbDto.Status, CouponType: cbDto.UsageRuleType}\n\tif cbDto.UsageRuleType == 1 {\n\t\tcb.OrderPriceLimit = cbDto.UsageRule[\"minAmount\"].(int)\n\t}\n\tquantityMap := cbDto.Quantity\n\tif quantityMap != nil {\n\t\tcb.CouponAmount = quantityMap[\"allQuantity\"].(int)\n\t\t//TODO.....other props of quantity\n\t}\n\treturn cb\n\n}", "func (bng *binningP1D) Bins() []BinP1D {\n\treturn bng.bins\n}", "func (c *CurveOperations) Fp2ToBytes(output []byte, fp2 *Fp2Element) {\n\tif len(output) < 2*c.Params.Bytelen {\n\t\tpanic(\"output byte slice too short\")\n\t}\n\tvar a Fp2Element\n\tc.Params.Op.FromMontgomery(fp2, &a)\n\n\t// convert to bytes in little endian form\n\tfor i := 0; i < c.Params.Bytelen; i++ {\n\t\t// set i = j*8 + k\n\t\tfp2 := i / 8\n\t\tk := uint64(i % 8)\n\t\toutput[i] = byte(a.A[fp2] >> (8 * k))\n\t\toutput[i+c.Params.Bytelen] = byte(a.B[fp2] >> (8 * k))\n\t}\n}", "func QuadAxpy(c, b []float64, s float64, ci, bi int)", "func X2(env *tempAll.Environment) (float64, error) {\n\t// kz^2 version - incompatible with finite magnetic field\n\tif env.PairKzSquaredSpectrum && math.Abs(env.Be_field) < 1e-9 {\n\t\tnu, err := nu(env)\n\t\tif err != nil {\n\t\t\treturn 0.0, err\n\t\t}\n\t\tx2 := nu / math.Pow(env.Beta, 3.0/2.0)\n\t\treturn x2, nil\n\t}\n\t// cos(kz) version\n\tif -env.Mu_b > -2.0*env.Mu_h {\n\t\treturn 0.0, nil\n\t}\n\t// find omega_+ coefficients\n\ta, b := env.A, env.B\n\tif !env.FixedPairCoeffs || !env.PairCoeffsReady {\n\t\tplusCoeffs, err := OmegaFit(env, OmegaPlus)\n\t\t//fmt.Printf(\"plusCoeffs in X2: %v\\n\", plusCoeffs)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"suppressing error in x2 - cannot find pair spectrum\")\n\t\t\treturn 0.0, nil\n\t\t}\n\t\ta, b = plusCoeffs[0], plusCoeffs[2]\n\t}\n\t// zero magnetic field with cos(kz) spectrum\n\tif math.Abs(env.Be_field) < 1e-9 {\n\t\tintegrand := func(y, kz float64) float64 {\n\t\t\tbterm := 2.0 * b * (1.0 - math.Cos(kz))\n\t\t\treturn 2.0 / (math.Exp(y+env.Beta*(bterm-env.Mu_b)) - 1.0)\n\t\t}\n\t\tplus, err := OmegaIntegralCos(env, a, b, integrand)\n\t\tif err != nil {\n\t\t\treturn 0.0, err\n\t\t}\n\t\treturn plus, nil\n\t}\n\t// if we get here, math.Abs(env.Be_field) >= 1e-9\n\t//fmt.Printf(\"about to calculate x2 sum for env = %s\\n\", env.String())\n\tx2BSumTerm := func(ri int) float64 {\n\t\tr := float64(ri)\n\t\tI0 := bessel.ModifiedBesselFirstKindZeroth(2.0 * b * env.Beta * r)\n\t\tomega_c := 4.0 * env.Be_field * a\n\t\tmu_tilde := env.Mu_b - omega_c/2.0\n\t\treturn I0 * math.Exp(env.Beta*r*(mu_tilde-2.0*b)) / (-math.Expm1(-env.Beta * omega_c * r))\n\t\t/*\n\t\tsum_n_term := func(ni int) float64 {\n\t\t\tn := float64(ni)\n\t\t\tnp1_fact := math.Gamma(n + 2.0)\n\t\t\treturn math.Pow(-r * env.Beta * omega_c, n) / np1_fact\n\t\t}\n\t\tsum_n, _ := seriesaccel.Levin_u(sum_n_term, 1, 20)\n\t\treturn I0 * math.Exp(env.Beta*r*(mu_tilde-2.0*b)) / (r * (1.0 + sum_n))\n\t\t*/\n\t}\n\tsum, _ := seriesaccel.Levin_u(x2BSumTerm, 1, 20)\n\t//fmt.Printf(\"%v\\n\", sum)\n\t// reporting of absErr:\n\t// (dropped this since absErr is always very small relative to sum)\n\t//sum, absErr := seriesaccel.Levin_u(x2BSumTerm, 1, 20)\n\t//fmt.Printf(\"for env=%s; x2 B sum %e, absErr %e\\n\", env.String(), sum, absErr)\n\treturn 2.0 * env.Be_field * sum / math.Pi, nil\n\t//return sum / (2.0 * math.Pi * env.Beta * a), nil\n}", "func monoCubicInterpolate(xs []float64, ys []float64) func(float64) float64 {\n\tlength := len(xs)\n\n\t// Dealing with length issues\n\tswitch {\n\tcase length != len(ys):\n\t\tpanic(errors.New(\"need an equal count of xs and ys\"))\n\tcase length == 0:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn 0\n\t\t}\n\tcase length == 1:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn ys[0]\n\t\t}\n\t}\n\n\t// Get consecutive differences and slopes\n\tdys := make([]float64, length-1)\n\tdxs := make([]float64, length-1)\n\tms := make([]float64, length-1)\n\tfor i := 0; i < length-1; i++ {\n\t\tdx := xs[i+1] - xs[i]\n\t\tdy := ys[i+1] - ys[i]\n\t\tdxs[i], dys[i], ms[i] = dx, dy, dy/dx\n\t}\n\n\t// Get degree-1 coefficients\n\tc1s := make([]float64, length)\n\tc1s[0] = ms[0]\n\tfor i := 1; i < len(dxs); i++ {\n\t\tm, mNext := ms[i-1], ms[i]\n\t\tif m * mNext <= 0 {\n\t\t\tc1s[i] = 0\n\t\t} else {\n\t\t\tdx_, dxNext := dxs[i-1], dxs[i]\n\t\t\tcommon := dx_ + dxNext\n\t\t\tc1s[i] = 3 * common / ((common + dxNext)/m + (common + dx_)/mNext)\n\t\t}\n\t}\n\tc1s[length-1] = ms[len(ms)-1]\n\n\t// Get degree-2 and degree-3 coefficients\n\tc2s := make([]float64, length-1)\n\tc3s := make([]float64, length-1)\n\tfor i := 0; i < len(c1s)-1; i++ {\n\t\tc1, m_ := c1s[i], ms[i]\n\t\tinvDx, common_ := 1/dxs[i], c1 + c1s[i+1] - m_ - m_\n\t\tc2s[i] = (m_ - c1 - common_) * invDx\n\t\tc3s[i] = common_ * invDx * invDx\n\t}\n\n\t// Return interpolant function\n\treturn func(x float64) float64 {\n\t\t// The rightmost point in the dataset should give an exact result\n\t\ti := len(xs) - 1\n\t\tif x == xs[i] {\n\t\t\treturn ys[i]\n\t\t}\n\n\t\t// Search for the interval x is in, returning the corresponding y if x is one of the original xs\n\t\tlow, mid, high := 0, len(c3s)-1, len(c3s)-1\n\t\tfor low <= high {\n\t\t\tmid = int(math.Floor(0.5 * float64(low + high)))\n\t\t\txHere := xs[mid]\n\t\t\tif xHere < x {\n\t\t\t\tlow = mid + 1\n\t\t\t} else if xHere > x {\n\t\t\t\thigh = mid - 1\n\t\t\t} else {\n\t\t\t\treturn ys[mid]\n\t\t\t}\n\t\t}\n\t\ti = int(math.Max(0, float64(high)))\n\n\t\t// Interpolate\n\t\tdiff := x - xs[i]\n\t\tdiffSq := diff*diff\n\t\treturn ys[i] + c1s[i]*diff + c2s[i]*diffSq + c3s[i]*diff*diffSq\n\t}\n\n}", "func (p thinPoly) Zero() thinPoly {\n\tfor i := range p {\n\t\tp[i] = 0\n\t}\n\treturn p\n}", "func (p *P1D) Binning() *binningP1D {\n\treturn &p.bng\n}", "func yCbCrToYCbCr(m *image.YCbCr, p image.Point, yBlock, cbBlock, crBlock *block) {\n\tb := m.Bounds()\n\txmax := b.Max.X - 1\n\tymax := b.Max.Y - 1\n\tfor j := 0; j < 8; j++ {\n\t\tsy := p.Y + j\n\t\tif sy > ymax {\n\t\t\tsy = ymax\n\t\t}\n\t\tfor i := 0; i < 8; i++ {\n\t\t\tsx := p.X + i\n\t\t\tif sx > xmax {\n\t\t\t\tsx = xmax\n\t\t\t}\n\t\t\tyi := m.YOffset(sx, sy)\n\t\t\tci := m.COffset(sx, sy)\n\t\t\tyBlock[8*j+i] = int32(m.Y[yi])\n\t\t\tcbBlock[8*j+i] = int32(m.Cb[ci])\n\t\t\tcrBlock[8*j+i] = int32(m.Cr[ci])\n\t\t}\n\t}\n}", "func GetGeneratorOfZnSubgroup(n, groupOrder, subgroupOrder *big.Int) (*big.Int, error) {\n\tif big.NewInt(0).Mod(groupOrder, subgroupOrder).Cmp(big.NewInt(0)) != 0 {\n\t\terr := errors.New(\"subgroupOrder does not divide groupOrder\")\n\t\treturn nil, err\n\t}\n\tr := new(big.Int).Div(groupOrder, subgroupOrder)\n\tfor {\n\t\th := GetRandomInt(n)\n\t\tg := new(big.Int)\n\t\tg.Exp(h, r, n)\n\t\tif g.Cmp(big.NewInt(1)) != 0 {\n\t\t\treturn g, nil\n\t\t}\n\t}\n}", "func PolygonForRing(ctx context.Context, rng [][2]float64) (plyg [][][2]float64) {\n\tif debug {\n\t\tlog.Printf(\"turn ring into polygon.\")\n\t\tlog.Printf(\"ring: %v\", wkt.MustEncode(rng))\n\t}\n\n\tif len(rng) <= 2 {\n\t\treturn nil\n\t}\n\n\t// normalize ring\n\tcmppkg.RotateToLeftMostPoint(rng)\n\n\tpIdx := func(i int) int {\n\t\tif i == 0 {\n\t\t\treturn len(rng) - 1\n\t\t}\n\t\treturn i - 1\n\t}\n\tnIdx := func(i int) int {\n\t\tif i == len(rng)-1 {\n\t\t\treturn 0\n\t\t}\n\t\treturn i + 1\n\t}\n\n\t// Allocate space for the initial ring.\n\tplyg = make([][][2]float64, 1)\n\n\t// Remove bubbles. There are two types of bubbles we have to look for.\n\t// 1. ab … bc, in which case we need to hold on to b.\n\t// It is possible that b is absolutely not necessary. It could lie on the line between a and c, in which case\n\t// we should remove the extra point.\n\t// 2. ab … ba, which case we do not need to have b in the ring.\n\n\t// let's build an index of where the points that we are walking are. That way when we encounter the same\n\t// point we are able to “jump” to that point.\n\tptIndex := map[[2]float64]int{}\n\tvar ok bool\n\tvar idx int\n\n\t// Let's walk the points\n\tfor i := 0; i < len(rng); i++ {\n\t\t// Context has been cancelled.\n\t\tif ctx.Err() != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// check to see if we have already seen this point.\n\t\tif idx, ok = ptIndex[rng[i]]; !ok {\n\t\t\tptIndex[rng[i]] = i\n\t\t\tcontinue\n\t\t}\n\n\t\t// ➠ what type of bubble are we dealing with\n\t\tpidx, nidx := pIdx(idx), nIdx(i)\n\n\t\t// clear out ptIndex of the values we are going to cut.\n\t\tfor j := idx; j <= i; j++ {\n\t\t\tdelete(ptIndex, rng[j])\n\t\t}\n\n\t\t// ab…ba ring. So we need to remove all the way to a.\n\t\tif nidx != pidx && cmp.PointEqual(rng[pidx], rng[nidx]) {\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"bubble type ab…ba: (% 5v)(% 5v) … (% 5v)(% 5v)\", pidx, idx, i, nidx)\n\t\t\t}\n\n\t\t\t// delete the ʽaʼ point as well from point index\n\t\t\tdelete(ptIndex, rng[pidx])\n\n\t\t\tsliver := cut(&rng, pidx, nidx)\n\t\t\t// remove the start ab\n\t\t\tsliver = sliver[2:]\n\t\t\tif len(sliver) >= 3 { // make a copy to free up memory.\n\t\t\t\tps := make([][2]float64, len(sliver))\n\t\t\t\tcopy(ps, sliver)\n\t\t\t\tcmppkg.RotateToLeftMostPoint(ps)\n\t\t\t\tif debug {\n\t\t\t\t\tlog.Printf(\"ring: %v\", wkt.MustEncode(rng))\n\t\t\t\t\tlog.Printf(\"sliver: %v\", wkt.MustEncode(sliver))\n\t\t\t\t}\n\t\t\t\tplyg = append(plyg, ps)\n\t\t\t}\n\n\t\t\tif i = idx - 1; i < 0 {\n\t\t\t\ti = 0\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// do a quick check to see if b is on ac\n\t\tremoveB := planar.IsPointOnLine(cmp, rng[i], rng[pidx], rng[nidx])\n\n\t\t// ab … bc The sliver is going to be from b … just before b. So, the ring will be …abc… or …ac… depending on removeB\n\t\tif debug {\n\t\t\tlog.Printf(\"bubble type ab…bc: (% 5v)(% 5v) … (% 5v)(% 5v) == %t\", pidx, idx, i, nidx, removeB)\n\t\t\tlog.Printf(\"ab..bc: [%v][%v]..[%v][%v]\",\n\t\t\t\twkt.MustEncode(geom.Point(rng[pidx])),\n\t\t\t\twkt.MustEncode(geom.Point(rng[idx])),\n\t\t\t\twkt.MustEncode(geom.Point(rng[i])),\n\t\t\t\twkt.MustEncode(geom.Point(rng[nidx])),\n\t\t\t)\n\t\t\tlog.Printf(\"%v , %v\",\n\t\t\t\twkt.MustEncode(geom.Point(rng[i])),\n\t\t\t\twkt.MustEncode(geom.Line{rng[pidx], rng[nidx]}),\n\t\t\t)\n\t\t}\n\n\t\t// Quick hack to remove extra bridges that are geting left over.\n\t\tsliver := removeBridge(cut(&rng, idx, i))\n\n\t\tif len(sliver) >= 3 {\n\t\t\tcmppkg.RotateToLeftMostPoint(sliver)\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"ring: %v\", wkt.MustEncode(rng))\n\t\t\t\tlog.Printf(\"sliver: %v\", wkt.MustEncode(sliver))\n\t\t\t}\n\t\t\tplyg = append(plyg, sliver)\n\t\t}\n\n\t\ti = idx\n\t\tif removeB {\n\t\t\tcut(&rng, idx, idx+1)\n\t\t\tif idx == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti = idx - 1\n\t\t}\n\t} // for\n\n\tif len(rng) <= 2 {\n\t\tif debug {\n\t\t\tlog.Println(\"rng:\", rng)\n\t\t\tlog.Println(\"plyg:\", plyg)\n\t\t\tpanic(\"main ring is not correct!\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tplyg[0] = make([][2]float64, len(rng))\n\tcopy(plyg[0], rng)\n\tcmppkg.RotateToLeftMostPoint(plyg[0])\n\treturn plyg\n}", "func PolyInt64(a []int64, t []TermT) TermT {\n\tcount := C.uint32_t(len(a))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_int64(count, (*C.int64_t)(&a[0]), (*C.term_t)(&t[0])))\n}", "func CVTPD2PL(mx, x operand.Op) { ctx.CVTPD2PL(mx, x) }", "func initTerrain(game *gamestate) {\n\trand.New(rand.NewSource(42)) //42 best magical Constant\n\trand.Seed(time.Now().UnixNano())\n\tx := 0\n\n\ty := heightOfMap - rand.Float64()*(heightOfMap/2) // the height to start at\n\tfmt.Println(y)\n\t//standardTerrain := y\n\tvar dy float64 = 0\n\tvar dyGoal float64 = 0\n\tvar curveDensity float64 = 0\n\n\tfor x < int(mapSize) {\n\t\tif curveDensity == 0 {\n\t\t\tdyGoal = 0.5 * (-0.5 + rand.Float64())\n\t\t\tcurveDensity = 30\n\t\t}\n\t\tdy += dyGoal / 30\n\t\ty += dy\n\t\tif x == 0 {\n\t\t\tfmt.Println(int(y))\n\t\t}\n\t\tgame.Terrain[x] = genTerrain(x, int(y))\n\t\tcurveDensity--\n\t\tx++\n\t\tif y > heightOfMap-250 {\n\t\t\tdy -= 0.02\n\t\t}\n\t\tif y > heightOfMap-200 {\n\t\t\tdyGoal = -0.5\n\t\t\tdy -= 0.05\n\t\t}\n\n\t\tif y < reactionHeight+100 {\n\t\t\tdy += 0.01\n\t\t}\n\t\tif y < reactionHeight {\n\t\t\tdyGoal = 0.5\n\t\t\tdy += 0.05\n\t\t}\n\t\tif dy >= 0.33 {\n\t\t\tdy = 0.33\n\t\t}\n\t\tif dy <= -0.33 {\n\t\t\tdy = -0.33\n\t\t}\n\n\t}\n\n}", "func (win *window) Polygon(pt []image.Point, fill bool) {\n\tif len(pt) < 2 {\n\t\treturn\n\t}\n\tpts := make([]xgb.Point, len(pt))\n\tfor i, p := range pt {\n\t\tpts[i].X, pts[i].Y = int16(p.X), int16(p.Y)\n\t}\n\tif !fill {\n\t\tif !pt[0].Eq(pt[len(pt)-1]) {\n\t\t\tpts = append(pts, xgb.Point{int16(pt[0].X), int16(pt[0].Y)})\n\t\t}\n\t\txwin.PolyLine(xgb.CoordModeOrigin, win.id, win.gc, pts)\n\t\treturn\n\t}\n\txwin.FillPoly(win.id, win.gc, xgb.PolyShapeComplex, xgb.CoordModeOrigin, pts)\n}" ]
[ "0.6076159", "0.5446268", "0.533303", "0.53215396", "0.5311621", "0.5164656", "0.50984806", "0.50669074", "0.5052633", "0.5024495", "0.50004286", "0.4997913", "0.4875465", "0.48699003", "0.4860667", "0.48596975", "0.48523688", "0.48450688", "0.47901952", "0.4755157", "0.47239137", "0.47198159", "0.46731052", "0.46523052", "0.46288776", "0.46133414", "0.46010536", "0.4599966", "0.44536746", "0.44448167", "0.4426283", "0.4425771", "0.44229612", "0.44127473", "0.44118282", "0.44001946", "0.43695554", "0.43607923", "0.4359021", "0.4354771", "0.4331588", "0.433126", "0.43206096", "0.4318537", "0.43072432", "0.43012753", "0.42963728", "0.42917734", "0.42915955", "0.42798454", "0.4278273", "0.42715624", "0.42570227", "0.42340893", "0.42336977", "0.42158082", "0.42145452", "0.4210671", "0.41984573", "0.41915974", "0.4189942", "0.41845968", "0.41730732", "0.41720167", "0.41670185", "0.41666144", "0.4164947", "0.41616595", "0.4159695", "0.4159477", "0.4158683", "0.41478255", "0.41459078", "0.4136555", "0.4123475", "0.41149566", "0.4107991", "0.41025102", "0.4101143", "0.40976185", "0.406898", "0.40689194", "0.4062789", "0.40491682", "0.40472826", "0.40466225", "0.40453276", "0.4043426", "0.4042239", "0.40392622", "0.40370882", "0.40353155", "0.4026617", "0.40221295", "0.40131503", "0.40129328", "0.40113646", "0.401021", "0.40100098", "0.39840448" ]
0.75362754
0
polyCBD3 samples a poly using a centered binomial distribution
func polyCBD3(outbuf []byte) Poly { var t, d uint32 var a, b int16 var p Poly for i := 0; i < n/4; i++ { t = load24LE(outbuf[3*i:]) d = t & 0x00249249 d += (t >> 1) & 0x00249249 d += (t >> 2) & 0x00249249 for j := 0; j < 4; j++ { a = int16((d >> (6*j + 0)) & 0x7) b = int16((d >> (6*j + 3)) & 0x7) p[4*i+j] = a - b } } return p }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func polyGetNoise(eta int, seed []byte, nonce byte) Poly {\n\toutbuf := make([]byte, eta*n/4)\n\tstate := sha3.NewShake256()\n\tstate.Write(seed[:])\n\tstate.Write([]byte{nonce})\n\tstate.Read(outbuf[:])\n\tvar p Poly\n\tif eta == 3 {\n\t\tp = polyCBD3(outbuf)\n\t}\n\tif eta == 2 {\n\t\tp = polyCBD2(outbuf)\n\t}\n\treturn p\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func (z *Int) Binomial(n, k int64) *Int {}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func RandomPolynomial(r io.Reader, degree uint64) (*Polynomial, error) {\n\tcoefficients := []*big.Int{}\n\tfor i := uint64(0); i < degree+1; i++ {\n\t\tc, err := rand.Int(r, bn256.Order)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tcoefficients = append(coefficients, c)\n\t}\n\treturn NewPolynomial(coefficients)\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func binomCoeff(n, k float64) float64 {\n\treturn fact(n) / (fact(k) * fact(n-k))\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func QuadAxpy(c, b []float64, s float64, ci, bi int)", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func wbbKeyGen(curve *math.Curve, rng io.Reader) (*math.Zr, *math.G2) {\n\t// sample sk uniform from Zq\n\tsk := curve.NewRandomZr(rng)\n\t// set pk = g2^sk\n\tpk := curve.GenG2.Mul(sk)\n\treturn sk, pk\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func NewPolynomialGenerator(b, step float64, a ...float64) *Euclidean {\n\tx := []float64{b}\n\tx = append(x, a...)\n\treturn &Euclidean{\n\t\tNewLinearSequence(0, step),\n\t\tF{f: []Y{\n\t\t\t// x coordinate :\n\t\t\tfunc(x ...float64) float64 {\n\t\t\t\treturn x[0]\n\t\t\t},\n\t\t\t// y coordinate\n\t\t\tpolynomialFunction(x...),\n\t\t}}}\n}", "func IntBinomial(z *big.Int, n, k int64) *big.Int", "func (c *curve) init(self kyber.Group, p *Param, fullGroup bool,\n\tnull, base point) *curve {\n\tc.self = self\n\tc.Param = *p\n\tc.full = fullGroup\n\tc.null = null\n\n\t// Edwards curve parameters as ModInts for convenience\n\tc.a.Init(&p.A, &p.P)\n\tc.d.Init(&p.D, &p.P)\n\n\t// Cofactor\n\tc.cofact.Init64(int64(p.R), &c.P)\n\n\t// Determine the modulus for scalars on this curve.\n\t// Note that we do NOT initialize c.order with Init(),\n\t// as that would normalize to the modulus, resulting in zero.\n\t// Just to be sure it's never used, we leave c.order.M set to nil.\n\t// We want it to be in a ModInt so we can pass it to P.Mul(),\n\t// but the scalar's modulus isn't needed for point multiplication.\n\tif fullGroup {\n\t\t// Scalar modulus is prime-order times the ccofactor\n\t\tc.order.V.SetInt64(int64(p.R)).Mul(&c.order.V, &p.Q)\n\t} else {\n\t\tc.order.V.Set(&p.Q) // Prime-order subgroup\n\t}\n\n\t// Useful ModInt constants for this curve\n\tc.zero.Init64(0, &c.P)\n\tc.one.Init64(1, &c.P)\n\n\t// Identity element is (0,1)\n\tnull.initXY(zero, one, self)\n\n\t// Base point B\n\tvar bx, by *big.Int\n\tif !fullGroup {\n\t\tbx, by = &p.PBX, &p.PBY\n\t} else {\n\t\tbx, by = &p.FBX, &p.FBY\n\t\tbase.initXY(&p.FBX, &p.FBY, self)\n\t}\n\tif by.Sign() == 0 {\n\t\t// No standard base point was defined, so pick one.\n\t\t// Find the lowest-numbered y-coordinate that works.\n\t\t//println(\"Picking base point:\")\n\t\tvar x, y mod.Int\n\t\tfor y.Init64(2, &c.P); ; y.Add(&y, &c.one) {\n\t\t\tif !c.solveForX(&x, &y) {\n\t\t\t\tcontinue // try another y\n\t\t\t}\n\t\t\tif c.coordSign(&x) != 0 {\n\t\t\t\tx.Neg(&x) // try positive x first\n\t\t\t}\n\t\t\tbase.initXY(&x.V, &y.V, self)\n\t\t\tif c.validPoint(base) {\n\t\t\t\tbreak // got one\n\t\t\t}\n\t\t\tx.Neg(&x) // try -bx\n\t\t\tif c.validPoint(base) {\n\t\t\t\tbreak // got one\n\t\t\t}\n\t\t}\n\t\t//println(\"BX: \"+x.V.String())\n\t\t//println(\"BY: \"+y.V.String())\n\t\tbx, by = &x.V, &y.V\n\t}\n\tbase.initXY(bx, by, self)\n\n\t// Uniform representation encoding methods,\n\t// only useful when using the full group.\n\t// (Points taken from the subgroup would be trivially recognizable.)\n\tif fullGroup {\n\t\tif p.Elligator1s.Sign() != 0 {\n\t\t\tc.hide = new(el1param).init(c, &p.Elligator1s)\n\t\t} else if p.Elligator2u.Sign() != 0 {\n\t\t\tc.hide = new(el2param).init(c, &p.Elligator2u)\n\t\t}\n\t}\n\n\t// Sanity checks\n\tif !c.validPoint(null) {\n\t\tpanic(\"invalid identity point \" + null.String())\n\t}\n\tif !c.validPoint(base) {\n\t\tpanic(\"invalid base point \" + base.String())\n\t}\n\n\treturn c\n}", "func NegativeBinomialCDF(ρ float64, r int64) func(k int64) float64 {\n\treturn func(k int64) float64 {\n\t\tIP := BetaCDFAt(float64(k+1), float64(r), ρ)\n\t\treturn 1 - IP\n\t}\n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func ConfBinomial(a int64, b int64) int {\n\tif b > a {\n\t\tfmt.Printf(\"\\033[31mX\\033[0m Error: the second number : %v is greater than %v\\n\", b, a)\n\t\treturn 84\n\t}\n\tres := new(big.Int)\n\tfmt.Printf(\"%v-combination of a set of size %v:\\n%v\\n\", uint64(b), uint64(a), res.Binomial(a, b))\n\treturn 0\n}", "func boxToPoly(b Box2d) polygon {\n\tcen_x, cen_y := b.Position()\n\twidth, height := b.Size()\n\tangle := b.AngleDegrees()\n\n\tpoints := [4]point{}\n\n\tpoints[0] = point{X: getX(-width/2, -height/2, angle) + cen_x,\n\t\tY: getY(-width/2, -height/2, angle) + cen_y}\n\n\tpoints[1] = point{X: getX(width/2, -height/2, angle) + cen_x,\n\t\tY: getY(width/2, -height/2, angle) + cen_y}\n\n\tpoints[2] = point{X: getX(-width/2, height/2, angle) + cen_x,\n\t\tY: getY(-width/2, height/2, angle) + cen_y}\n\n\tpoints[3] = point{X: getX(width/2, height/2, angle) + cen_x,\n\t\tY: getY(width/2, height/2, angle) + cen_y}\n\tz := boxPoly{points: points[:4]}\n\n\treturn z\n}", "func toomInterpolate(points [][]int32, param []int32) []int32 {\n\tt := make(thinPoly, 256)\n\tu := make(thinPoly, 256)\n\n\tfor i := range points {\n\t\tt.Inc(u.Mul(param[i], points[i]))\n\t}\n\n\treturn t.Freeze()\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func lagrangeInterpolate(points map[int]*big.Int, x int, curve elliptic.Curve) *big.Int {\n\tlog.Printf(\"The points is: %v\", points)\n\n\t// 通过这些坐标点来恢复出多项式\n\tpolynomialClient := polynomial.New(curve.Params().N)\n\tresult := polynomialClient.GetPolynomialByPoints(points)\n\n\t// 秘密就是常数项\n\tsecret := result[len(result)-1]\n\n\tlog.Printf(\"The coefficients of the polynomial is: %v\", result)\n\treturn secret\n}", "func ExampleFacettedPolygon() {\n\tf := FacettedNib{LineNib: LineNib{unitX, unitY}}\n\tPrintGraph(f.Polygon([][2]x{{0, 0}, {5 * unitX, 5 * unitX}, {5 * unitX, -5 * unitX}}...), -10*unitX, 10*unitX, -10*unitX, 10*unitX, unitX)\n\t// Output:\n\t/*\n\t\tGraph\n\t\t -10\t---------------------\n\t\t -9\t---------------------\n\t\t -8\t---------------------\n\t\t -7\t---------------------\n\t\t -6\t---------------------\n\t\t -5\t---------------X-----\n\t\t -4\t--------------XX-----\n\t\t -3\t-------------X-X-----\n\t\t -2\t------------X--X-----\n\t\t -1\t-----------X---X-----\n\t\t 0\t----------X----X-----\n\t\t 1\t-----------X---X-----\n\t\t 2\t------------X--X-----\n\t\t 3\t-------------X-X-----\n\t\t 4\t--------------XX-----\n\t\t 5\t---------------X-----\n\t\t 6\t---------------------\n\t\t 7\t---------------------\n\t\t 8\t---------------------\n\t\t 9\t---------------------\n\t\t 10\t---------------------\n\t*/\n}", "func BinomialDist(nb float64) int {\n\tfmt.Printf(\"Binomial distribution:\\n\")\n\tstart := time.Now()\n\t//\n\toverload := new(big.Float)\n\toverload.SetFloat64(1)\n\thundred := new(big.Float).SetFloat64(100)\n\tp := float64(nb / (8 * 60 * 60))\n\n\tfor k := float64(0); k != 51; k++ {\n\t\tfmt.Printf(\"%.0f -> %.3f\", k, BinomialAlgo(k, p))\n\n\t\tif (int(k+1) % 5) == 0 {\n\t\t\tfmt.Printf(\"\\n\")\n\t\t} else if k != 50 {\n\t\t\tfmt.Printf(\"\\t\")\n\t\t}\n\t\tif k <= 25 {\n\t\t\toverload.Sub(overload, BinomialAlgo(k, p))\n\t\t}\n\t}\n\t//\n\tduration := time.Since(start)\n\tfmt.Printf(\"\\nOverload: %.1f%%\", overload.Mul(overload, hundred))\n\tfmt.Printf(\"\\nComputation time: %.2f ms\\n\\n\",\n\t\tfloat64(duration.Nanoseconds())/1000000)\n\treturn 0\n}", "func hornerPolyEval(poly []*big.Int, x *big.Int) *big.Int {\n\tresult := big.NewInt(0)\n\tresult.Add(result, poly[0])\n\tfor i := 1; i < len(poly); i++ {\n\t\tresult = result.Mul(result, x).Add(result, poly[i])\n\t}\n\treturn result.Mod(result, baseN)\n}", "func Keygen(pub *BswabePub,msk *BswabeMsk, attrs []string) *BswabePrv {\n\t//attrs := strings.Split(attr, \" \")\n\n\tprv := new(BswabePrv)\n\tvar g_r, r, beta_inv *pbc.Element\n\tvar pairing *pbc.Pairing\n\n\t/* initialize */\n\tpairing = pub.p\n\tprv.d = pairing.NewG2()\n\tg_r = pairing.NewG2()\n\tr = pairing.NewZr()\n\tbeta_inv = pairing.NewZr()\n\n\t/* compute */\n\tr.Rand()\n\tprv.r = r.NewFieldElement().Set(r)\n\tg_r = pub.gp.NewFieldElement().Set(pub.gp)\n\t//g_r = pub.g.NewFieldElement().Set(pub.g)\n\tg_r.PowZn(g_r, r)\n\n\tprv.d = msk.g_alpha.NewFieldElement().Set(msk.g_alpha)\n\tprv.d.Mul(prv.d, g_r)\n\tbeta_inv = msk.beta.NewFieldElement().Set(msk.beta)\n\tbeta_inv.Invert(beta_inv)\n\tprv.d.PowZn(prv.d, beta_inv)\n\n\tlen := len(attrs)\n\tfor i := 0; i < len; i++ {\n\t\tcomp := new(BswabePrvComp)\n\t\tvar h_rp, rp *pbc.Element\n\n\t\tcomp.attr = attrs[i]\n\t\tcomp.d = pairing.NewG2()\n\t\tcomp.dp = pairing.NewG1()\n\t\th_rp = pairing.NewG2()\n\t\trp = pairing.NewZr()\n\n\t\telementFromString(h_rp, comp.attr)\n\t\trp.Rand()\n\n\t\th_rp.PowZn(h_rp, rp)\n\n\t\tcomp.d = g_r.NewFieldElement().Set(g_r)\n\t\tcomp.d.Mul(comp.d, h_rp)\n\t\tcomp.dp = pub.g.NewFieldElement().Set(pub.g)\n\t\tcomp.dp.PowZn(comp.dp, rp)\n\n\t\tprv.comps = append(prv.comps, comp)\n\t}\n\treturn prv\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func NewCyclicPoly(n int) *CyclicPoly {\n\tif n < 1 {\n\t\tpanic(\"argument n must be positive\")\n\t}\n\treturn &CyclicPoly{p: make([]uint64, 0, n)}\n}", "func (p Polynomial) Init(s []ed25519.Scalar) {\n\tcopy(p.coeffs, s)\n}", "func NewPolyDataMapper(nOriFeatures, iFeature, jFeature, order int) (o *PolyDataMapper) {\n\n\t// check\n\tif order < 2 {\n\t\tchk.Panic(\"PolyDataMapper is useful for order >= 2. order = %d is invalid\\n\", order)\n\t}\n\tif iFeature > nOriFeatures-1 {\n\t\tchk.Panic(\"iFeature must be within [0, %d]. iFeature = %d is invalid\\n\", nOriFeatures-1, iFeature)\n\t}\n\tif jFeature > nOriFeatures {\n\t\tchk.Panic(\"jFeature must be within [0, %d]. jFeature = %d is invalid\\n\", nOriFeatures-1, jFeature)\n\t}\n\n\t// input data\n\to = new(PolyDataMapper)\n\to.nOriFeatures = nOriFeatures\n\to.iFeature = iFeature\n\to.jFeature = jFeature\n\to.order = order\n\n\t// derived\n\tp := o.order + 1 // auxiliary\n\tnPascal := p*(p+1)/2 - 1 // -1 because first row in Pascal triangle is neglected\n\to.nExtraFeatures = nPascal - 2 // -2 because iFeature and jFeatureare were considered in nPascal already\n\treturn\n}", "func makeRenderablePoly(name string, n int, drawType uint, color vec4) *Renderable {\n\t// build poly verts\n\tvertex := makePoly(n)\n\tr := &Renderable{\n\t\tworld.Transform(),\n\t\tworld.Operation(name, &world.Poly{Points: vertex}),\n\t\tworld.MaterialComponent{\n\t\t\tDrawType: drawType,\n\t\t\tProps: map[string]interface{}{\n\t\t\t\t\"color\": world.Color(color),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn r\n}", "func newbloom(n uint64, p float64) (b Bloom) {\n\tm := math.Ceil(-float64(n) * math.Log(p) / math.Ln2 / math.Ln2)\n\tk := math.Ceil(-math.Log(p) / math.Ln2)\n\t// fmt.Printf(\"MiB %v keys %v\\n\", m/8/1024/1024, k)\n\tarrsize := (uint64(m) + 8) / 8\n\tb.bitarray = make([]uint8, arrsize)\n\tb.size = uint64(m)\n\tb.keys = make([][16]byte, int(k))\n\tfor i := 0; i < len(b.keys); i++ {\n\t\tfor j := 0; j < len(b.keys[i]); j++ {\n\t\t\tb.keys[i][j] = byte(rand.Int31n(256))\n\t\t}\n\t}\n\treturn\n}", "func (p *CubicPolynomial) Set(y0, y1, D0, D1 float64) {\n\tp.a = y0\n\tp.b = D0\n\tp.c = 3*(y1-y0) - 2*D0 - D1\n\tp.d = 2*(y0-y1) + D0 + D1\n\t// Zero out any coefficients that are small relative to the others.\n\tsum := math.Abs(p.a) + math.Abs(p.b) + math.Abs(p.c) + math.Abs(p.d)\n\tp.a = ZeroSmall(p.a, sum, epsilon)\n\tp.b = ZeroSmall(p.b, sum, epsilon)\n\tp.c = ZeroSmall(p.c, sum, epsilon)\n\tp.d = ZeroSmall(p.d, sum, epsilon)\n}", "func dividePolynomial(nn []float64 , dd []float64) (q, r []float64, ok bool) {\n \n if degree(dd) < 0 {\n return\n }\n\n nnfloat := append(r, nn...)\n \n if degree(nnfloat) >= degree(dd) {\n\n q = make([]float64, degree(nnfloat)-degree(dd)+1)\n\n for degree(nnfloat) >= degree(dd) {\n d := make([]float64, degree(nnfloat)+1)\n copy(d[degree(nnfloat)-degree(dd):], dd)\n q[degree(nnfloat)-degree(dd)] = nnfloat[degree(nnfloat)] / d[degree(d)]\n for i := range d {\n d[i] *= q[degree(nnfloat)-degree(dd)]\n nnfloat[i] -= d[i]\n }\n }\n }\n\n return q, nnfloat, true\n\n}", "func (b Binomial) Rand() float64 {\n\t// NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)\n\t// p. 295-6\n\t// http://www.aip.de/groups/soe/local/numres/bookcpdf/c7-3.pdf\n\n\trunif := rand.Float64\n\trexp := rand.ExpFloat64\n\tif b.Src != nil {\n\t\trnd := rand.New(b.Src)\n\t\trunif = rnd.Float64\n\t\trexp = rnd.ExpFloat64\n\t}\n\n\tp := b.P\n\tif p > 0.5 {\n\t\tp = 1 - p\n\t}\n\tam := b.N * p\n\n\tif b.N < 25 {\n\t\t// Use direct method.\n\t\tbnl := 0.0\n\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\tif runif() < p {\n\t\t\t\tbnl++\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\n\tif am < 1 {\n\t\t// Use rejection method with Poisson proposal.\n\t\tconst logM = 2.6e-2 // constant for rejection sampling (https://en.wikipedia.org/wiki/Rejection_sampling)\n\t\tvar bnl float64\n\t\tz := -p\n\t\tpclog := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z) // Padé approximant of log(1 + x)\n\t\tfor {\n\t\t\tbnl = 0.0\n\t\t\tt := 0.0\n\t\t\tfor i := 0; i < int(b.N); i++ {\n\t\t\t\tt += rexp()\n\t\t\t\tif t >= am {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tbnl++\n\t\t\t}\n\t\t\tbnlc := b.N - bnl\n\t\t\tz = -bnl / b.N\n\t\t\tlog1p := (1 + 0.5*z) * z / (1 + (1+1.0/6*z)*z)\n\t\t\tt = (bnlc+0.5)*log1p + bnl - bnlc*pclog + 1/(12*bnlc) - am + logM // Uses Stirling's expansion of log(n!)\n\t\t\tif rexp() >= t {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif p != b.P {\n\t\t\treturn b.N - bnl\n\t\t}\n\t\treturn bnl\n\t}\n\t// Original algorithm samples from a Poisson distribution with the\n\t// appropriate expected value. However, the Poisson approximation is\n\t// asymptotic such that the absolute deviation in probability is O(1/n).\n\t// Rejection sampling produces exact variates with at worst less than 3%\n\t// rejection with minimal additional computation.\n\n\t// Use rejection method with Cauchy proposal.\n\tg, _ := math.Lgamma(b.N + 1)\n\tplog := math.Log(p)\n\tpclog := math.Log1p(-p)\n\tsq := math.Sqrt(2 * am * (1 - p))\n\tfor {\n\t\tvar em, y float64\n\t\tfor {\n\t\t\ty = math.Tan(math.Pi * runif())\n\t\t\tem = sq*y + am\n\t\t\tif em >= 0 && em < b.N+1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tem = math.Floor(em)\n\t\tlg1, _ := math.Lgamma(em + 1)\n\t\tlg2, _ := math.Lgamma(b.N - em + 1)\n\t\tt := 1.2 * sq * (1 + y*y) * math.Exp(g-lg1-lg2+em*plog+(b.N-em)*pclog)\n\t\tif runif() <= t {\n\t\t\tif p != b.P {\n\t\t\t\treturn b.N - em\n\t\t\t}\n\t\t\treturn em\n\t\t}\n\t}\n}", "func bobKeyGenSlow(secretKey *SIDHSecretKeyBob) SIDHPublicKeyBob {\n\tvar xP, xQ, xQmP, xR, xS ProjectivePoint\n\n\txP.FromAffinePrimeField(&Affine_xPA) // = ( x_P : 1) = x(P_A)\n\txQ.FromAffinePrimeField(&Affine_xPA) //\n\txQ.X.Neg(&xQ.X) // = (-x_P : 1) = x(Q_A)\n\txQmP = DistortAndDifference(&Affine_xPA) // = x(Q_B - P_B)\n\n\txR = SecretPoint(&Affine_xPB, &Affine_yPB, secretKey.Scalar[:])\n\n\tvar currentCurve ProjectiveCurveParameters\n\t// Starting curve has a = 0, so (A:C) = (0,1)\n\tcurrentCurve.A.Zero()\n\tcurrentCurve.C.One()\n\n\tvar phi ThreeIsogeny\n\tfor e := 238; e >= 0; e-- {\n\t\txS.Pow3k(&currentCurve, &xR, uint32(e))\n\t\tcurrentCurve, phi = ComputeThreeIsogeny(&xS)\n\t\txR = phi.Eval(&xR)\n\t\txP = phi.Eval(&xP)\n\t\txQ = phi.Eval(&xQ)\n\t\txQmP = phi.Eval(&xQmP)\n\t}\n\n\tvar invZP, invZQ, invZQmP ExtensionFieldElement\n\tExtensionFieldBatch3Inv(&xP.Z, &xQ.Z, &xQmP.Z, &invZP, &invZQ, &invZQmP)\n\n\tvar publicKey SIDHPublicKeyBob\n\tpublicKey.affine_xP.Mul(&xP.X, &invZP)\n\tpublicKey.affine_xQ.Mul(&xQ.X, &invZQ)\n\tpublicKey.affine_xQmP.Mul(&xQmP.X, &invZQmP)\n\n\treturn publicKey\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func binomial(n, x int) float64 {\n\ti, f := new(big.Int), new(big.Float)\n\tbinom, _ := f.SetInt(i.Binomial(int64(n), int64(x))).Float64()\n\treturn binom\n}", "func monoCubicInterpolate(xs []float64, ys []float64) func(float64) float64 {\n\tlength := len(xs)\n\n\t// Dealing with length issues\n\tswitch {\n\tcase length != len(ys):\n\t\tpanic(errors.New(\"need an equal count of xs and ys\"))\n\tcase length == 0:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn 0\n\t\t}\n\tcase length == 1:\n\t\treturn func(x float64) (float64) {\n\t\t\treturn ys[0]\n\t\t}\n\t}\n\n\t// Get consecutive differences and slopes\n\tdys := make([]float64, length-1)\n\tdxs := make([]float64, length-1)\n\tms := make([]float64, length-1)\n\tfor i := 0; i < length-1; i++ {\n\t\tdx := xs[i+1] - xs[i]\n\t\tdy := ys[i+1] - ys[i]\n\t\tdxs[i], dys[i], ms[i] = dx, dy, dy/dx\n\t}\n\n\t// Get degree-1 coefficients\n\tc1s := make([]float64, length)\n\tc1s[0] = ms[0]\n\tfor i := 1; i < len(dxs); i++ {\n\t\tm, mNext := ms[i-1], ms[i]\n\t\tif m * mNext <= 0 {\n\t\t\tc1s[i] = 0\n\t\t} else {\n\t\t\tdx_, dxNext := dxs[i-1], dxs[i]\n\t\t\tcommon := dx_ + dxNext\n\t\t\tc1s[i] = 3 * common / ((common + dxNext)/m + (common + dx_)/mNext)\n\t\t}\n\t}\n\tc1s[length-1] = ms[len(ms)-1]\n\n\t// Get degree-2 and degree-3 coefficients\n\tc2s := make([]float64, length-1)\n\tc3s := make([]float64, length-1)\n\tfor i := 0; i < len(c1s)-1; i++ {\n\t\tc1, m_ := c1s[i], ms[i]\n\t\tinvDx, common_ := 1/dxs[i], c1 + c1s[i+1] - m_ - m_\n\t\tc2s[i] = (m_ - c1 - common_) * invDx\n\t\tc3s[i] = common_ * invDx * invDx\n\t}\n\n\t// Return interpolant function\n\treturn func(x float64) float64 {\n\t\t// The rightmost point in the dataset should give an exact result\n\t\ti := len(xs) - 1\n\t\tif x == xs[i] {\n\t\t\treturn ys[i]\n\t\t}\n\n\t\t// Search for the interval x is in, returning the corresponding y if x is one of the original xs\n\t\tlow, mid, high := 0, len(c3s)-1, len(c3s)-1\n\t\tfor low <= high {\n\t\t\tmid = int(math.Floor(0.5 * float64(low + high)))\n\t\t\txHere := xs[mid]\n\t\t\tif xHere < x {\n\t\t\t\tlow = mid + 1\n\t\t\t} else if xHere > x {\n\t\t\t\thigh = mid - 1\n\t\t\t} else {\n\t\t\t\treturn ys[mid]\n\t\t\t}\n\t\t}\n\t\ti = int(math.Max(0, float64(high)))\n\n\t\t// Interpolate\n\t\tdiff := x - xs[i]\n\t\tdiffSq := diff*diff\n\t\treturn ys[i] + c1s[i]*diff + c2s[i]*diffSq + c3s[i]*diff*diffSq\n\t}\n\n}", "func main() {\n // Parameters begin\n message := []byte(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\")\n n := 5\n // Parameters end\n \n fmt.Printf(\"{\\n\")\n // Generate key pairs\n var privates []kyber.Scalar\n var publics []kyber.Point\n for i := 0; i < n; i++ {\n // kp := key.NewKeyPair(testSuite)\n private := testSuite.Scalar().Pick(random.Stream)\n public := testSuite.Point().Mul(expand(private), nil)\n privates = append(privates, private)\n publics = append(publics, public)\n }\n\n fmt.Printf(\" privKeys: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(privates[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n fmt.Printf(\" pubKeys: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032s\\\")\", publics[i].String())\n }\n fmt.Printf(\"],\\n\")\n\n // Init masks\n var masks []*cosi.Mask\n var byteMasks [][]byte\n for i := 0; i < n; i++ {\n m, err := cosi.NewMask(testSuite, publics, publics[i])\n if err != nil {\n panic(err.Error())\n }\n masks = append(masks, m)\n byteMasks = append(byteMasks, masks[i].Mask())\n }\n\n // Compute commitments\n var v []kyber.Scalar // random\n var V []kyber.Point // commitment\n for i := 0; i < n; i++ {\n x, X := cosi.Commit(testSuite, nil)\n v = append(v, x)\n V = append(V, X)\n }\n\n fmt.Printf(\" secrets: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(v[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n fmt.Printf(\" commitments: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032s\\\")\", V[i].String())\n }\n fmt.Printf(\"],\\n\")\n\n // Aggregate commitments\n aggV, aggMask, err := cosi.AggregateCommitments(testSuite, V, byteMasks)\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\" aggCommitment: BufferUtils.fromHex(\\\"%032s\\\"),\\n\", aggV.String())\n\n // Set aggregate mask in nodes\n for i := 0; i < n; i++ {\n masks[i].SetMask(aggMask)\n }\n\n // Compute challenge\n var c []kyber.Scalar\n for i := 0; i < n; i++ {\n ci, err := cosi.Challenge(testSuite, aggV, masks[i].AggregatePublic, message)\n if err != nil {\n panic(err.Error())\n }\n c = append(c, ci)\n }\n fmt.Printf(\" aggPubKey: BufferUtils.fromHex(\\\"%032s\\\"),\\n\", masks[0].AggregatePublic.String())\n\n // Compute responses\n var r []kyber.Scalar\n for i := 0; i < n; i++ {\n ri, _ := cosi.Response(testSuite, expand(privates[i]), v[i], c[i])\n r = append(r, ri)\n }\n\n fmt.Printf(\" partialSignatures: [\")\n for i := 0; i < n; i++ {\n if i != 0 {\n fmt.Printf(\", \")\n }\n fmt.Printf(\"BufferUtils.fromHex(\\\"%032x\\\")\", reverse(r[i].Bytes()))\n }\n fmt.Printf(\"],\\n\")\n\n // Aggregate responses\n aggr, err := cosi.AggregateResponses(testSuite, r)\n if err != nil {\n panic(err.Error())\n }\n fmt.Printf(\" aggSignature: BufferUtils.fromHex(\\\"%032x\\\"),\\n\", reverse(aggr.Bytes()))\n\n for i := 0; i < n; i++ {\n // Sign\n sig, err := cosi.Sign(testSuite, aggV, aggr, masks[i])\n if err != nil {\n panic(err.Error())\n }\n // Verify (using default policy)\n if err := cosi.Verify(testSuite, publics, message, sig, nil); err != nil {\n panic(err.Error())\n }\n }\n\n fmt.Printf(\" signature: BufferUtils.fromHex(\\\"%032s%032x\\\"),\\n\", aggV.String(), reverse(aggr.Bytes()))\n fmt.Printf(\" message: BufferUtils.fromAscii(\\\"%032s\\\")\\n\", message)\n fmt.Printf(\"}\\n\")\n}", "func newPolyGF2(coeffs uint64) *polyGF2 {\n\tvar p polyGF2\n\tp.coeff.SetUint64(coeffs)\n\treturn &p\n}", "func MakeTable(poly uint32) *Table {}", "func (ks *KZG1Settings) CommitToPoly(coeffs []gmcl.Fr) *gmcl.G1 {\n\tvar out gmcl.G1\n\tgmcl.G1MulVec(&out, ks.PK[:len(coeffs)], coeffs)\n\treturn &out\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func coef(n int, t, y []Num) ([]Num, []Num) {\r\n\tsize := n + 1\r\n\ta := make([]Num, size)\r\n\th := make([]Num, size)\r\n\r\n\tfor i := 1; i <= n; i++ {\r\n\t\th[i] = t[i] - t[i-1]\r\n\t}\r\n\r\n\th[0] = h[1]\r\n\th[size] = h[n]\r\n\r\n\tdel := Num(-1)\r\n\tgam := 2 * y[0]\r\n\tp := del * gam\r\n\tq := Num(2)\r\n\r\n\tfor i := 0; i < n; i++ {\r\n\t\tr := h[i+1] / h[i]\r\n\t\tdel = Num(-1) * r * del\r\n\t\tgam = Num(-1)*gam + (r+1)*y[i]\r\n\t\tp = p + gam*del\r\n\t\tq = q + del*del\r\n\t}\r\n\r\n\ta[0] = (Num(-1) * p) / q\r\n\r\n\tfor i := 1; i < size; i++ {\r\n\t\ta[i] = ((h[i-1]+h[i])*y[i-1] - h[i]*a[i-1]) / h[i-1]\r\n\r\n\t}\r\n\r\n\treturn a[:], h[:]\r\n}", "func SetRandomPolynomial(dst *poly.Poly, degree int) {\n\t// Make all memory available to be accessed.\n\t*dst = (*dst)[:cap(*dst)]\n\n\t// Fill entire memory with random values, as even memory locations\n\t// beyond the degree can contain non zero values in practice.\n\tfor i := range *dst {\n\t\t(*dst)[i] = secp256k1.RandomFn()\n\t}\n\n\t// Ensure that the leading term is non-zero.\n\tfor dst.Coefficient(degree).IsZero() {\n\t\t(*dst)[degree] = secp256k1.RandomFn()\n\t}\n\n\t// Set degree.\n\t*dst = (*dst)[:degree+1]\n}", "func (this *NurbsCurve) regularSample(numSamples int) []CurvePoint {\n\treturn this.regularSampleRange(\n\t\tthis.knots[0], this.knots[len(this.knots)-1],\n\t\tnumSamples,\n\t)\n}", "func (s *CubicSplineSDF2) Polygonize(n int) *Polygon {\n\tp := NewPolygon()\n\tdt := float64(len(s.spline)) / float64(n-1)\n\tt := 0.0\n\tfor i := 0; i < n; i++ {\n\t\tp.AddV2(s.f0(t))\n\t\tt += dt\n\t}\n\treturn p\n}", "func newBSpline(n int, t, y []Num) *BSpline {\r\n\ts := new(BSpline)\r\n\ts.a = make([]Num, n+1)\r\n\ts.h = make([]Num, n+1)\r\n\ts.a, s.h = coef(n, t, y)\r\n\r\n\treturn s\r\n}", "func (this *NurbsCurve) adaptiveSample(tol *float64, includeU *bool) []CurvePoint {\n\tvar _tol float64\n\tif tol == nil {\n\t\t_tol = 1e-6\n\t} else {\n\t\t_tol = *tol\n\t}\n\n\tvar _includeU bool\n\tif includeU != nil {\n\t\t_includeU = *includeU\n\t}\n\n\t// if degree is 1, just return the dehomogenized control points\n\tif this.degree == 1 {\n\t\tsamples := make([]CurvePoint, len(this.controlPoints))\n\t\t// the first element of each array is the parameter\n\t\tfor i := range this.controlPoints {\n\t\t\tsamples[i] = CurvePoint{this.knots[i+1], this.controlPoints[i].Dehomogenized()}\n\t\t}\n\t\treturn samples\n\t}\n\n\treturn this.adaptiveSampleRange(this.knots[0], this.knots[len(this.knots)-1], _tol, _includeU)\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func binomdist(x, n, p float64) float64 {\n\treturn binomCoeff(n, x) * math.Pow(p, x) * math.Pow(1-p, n-x)\n}", "func MakeTable(poly uint64) *Table {}", "func (p *Poly) reduce() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = barretReduce(p[i])\n\t}\n}", "func Poly(p *sdf.Polygon, path string) error {\n\n\tvlist := p.Vertices()\n\tif vlist == nil {\n\t\treturn errors.New(\"no vertices\")\n\t}\n\n\tfmt.Printf(\"rendering %s\\n\", path)\n\td := NewDXF(path)\n\n\tfor i := 0; i < len(vlist)-1; i++ {\n\t\tp0 := vlist[i]\n\t\tp1 := vlist[i+1]\n\t\td.Line(p0, p1)\n\t}\n\n\tif p.Closed() {\n\t\tp0 := vlist[len(vlist)-1]\n\t\tp1 := vlist[0]\n\t\tif !p0.Equals(p1, tolerance) {\n\t\t\td.Line(p0, p1)\n\t\t}\n\t}\n\n\treturn d.Save()\n}", "func (phi *isogeny3) GenerateCurve(p *ProjectivePoint) CurveCoefficientsEquiv {\n\tvar t0, t1, t2, t3, t4 Fp2Element\n\tvar coefEq CurveCoefficientsEquiv\n\tvar K1, K2 = &phi.K1, &phi.K2\n\n\top := phi.Field\n\top.Sub(K1, &p.X, &p.Z) // K1 = XP3 - ZP3\n\top.Square(&t0, K1) // t0 = K1^2\n\top.Add(K2, &p.X, &p.Z) // K2 = XP3 + ZP3\n\top.Square(&t1, K2) // t1 = K2^2\n\top.Add(&t2, &t0, &t1) // t2 = t0 + t1\n\top.Add(&t3, K1, K2) // t3 = K1 + K2\n\top.Square(&t3, &t3) // t3 = t3^2\n\top.Sub(&t3, &t3, &t2) // t3 = t3 - t2\n\top.Add(&t2, &t1, &t3) // t2 = t1 + t3\n\top.Add(&t3, &t3, &t0) // t3 = t3 + t0\n\top.Add(&t4, &t3, &t0) // t4 = t3 + t0\n\top.Add(&t4, &t4, &t4) // t4 = t4 + t4\n\top.Add(&t4, &t1, &t4) // t4 = t1 + t4\n\top.Mul(&coefEq.C, &t2, &t4) // A24m = t2 * t4\n\top.Add(&t4, &t1, &t2) // t4 = t1 + t2\n\top.Add(&t4, &t4, &t4) // t4 = t4 + t4\n\top.Add(&t4, &t0, &t4) // t4 = t0 + t4\n\top.Mul(&t4, &t3, &t4) // t4 = t3 * t4\n\top.Sub(&t0, &t4, &coefEq.C) // t0 = t4 - A24m\n\top.Add(&coefEq.A, &coefEq.C, &t0) // A24p = A24m + t0\n\treturn coefEq\n}", "func initTerrain(game *gamestate) {\n\trand.New(rand.NewSource(42)) //42 best magical Constant\n\trand.Seed(time.Now().UnixNano())\n\tx := 0\n\n\ty := heightOfMap - rand.Float64()*(heightOfMap/2) // the height to start at\n\tfmt.Println(y)\n\t//standardTerrain := y\n\tvar dy float64 = 0\n\tvar dyGoal float64 = 0\n\tvar curveDensity float64 = 0\n\n\tfor x < int(mapSize) {\n\t\tif curveDensity == 0 {\n\t\t\tdyGoal = 0.5 * (-0.5 + rand.Float64())\n\t\t\tcurveDensity = 30\n\t\t}\n\t\tdy += dyGoal / 30\n\t\ty += dy\n\t\tif x == 0 {\n\t\t\tfmt.Println(int(y))\n\t\t}\n\t\tgame.Terrain[x] = genTerrain(x, int(y))\n\t\tcurveDensity--\n\t\tx++\n\t\tif y > heightOfMap-250 {\n\t\t\tdy -= 0.02\n\t\t}\n\t\tif y > heightOfMap-200 {\n\t\t\tdyGoal = -0.5\n\t\t\tdy -= 0.05\n\t\t}\n\n\t\tif y < reactionHeight+100 {\n\t\t\tdy += 0.01\n\t\t}\n\t\tif y < reactionHeight {\n\t\t\tdyGoal = 0.5\n\t\t\tdy += 0.05\n\t\t}\n\t\tif dy >= 0.33 {\n\t\t\tdy = 0.33\n\t\t}\n\t\tif dy <= -0.33 {\n\t\t\tdy = -0.33\n\t\t}\n\n\t}\n\n}", "func getcondprop(x,y int, dots []lib.Dot, dim int) float32{\n\tif len(dots) < 1{\n\t\treturn 0\n\t\treturn 0\n\t}\n\tcounty := 0\n\tcountxy := 0\n\tfor i:=0; i<len(dots); i++{\n\t\tif int(dots[i].Value) == y{\n\t\t\tcounty++\n\t\t\tif dots[i].Corordinate[dim-1] == x{\n\t\t\t\tcountxy++\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn float32(countxy)/float32(county)\n}", "func TestNegativeBinomial_PMF_CDF(t *testing.T) {\n\tvar (\n\t\tρ float64\n\t\ti, n int64\n\t)\n\n\t// edit the following values: >>>\n\tρ = 0.5\n\tn = 20\n\n\tk := []int64{10, 11, 12, 16, 25, 40}\n\tpmf := []float64{0.0186544004827737808228, 0.025437818840146064758, 0.0328571826685220003128, 0.05907974191359244287, 0.04004139896255765052, 0.00121194851197753156874}\n\tcdf := []float64{0.0493685733526945114136, 0.074806392192840576172, 0.1076635748613625764847, 0.30885965851484797895, 0.81435098276449480181, 0.9968911986703366647292}\n\n\t// <<<\n\n\tfmt.Println(\"test of NegativeBinomial PMF\")\n\tfor i = 0; i < int64(len(k)); i++ {\n\t\tprob := NegBinomialPMFAt(ρ, n, k[i])\n\t\tif !check(prob, pmf[i]) {\n\t\t\tt.Error()\n\t\t\tfmt.Println(k[i], prob, pmf[i])\n\n\t\t}\n\t}\n\n\tfmt.Println(\"test of NegativeBinomial CDF\")\n\tfor i = 0; i < int64(len(k)); i++ {\n\t\tprob := NegBinomialCDFAt(ρ, n, k[i])\n\t\tif !check(prob, cdf[i]) {\n\t\t\tt.Error()\n\t\t\tfmt.Println(k[i], prob, cdf[i])\n\t\t}\n\t}\n}", "func bzPoints(L, d int) []vec.Vector {\n\tcachedL, okL := pointsCache[L]\n\tif okL {\n\t\tcachedD, okD := cachedL[d]\n\t\tif okD {\n\t\t\treturn cachedD\n\t\t}\n\t} else {\n\t\tpointsCache[L] = make(map[int][]vec.Vector)\n\t}\n\tpoints := make([]vec.Vector, pow(L, d))\n\t// start is the minumum value of any component of a point\n\tstart := -math.Pi\n\t// (finish - step) is the maximum value of any component of a point\n\tfinish := -start\n\t// step is the separation between point components\n\tstep := (finish - start) / float64(L)\n\tk := vec.ZeroVector(d)\n\tkIndex := make([]int, d)\n\t// set initial value for k\n\tfor i := 0; i < d; i++ {\n\t\tk[i] = start\n\t\tkIndex[i] = 0\n\t}\n\t// iterate over Brillouin zone\n\tdone := false\n\tfor i := 0; !done; i++ {\n\t\tpoints[i] = vec.ZeroVector(len(k))\n\t\tcopy(points[i], k)\n\t\tdone = bzAdvance(k, kIndex, start, step, L, d)\n\t}\n\tpointsCache[L][d] = points\n\treturn points\n}", "func (p thinPoly) Zero() thinPoly {\n\tfor i := range p {\n\t\tp[i] = 0\n\t}\n\treturn p\n}", "func (mesh *PolyMesh) init() error {\n\n\tfor _, t := range mesh.Transform.Elems {\n\t\tmesh.transformSRT = append(mesh.transformSRT, m.TransformDecompMatrix4(t))\n\t}\n\n\tmesh.initTransformBounds()\n\n\tif mesh.PolyCount != nil {\n\t\tbasei := uint32(0)\n\t\tfor k := range mesh.PolyCount {\n\t\t\ti := uint32(0)\n\t\t\tfor j := 0; j < int(mesh.PolyCount[k]-2); j++ {\n\t\t\t\ti++\n\t\t\t\tmesh.idxp = append(mesh.idxp, uint32(mesh.FaceIdx[basei]))\n\t\t\t\tmesh.idxp = append(mesh.idxp, uint32(mesh.FaceIdx[basei+i]))\n\t\t\t\tmesh.idxp = append(mesh.idxp, uint32(mesh.FaceIdx[basei+i+1]))\n\n\t\t\t\tV0 := mesh.Verts.Elems[mesh.FaceIdx[basei]]\n\t\t\t\tV1 := mesh.Verts.Elems[mesh.FaceIdx[basei+i]]\n\t\t\t\tV2 := mesh.Verts.Elems[mesh.FaceIdx[basei+i+1]]\n\n\t\t\t\tif V0 == V1 && V0 == V2 {\n\t\t\t\t\t//log.Printf(\"nil triangle: %v %v %v %v %v\\n\", mesh.NodeName, mesh.FaceIdx[basei], V0, V1, V2)\n\t\t\t\t}\n\n\t\t\t\tif mesh.UV.Elems != nil {\n\t\t\t\t\tif mesh.UVIdx != nil { // if UVIdx doesn't exist assume same as FaceIdx\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.UVIdx[basei]))\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.UVIdx[basei+i]))\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.UVIdx[basei+i+1]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.FaceIdx[basei]))\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.FaceIdx[basei+i]))\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.FaceIdx[basei+i+1]))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif mesh.Normals.Elems != nil {\n\t\t\t\t\tif mesh.NormalIdx != nil { // if NormalIdx doesn't exist assume same as FaceIdx\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.NormalIdx[basei]))\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.NormalIdx[basei+i]))\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.NormalIdx[basei+i+1]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.FaceIdx[basei]))\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.FaceIdx[basei+i]))\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.FaceIdx[basei+i+1]))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif mesh.ShaderIdx != nil {\n\t\t\t\t\tmesh.shaderidx = append(mesh.shaderidx, uint8(mesh.ShaderIdx[k]))\n\t\t\t\t}\n\t\t\t}\n\t\t\tbasei += uint32(mesh.PolyCount[k])\n\t\t}\n\n\t} else {\n\t\t// Assume already a triangle mesh\n\t\tif mesh.FaceIdx != nil {\n\t\t\tfor j := range mesh.FaceIdx {\n\t\t\t\tmesh.idxp = append(mesh.idxp, uint32(mesh.FaceIdx[j]))\n\n\t\t\t\tif mesh.UV.Elems != nil {\n\t\t\t\t\tif mesh.UVIdx != nil {\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.UVIdx[j]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.FaceIdx[j]))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif mesh.Normals.Elems != nil {\n\t\t\t\t\tif mesh.NormalIdx != nil {\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.NormalIdx[j]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.FaceIdx[j]))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t} else {\n\t\t\t// No indexes so assume the vertex array is simply the triangle verts\n\t\t\tfor j := 0; j < mesh.Verts.ElemsPerKey; j++ {\n\t\t\t\tmesh.idxp = append(mesh.idxp, uint32(j))\n\n\t\t\t\tif mesh.UV.Elems != nil {\n\t\t\t\t\tif mesh.UVIdx != nil {\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(mesh.UVIdx[j]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.uvtriidx = append(mesh.uvtriidx, uint32(j))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif mesh.Normals.Elems != nil {\n\t\t\t\t\tif mesh.NormalIdx != nil {\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(mesh.NormalIdx[j]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmesh.normalidx = append(mesh.normalidx, uint32(j))\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tfor _, idx := range mesh.ShaderIdx {\n\t\t\tmesh.shaderidx = append(mesh.shaderidx, uint8(idx))\n\t\t}\n\n\t}\n\n\tmesh.FaceIdx = nil\n\tmesh.PolyCount = nil\n\tmesh.UVIdx = nil\n\tmesh.NormalIdx = nil\n\tmesh.ShaderIdx = nil\n\n\treturn nil\n}", "func StatelessRandomBinomial(scope *Scope, shape tf.Output, seed tf.Output, counts tf.Output, probs tf.Output, optional ...StatelessRandomBinomialAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"StatelessRandomBinomial\",\n\t\tInput: []tf.Input{\n\t\t\tshape, seed, counts, probs,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (p thinPoly) Inc(x []int32) thinPoly {\n\tfor i := range x {\n\t\tp[i] += x[i]\n\t}\n\treturn p\n}", "func NewPolynomialFeatures(degree int) *PolynomialFeatures {\n\treturn &PolynomialFeatures{Degree: degree, InteractionOnly: false, IncludeBias: true}\n\n}", "func PolygonOffset(factor float32, units float32) {\n C.glowPolygonOffset(gpPolygonOffset, (C.GLfloat)(factor), (C.GLfloat)(units))\n}", "func (r *Random) initBySlice(initKey []uint32) {\n\tkeyLength := uint32(len(initKey))\n\tmt := &r.state\n\tr.initGenrand(19650218)\n\tvar i, j uint32 = 1, 0\n\tvar k uint32\n\tif cN > keyLength {\n\t\tk = cN\n\t} else {\n\t\tk = keyLength\n\t}\n\tfor ; k > 0; k-- {\n\t\tmt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525)) + initKey[j] + j // non linear\n\t\ti++\n\t\tj++\n\t\tif i >= cN {\n\t\t\tmt[0] = mt[cN-1]\n\t\t\ti = 1\n\t\t}\n\t\tif j >= keyLength {\n\t\t\tj = 0\n\t\t}\n\t}\n\tfor k = cN - 1; k > 0; k-- {\n\t\tmt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941)) - i // non linear\n\t\ti++\n\t\tif i >= cN {\n\t\t\tmt[0] = mt[cN-1]\n\t\t\ti = 1\n\t\t}\n\t}\n\tmt[0] = 0x80000000 // MSB is 1; assuring non-zero initial array\n}", "func lookupPoly(blockSizeLength int) int {\n\tswitch (blockSizeLength * 8) {\n\tcase 64: return 0x1B;\n\tcase 128: return 0x87;\n\tcase 160: return 0x2D;\n\tcase 192: return 0x87;\n\tcase 224: return 0x309;\n\tcase 256: return 0x425;\n\tcase 320: return 0x1B;\n\tcase 384: return 0x100D;\n\tcase 448: return 0x851;\n\tcase 512: return 0x125;\n\tcase 768: return 0xA0011;\n\tcase 1024: return 0x80043;\n\tcase 2048: return 0x86001;\n }\n\treturn -1\n}", "func next(c Candidate, polygonals [][]int) []Candidate {\n\tret := []Candidate{}\n\tfor i := range polygonals {\n\t\tif i == c.i {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, n := range polygonals[i] {\n\t\t\tif c.p%100 == n/100 {\n\t\t\t\tret = append(ret, Candidate{p: n, i: i})\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}", "func Random(degree int) Polynomial {\n\tvar coeffs []ed25519.Scalar\n\tfor i := 0; i <= degree; i++ {\n\t\tcoeffs = append(coeffs, ed25519.Random())\n\t}\n\treturn Polynomial{coeffs}\n}", "func sub(a, b Poly) Poly {\n\tvar c Poly\n\tfor i := 0; i < n; i++ {\n\t\tc[i] = a[i] - b[i]\n\t}\n\treturn c\n}", "func AxpyLoop(c, b []float64, s float64, bc, cib, bib, blockSize int)", "func bech32Polymod(values []byte) uint32 {\n\tgenerator := []uint32{0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3}\n\tchk := uint32(1)\n\tfor _, value := range values {\n\t\ttop := chk >> 25\n\t\tchk = (chk&0x1FFFFFF)<<5 ^ uint32(value)\n\t\tfor i := 0; i < 5; i++ {\n\t\t\tif (top>>i)&1 == 1 {\n\t\t\t\tchk ^= generator[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn chk\n}", "func p256OrdSqr(res, in []uint64, n int)", "func p256OrdSqr(res, in []uint64, n int)", "func (p thinPoly) Mul(c int32, v []int32) thinPoly {\n\tfor i := range v {\n\t\tp[i] = c * v[i]\n\t}\n\treturn p.Freeze()\n}", "func WideAxpy(c, b []float64, s float64, ci, bi int)", "func (p thinPoly) Karatsuba3(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 32)\n\tvar z = make(thinPoly, 64)\n\tf0, f1 := f[:16], f[16:]\n\tg0, g1 := g[:16], g[16:]\n\n\tt.Karatsuba4(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba4(f1, g1)\n\tz[16:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[16:].Inc(z.Mul(-1, z)[:48])\n\tt.Karatsuba4(z.Add(f0, f1), z[16:].Add(g0, g1))\n\tp[16:].Inc(t)\n\n\treturn p\n}", "func MultinomialA(n int, p []float64) []int {\n\t// Setup uniform distribution\n\tK := len(p)\n\tq := make([]float64, K)\n\tJ := make([]int, K)\n\n\tvar smaller []int\n\tvar larger []int\n\tfor i, prob := range p {\n\t\tq[i] = float64(K) * prob\n\t\tif q[i] < 1.0 {\n\t\t\tsmaller = append(smaller, i)\n\t\t} else {\n\t\t\tlarger = append(larger, i)\n\t\t}\n\t}\n\n\tvar small, large int\n\tfor len(smaller) > 0 && len(larger) > 0 {\n\t\tsmall, smaller = smaller[len(smaller)-1], smaller[:len(smaller)-1]\n\t\tlarge, larger = larger[len(larger)-1], larger[:len(larger)-1]\n\n\t\tJ[small] = large\n\t\tq[large] = float64(q[large] - (1.0 - q[small]))\n\n\t\tif q[large] < 1.0 {\n\t\t\tsmaller = append(smaller, large)\n\t\t} else {\n\t\t\tlarger = append(larger, large)\n\t\t}\n\t}\n\n\t// Draw sample\n\tresult := make([]int, len(p))\n\tfor i := 0; i < n; i++ {\n\t\tkk := rand.Intn(K)\n\t\tif rand.Float64() < float64(q[kk]) {\n\t\t\tresult[kk]++\n\t\t} else {\n\t\t\tresult[J[kk]]++\n\t\t}\n\t}\n\treturn result\n}", "func Binomial(n, k int64) *big.Int {\n\treturn new(big.Int).Binomial(n, k)\n}", "func poisson(q model.Quadrilateral, r float64) []model.Vector {\n\tx0, y0 := float64(q.P1.X), float64(q.P1.Y)\n\tx1, y1 := float64(q.P3.X), float64(q.P3.Y)\n\tk := 30\n\tpoints := poissondisc.Sample(x0, y0, x1, y1, r, k, nil)\n\tvectors := make([]model.Vector, len(points))\n\tfor i, p := range points {\n\t\tvectors[i] = model.Vector{float32(p.X), float32(p.Y), 0.0}\n\t}\n\treturn vectors\n}", "func PolyInt32(a []int32, t []TermT) TermT {\n\tcount := C.uint32_t(len(a))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_int32(count, (*C.int32_t)(&a[0]), (*C.term_t)(&t[0])))\n}", "func linearMap() {\n\tdt := 1.0\n\talpha := 0.01\n\tn := 1000\n\tN := make([]float64, n)\n\n\tN[0] = 0.0001\n\n\tfor i := 1; i < n; i++ {\n\t\tN[i] = N[i-1] * (1 + alpha*dt)\n\t}\n\n\twrite(N)\n}", "func (s *Gibbs) Sample(p []float64) int {\n\tret := s.BinomialGenerator.Multinomial(1, p, len(p))\n\tfor i, v := range ret {\n\t\tif v != 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\tpanic(\"Unreachable\") // practically this part is unreachable\n}", "func penalty(b board) (p float64) {\n\tfor k := range pen {\n\t\tp += pen[k] * freq[b[k]]\n\t}\n\treturn\n}", "func Cbrt(x complex128) complex128 {\n}", "func (z *polyGF2) Mul(a, b *polyGF2) *polyGF2 {\n\tvar out *polyGF2\n\tif z != a && z != b {\n\t\tout = z\n\t} else {\n\t\tout = &polyGF2{}\n\t}\n\n\tdx := a.Degree()\n\tvar bs big.Int\n\tfor i := 0; i <= dx; i++ {\n\t\tif a.coeff.Bit(i) != 0 {\n\t\t\tbs.Lsh(&b.coeff, uint(i))\n\t\t\tout.coeff.Xor(&out.coeff, &bs)\n\t\t}\n\t}\n\n\tif z != out {\n\t\tz.coeff.Set(&out.coeff)\n\t}\n\treturn z\n}", "func CVTPL2PD(mx, x operand.Op) { ctx.CVTPL2PD(mx, x) }", "func (p *Perlin) Noise3D(x, y, z float64) float64 {\n\t// Calculate the unit cube around the coordinates\n\txi := int(x) & 255\n\tyi := int(y) & 255\n\tzi := int(z) & 255\n\n\txf := x - math.Floor(x)\n\tyf := y - math.Floor(y)\n\tzf := z - math.Floor(z)\n\n\tu := fade(xf)\n\tv := fade(yf)\n\tw := fade(zf)\n\n\taaa := p.p[p.p[p.p[xi]+yi]+zi]\n\taba := p.p[p.p[p.p[xi]+inc(yi)]+zi]\n\taab := p.p[p.p[p.p[xi]+yi]+inc(zi)]\n\tabb := p.p[p.p[p.p[xi]+inc(yi)]+inc(zi)]\n\tbaa := p.p[p.p[p.p[inc(xi)]+yi]+zi]\n\tbba := p.p[p.p[p.p[inc(xi)]+inc(yi)]+zi]\n\tbab := p.p[p.p[p.p[inc(xi)]+yi]+inc(zi)]\n\tbbb := p.p[p.p[p.p[inc(xi)]+inc(yi)]+inc(zi)]\n\n\tvar x1, x2, y1, y2 float64\n\tx1 = lerp(\n\t\tgrad(aaa, xf, yf, zf),\n\t\tgrad(baa, xf-1, yf, zf), u)\n\tx2 = lerp(\n\t\tgrad(aba, xf, yf-1, zf),\n\t\tgrad(bba, xf-1, yf-1, zf), u)\n\ty1 = lerp(x1, x2, v)\n\tx1 = lerp(\n\t\tgrad(aab, xf, yf, zf-1),\n\t\tgrad(bab, xf-1, yf, zf-1), u)\n\tx2 = lerp(\n\t\tgrad(abb, xf, yf-1, zf-1),\n\t\tgrad(bbb, xf-1, yf-1, zf-1), u)\n\ty2 = lerp(x1, x2, v)\n\n\treturn (lerp(y1, y2, w) + 1) / 2\n}", "func rcube(x, y, l int) {\n\ttx := []int{x, x + (l * 3), x, x - (l * 3), x}\n\tty := []int{y, y + (l * 2), y + (l * 4), y + (l * 2), y}\n\n\tlx := []int{x - (l * 3), x, x, x - (l * 3), x - (l * 3)}\n\tly := []int{y + (l * 2), y + (l * 4), y + (l * 8), y + (l * 6), y + (l * 2)}\n\n\trx := []int{x + (l * 3), x + (l * 3), x, x, x + (l * 3)}\n\try := []int{y + (l * 2), y + (l * 6), y + (l * 8), y + (l * 4), y + (l * 2)}\n\n\tcanvas.Polygon(tx, ty, randcolor())\n\tcanvas.Polygon(lx, ly, randcolor())\n\tcanvas.Polygon(rx, ry, randcolor())\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func (this *DtNavMeshQuery) queryPolygonsInTile(tile *DtMeshTile, qmin, qmax []float32,\n\tfilter *DtQueryFilter, query DtPolyQuery) {\n\tDtAssert(this.m_nav != nil)\n\tconst batchSize int = 32\n\tvar polyRefs [batchSize]DtPolyRef\n\tvar polys [batchSize]*DtPoly\n\tn := 0\n\n\tif tile.BvTree != nil {\n\t\tnodeIndex := 0\n\t\tendIndex := int(tile.Header.BvNodeCount)\n\t\ttbmin := tile.Header.Bmin[:]\n\t\ttbmax := tile.Header.Bmax[:]\n\t\tqfac := tile.Header.BvQuantFactor\n\n\t\t// Calculate quantized box\n\t\tvar bmin, bmax [3]uint16\n\t\t// dtClamp query box to world box.\n\t\tminx := DtClampFloat32(qmin[0], tbmin[0], tbmax[0]) - tbmin[0]\n\t\tminy := DtClampFloat32(qmin[1], tbmin[1], tbmax[1]) - tbmin[1]\n\t\tminz := DtClampFloat32(qmin[2], tbmin[2], tbmax[2]) - tbmin[2]\n\t\tmaxx := DtClampFloat32(qmax[0], tbmin[0], tbmax[0]) - tbmin[0]\n\t\tmaxy := DtClampFloat32(qmax[1], tbmin[1], tbmax[1]) - tbmin[1]\n\t\tmaxz := DtClampFloat32(qmax[2], tbmin[2], tbmax[2]) - tbmin[2]\n\t\t// Quantize\n\t\tbmin[0] = (uint16)(qfac*minx) & 0xfffe\n\t\tbmin[1] = (uint16)(qfac*miny) & 0xfffe\n\t\tbmin[2] = (uint16)(qfac*minz) & 0xfffe\n\t\tbmax[0] = (uint16)(qfac*maxx+1) | 1\n\t\tbmax[1] = (uint16)(qfac*maxy+1) | 1\n\t\tbmax[2] = (uint16)(qfac*maxz+1) | 1\n\n\t\t// Traverse tree\n\t\tbase := this.m_nav.GetPolyRefBase(tile)\n\t\tfor nodeIndex < endIndex {\n\t\t\tnode := &tile.BvTree[nodeIndex]\n\t\t\toverlap := DtOverlapQuantBounds(bmin[:], bmax[:], node.Bmin[:], node.Bmax[:])\n\t\t\tisLeafNode := (node.I >= 0)\n\n\t\t\tif isLeafNode && overlap {\n\t\t\t\tref := base | (DtPolyRef)(node.I)\n\t\t\t\tif filter.PassFilter(ref, tile, &tile.Polys[node.I]) {\n\t\t\t\t\tpolyRefs[n] = ref\n\t\t\t\t\tpolys[n] = &tile.Polys[node.I]\n\n\t\t\t\t\tif n == batchSize-1 {\n\t\t\t\t\t\tquery.Process(tile, polys[:], polyRefs[:], batchSize)\n\t\t\t\t\t\tn = 0\n\t\t\t\t\t} else {\n\t\t\t\t\t\tn++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif overlap || isLeafNode {\n\t\t\t\tnodeIndex++\n\t\t\t} else {\n\t\t\t\tescapeIndex := int(-node.I)\n\t\t\t\tnodeIndex += escapeIndex\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvar bmin, bmax [3]float32\n\t\tbase := this.m_nav.GetPolyRefBase(tile)\n\t\tfor i := 0; i < int(tile.Header.PolyCount); i++ {\n\t\t\tp := &tile.Polys[i]\n\t\t\t// Do not return off-mesh connection polygons.\n\t\t\tif p.GetType() == DT_POLYTYPE_OFFMESH_CONNECTION {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Must pass filter\n\t\t\tref := base | (DtPolyRef)(i)\n\t\t\tif !filter.PassFilter(ref, tile, p) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Calc polygon bounds.\n\t\t\tv := tile.Verts[p.Verts[0]*3:]\n\t\t\tDtVcopy(bmin[:], v)\n\t\t\tDtVcopy(bmax[:], v)\n\t\t\tfor j := 1; j < int(p.VertCount); j++ {\n\t\t\t\tv = tile.Verts[p.Verts[j]*3:]\n\t\t\t\tDtVmin(bmin[:], v)\n\t\t\t\tDtVmax(bmax[:], v)\n\t\t\t}\n\t\t\tif DtOverlapBounds(qmin, qmax, bmin[:], bmax[:]) {\n\t\t\t\tpolyRefs[n] = ref\n\t\t\t\tpolys[n] = p\n\n\t\t\t\tif n == batchSize-1 {\n\t\t\t\t\tquery.Process(tile, polys[:], polyRefs[:], batchSize)\n\t\t\t\t\tn = 0\n\t\t\t\t} else {\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Process the last polygons that didn't make a full batch.\n\tif n > 0 {\n\t\tquery.Process(tile, polys[:], polyRefs[:], n)\n\t}\n}", "func BinomPiDiffCrI(postdiffmu, postdiffsigma, alpha float64) (float64, float64) {\n\t// postdiffmu\t\tposterior mean for difference of normal means\n\t// postdiffsigma\tposterior standard deviation for difference of normal means\n\t// alpha\t\t\tposterior probability that the true mean lies outside the credible interval\n\n\tz := ZQtlFor(alpha / 2)\n\tlow := postdiffmu - z*postdiffsigma\n\thigh := postdiffmu + z*postdiffsigma\n\treturn low, high\n}" ]
[ "0.657556", "0.58865243", "0.56174225", "0.55272275", "0.5338543", "0.5262446", "0.5153678", "0.50309294", "0.50292194", "0.5004865", "0.49390826", "0.49338847", "0.488069", "0.4877766", "0.4768621", "0.47478262", "0.47200382", "0.4699926", "0.46465135", "0.4619948", "0.46084625", "0.45972618", "0.45504895", "0.4534576", "0.4518679", "0.45105183", "0.44966453", "0.44942313", "0.4486797", "0.4478873", "0.44774914", "0.44770387", "0.44757012", "0.44725105", "0.44722867", "0.44459262", "0.44256943", "0.43984953", "0.43933576", "0.43930084", "0.43757054", "0.43660834", "0.436518", "0.4356899", "0.4348441", "0.43382218", "0.43152383", "0.4309979", "0.428359", "0.42802876", "0.42659983", "0.42553374", "0.42486563", "0.42419836", "0.42340907", "0.422127", "0.42181474", "0.4201334", "0.41977715", "0.4182436", "0.41819754", "0.41790342", "0.41789287", "0.41712457", "0.4170145", "0.41587943", "0.4155587", "0.41536552", "0.41348433", "0.4130025", "0.41252097", "0.41238406", "0.41217792", "0.4118992", "0.4118936", "0.41179043", "0.40906963", "0.4087757", "0.4080742", "0.40777776", "0.40725082", "0.40725082", "0.40694514", "0.4065705", "0.40637076", "0.40619862", "0.4058936", "0.40574268", "0.40492147", "0.40399656", "0.4036873", "0.40332454", "0.4027883", "0.40242833", "0.40223435", "0.40184355", "0.4016103", "0.40051574", "0.40025163", "0.39955506" ]
0.70405465
0
polyBaseMul multiplies two polynomials
func polyBaseMul(a, b Poly) Poly { var r Poly for i := 0; i < n/4; i++ { copy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i])) copy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i])) } return r }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (z *polyGF2) Mul(a, b *polyGF2) *polyGF2 {\n\tvar out *polyGF2\n\tif z != a && z != b {\n\t\tout = z\n\t} else {\n\t\tout = &polyGF2{}\n\t}\n\n\tdx := a.Degree()\n\tvar bs big.Int\n\tfor i := 0; i <= dx; i++ {\n\t\tif a.coeff.Bit(i) != 0 {\n\t\t\tbs.Lsh(&b.coeff, uint(i))\n\t\t\tout.coeff.Xor(&out.coeff, &bs)\n\t\t}\n\t}\n\n\tif z != out {\n\t\tz.coeff.Set(&out.coeff)\n\t}\n\treturn z\n}", "func (z *Perplex) Mul(x, y *Perplex) *Perplex {\n\ta := new(big.Int).Set(&x.l)\n\tb := new(big.Int).Set(&x.r)\n\tc := new(big.Int).Set(&y.l)\n\td := new(big.Int).Set(&y.r)\n\ttemp := new(big.Int)\n\tz.l.Add(\n\t\tz.l.Mul(a, c),\n\t\ttemp.Mul(d, b),\n\t)\n\tz.r.Add(\n\t\tz.r.Mul(d, a),\n\t\ttemp.Mul(b, c),\n\t)\n\treturn z\n}", "func (z *polyGF2) Add(a, b *polyGF2) *polyGF2 {\n\tz.coeff.Xor(&a.coeff, &b.coeff)\n\treturn z\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func (ec *EC) BaseMul(x *big.Int) *Point {\n\treturn ec.Mul(x, ec.G)\n}", "func (z *polyGF2) MulX(a *polyGF2, n int) *polyGF2 {\n\tif n < 0 {\n\t\tpanic(\"power must be >= 0\")\n\t}\n\tz.coeff.Lsh(&a.coeff, uint(n))\n\treturn z\n}", "func (self *State)Pow(a,b any)any{\n self.IncOperations(self.coeff[\"pow\"]+self.off[\"pow\"])\n return wrap2(a,b,math.Pow)\n}", "func (p thinPoly) Mul(c int32, v []int32) thinPoly {\n\tfor i := range v {\n\t\tp[i] = c * v[i]\n\t}\n\treturn p.Freeze()\n}", "func Mul(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_mul(C.term_t(t1), C.term_t(t2)))\n}", "func feMul(out *fieldElement, a *fieldElement, b *fieldElement)", "func basicMul(z, x, y nat) {\n\tz[0 : len(x)+len(y)].clear() // initialize z\n\tfor i, d := range y {\n\t\tif d != 0 {\n\t\t\tz[len(x)+i] = addMulVVW(z[i:i+len(x)], x, d)\n\t\t}\n\t}\n}", "func (z *BiComplex) Mul(x, y *BiComplex) *BiComplex {\n\ta := new(Complex).Set(&x.l)\n\tb := new(Complex).Set(&x.r)\n\tc := new(Complex).Set(&y.l)\n\td := new(Complex).Set(&y.r)\n\ttemp := new(Complex)\n\tz.l.Sub(\n\t\tz.l.Mul(a, c),\n\t\ttemp.Mul(b, d),\n\t)\n\tz.r.Add(\n\t\tz.r.Mul(a, d),\n\t\ttemp.Mul(b, c),\n\t)\n\treturn z\n}", "func DoubleScalarDoubleBaseMulPrecomputed(output *ExtendedGroupElement, s1, s2 *Key, table *PRECOMPUTE_TABLE) {\n\n\tvar c CompletedGroupElement\n\tvar p ProjectiveGroupElement\n\n\tvar output_bytes Key\n\t_ = output_bytes\n\n\toutput.Zero()\n\tp.Zero()\n\n\tfor i := 31; i >= 0; i-- {\n\n\t\t// we are processing 4 bits at a time\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\t//c.ToProjective(&p)\n\t\tc.ToExtended(output)\n\n\t\t{ // process high nibble first\n\t\t\tpoint := ((s1[i] >> 4) & 0xf) | (((s2[i] >> 4) & 0xf) << 4)\n\n\t\t\tgeAdd(&c, output, &table[point])\n\t\t\t//c.ToExtended(output)\n\t\t\tc.ToProjective(&p)\n\t\t}\n\n\t\t// again 4 bits at a time\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\t//c.ToProjective(&p)\n\t\tc.ToExtended(output)\n\n\t\t{ // process low nibble now\n\t\t\tpoint := ((s1[i]) & 0xf) | (((s2[i]) & 0xf) << 4)\n\t\t\t//fmt.Printf(\"%d lpoint %d\\n\",i, point )\n\t\t\tgeAdd(&c, output, &table[point])\n\t\t\tc.ToExtended(output)\n\t\t}\n\t\t//output.ToBytes(&output_bytes)\n\n\t\t//fmt.Printf(\"%d output %s\\n\", i,output_bytes)\n\n\t\toutput.ToProjective(&p) // for doubling\n\n\t}\n\n}", "func (p Poly64) Plus(q Poly64) Poly64 {\n\treturn p ^ q\n}", "func (curve p256Curve) CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int) {\n\tscalarReversed := make([]uint64, 4)\n\tvar r1, r2 p256Point\n\tp256GetScalar(scalarReversed, baseScalar)\n\tr1IsInfinity := scalarIsZero(scalarReversed)\n\tr1.p256BaseMult(scalarReversed)\n\n\tp256GetScalar(scalarReversed, scalar)\n\tr2IsInfinity := scalarIsZero(scalarReversed)\n\tfromBig(r2.xyz[0:4], maybeReduceModP(bigX))\n\tfromBig(r2.xyz[4:8], maybeReduceModP(bigY))\n\tp256Mul(r2.xyz[0:4], r2.xyz[0:4], rr[:])\n\tp256Mul(r2.xyz[4:8], r2.xyz[4:8], rr[:])\n\n\t// This sets r2's Z value to 1, in the Montgomery domain.\n//\tr2.xyz[8] = 0x0000000000000001\n//\tr2.xyz[9] = 0xffffffff00000000\n//\tr2.xyz[10] = 0xffffffffffffffff\n//\tr2.xyz[11] = 0x00000000fffffffe\n\tr2.xyz[8] = 0x0000000000000001\n\tr2.xyz[9] = 0x00000000FFFFFFFF\n\tr2.xyz[10] = 0x0000000000000000\n\tr2.xyz[11] = 0x0000000100000000\n\n\t//r2.p256ScalarMult(scalarReversed)\n\t//p256PointAddAsm(r1.xyz[:], r1.xyz[:], r2.xyz[:])\n\n\tr2.p256ScalarMult(scalarReversed)\n\n\tvar sum, double p256Point\n\tpointsEqual := p256PointAddAsm(sum.xyz[:], r1.xyz[:], r2.xyz[:])\n\tp256PointDoubleAsm(double.xyz[:], r1.xyz[:])\n\tsum.CopyConditional(&double, pointsEqual)\n\tsum.CopyConditional(&r1, r2IsInfinity)\n\tsum.CopyConditional(&r2, r1IsInfinity)\n\treturn sum.p256PointToAffine()\n}", "func (n *bigNumber) mul(x *bigNumber, y *bigNumber) *bigNumber {\n\t//it does not work in place, that why the temporary bigNumber is necessary\n\treturn karatsubaMul(n, x, y)\n}", "func p256Mul(res, in1, in2 []uint64)", "func p256Mul(res, in1, in2 []uint64)", "func (z *Big) Mul(x, y *Big) *Big { return z.Context.Mul(z, x, y) }", "func Mul(x, y Number) Number {\n\treturn Number{\n\t\tReal: x.Real * y.Real,\n\t\tE1mag: x.Real*y.E1mag + x.E1mag*y.Real,\n\t\tE2mag: x.Real*y.E2mag + x.E2mag*y.Real,\n\t\tE1E2mag: x.Real*y.E1E2mag + x.E1mag*y.E2mag + x.E2mag*y.E1mag + x.E1E2mag*y.Real,\n\t}\n}", "func mult(f1, f2, p []complex128) {\n\tfor idx := range f1 {\n\t\tp[idx] = f1[idx] * f2[idx]\n\t}\n}", "func CurveParamsScalarBaseMult(curve *elliptic.CurveParams, k []byte) (*big.Int, *big.Int)", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func basicMul(z, x, y fermat) {\n\t// initialize z\n\tfor i := 0; i < len(z); i++ {\n\t\tz[i] = 0\n\t}\n\tfor i, d := range y {\n\t\tif d != 0 {\n\t\t\tz[len(x)+i] = addMulVVW(z[i:i+len(x)], x, d)\n\t\t}\n\t}\n}", "func (z *E12) Mul(x, y *E12) *E12 {\n\tvar a, b, c E6\n\ta.Add(&x.C0, &x.C1)\n\tb.Add(&y.C0, &y.C1)\n\ta.Mul(&a, &b)\n\tb.Mul(&x.C0, &y.C0)\n\tc.Mul(&x.C1, &y.C1)\n\tz.C1.Sub(&a, &b).Sub(&z.C1, &c)\n\tz.C0.MulByNonResidue(&c).Add(&z.C0, &b)\n\treturn z\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func productOf(a, b bigCombination) bigCombination {\n\ta.numeratorTerms = append(a.numeratorTerms, b.numeratorTerms...)\n\ta.denominatorTerms = append(a.denominatorTerms, b.denominatorTerms...)\n\treturn a\n}", "func (p Polynomial) Eval(arg int) ed25519.Scalar {\n\tx := ed25519.New_scalar(*big.NewInt(int64(arg)))\n\tresult := p.coeffs[0].Add(p.coeffs[1].Mul(x))\n\tx_pow := x.Copy()\n\tfor i := 2; i < len(p.coeffs); i++ {\n\t\tx_pow = x_pow.Mul(x)\n\t\tresult = result.Add(p.coeffs[i].Mul(x_pow))\n\t}\n\treturn result\n}", "func (p thinPoly) x4Mul(f, g thinPoly) thinPoly {\n\tp.Zero()\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tp[i+j] += Freeze(f[i] * g[j])\n\t\t}\n\t}\n\treturn p\n}", "func Multiply(a cty.Value, b cty.Value) (cty.Value, error) {\n\treturn MultiplyFunc.Call([]cty.Value{a, b})\n}", "func Mul(z, x, y *Elt)", "func PolyMpq(q []MpqT, t []TermT) TermT {\n\tcount := C.uint32_t(len(q))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpqp(count, (*C.mpq_t)(&q[0]), (*C.term_t)(&t[0])))\n}", "func (p Point2) Mul(ps ...Point2) Point2 {\n\tfor _, p2 := range ps {\n\t\tp[0] *= p2[0]\n\t\tp[1] *= p2[1]\n\t}\n\treturn p\n}", "func (z *E6) Mul(x, y *E6) *E6 {\n\t// Algorithm 13 from https://eprint.iacr.org/2010/354.pdf\n\tvar t0, t1, t2, c0, c1, c2, tmp E2\n\tt0.Mul(&x.B0, &y.B0)\n\tt1.Mul(&x.B1, &y.B1)\n\tt2.Mul(&x.B2, &y.B2)\n\n\tc0.Add(&x.B1, &x.B2)\n\ttmp.Add(&y.B1, &y.B2)\n\tc0.Mul(&c0, &tmp).Sub(&c0, &t1).Sub(&c0, &t2).MulByNonResidue(&c0).Add(&c0, &t0)\n\n\tc1.Add(&x.B0, &x.B1)\n\ttmp.Add(&y.B0, &y.B1)\n\tc1.Mul(&c1, &tmp).Sub(&c1, &t0).Sub(&c1, &t1)\n\ttmp.MulByNonResidue(&t2)\n\tc1.Add(&c1, &tmp)\n\n\ttmp.Add(&x.B0, &x.B2)\n\tc2.Add(&y.B0, &y.B2).Mul(&c2, &tmp).Sub(&c2, &t0).Sub(&c2, &t2).Add(&c2, &t1)\n\n\tz.B0.Set(&c0)\n\tz.B1.Set(&c1)\n\tz.B2.Set(&c2)\n\n\treturn z\n}", "func rcMul(p *TCompiler, code *TCode) (*value.Value, error) {\n\tv := value.Mul(p.regGet(code.B), p.regGet(code.C))\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func MulAdd128(x, y, c uint64) (z1, z0 uint64) {\n\t// Split x and y into 2 halfwords each, multiply\n\t// the halfwords separately while avoiding overflow,\n\t// and return the product as 2 words.\n\n\tconst (\n\t\tW\t= uint(unsafe.Sizeof(x)) * 8;\n\t\tW2\t= W / 2;\n\t\tB2\t= 1 << W2;\n\t\tM2\t= B2 - 1;\n\t)\n\n\t// TODO(gri) Should implement special cases for faster execution.\n\n\t// general case\n\t// sub-digits of x, y, and c are (x1, x0), (y1, y0), (c1, c0)\n\t// x = (x1*B2 + x0)\n\t// y = (y1*B2 + y0)\n\tx1, x0 := x>>W2, x&M2;\n\ty1, y0 := y>>W2, y&M2;\n\tc1, c0 := c>>W2, c&M2;\n\n\t// x*y + c = t2*B2*B2 + t1*B2 + t0\n\tt0 := x0*y0 + c0;\n\tt1 := x1*y0 + x0*y1 + c1;\n\tt2 := x1 * y1;\n\n\t// compute result digits but avoid overflow\n\t// z = z[1]*B + z[0] = x*y\n\tz0 = t1<<W2 + t0;\n\tz1 = t2 + (t1+t0>>W2)>>W2;\n\treturn;\n}", "func (g *Graph) Mul(x1 Node, x2 Node) Node {\n\treturn g.NewOperator(fn.NewMul(x1, x2), x1, x2)\n}", "func Pow(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.Pow(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.PowOf(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.PowOfR(a, opts...)\n\t}\n\tpanic(\"Unreachable\")\n}", "func (a *Array64) Pow(b *Array64) *Array64 {\n\tif a.valRith(b, \"Pow\") {\n\t\treturn a\n\t}\n\n\tif b.shape[len(b.shape)-1] == a.shape[len(a.shape)-1] {\n\t\tlna, lnb := len(a.data), len(b.data)\n\t\tfor i, j := 0, 0; i < lna; i, j = i+1, j+1 {\n\t\t\tif j >= lnb {\n\t\t\t\tj = 0\n\t\t\t}\n\t\t\ta.data[i] = math.Pow(a.data[i], b.data[j])\n\t\t}\n\t\treturn a\n\t}\n\n\tst := a.strides[len(a.strides)-1] * a.shape[len(a.shape)-1]\n\tfor i := 0; i < len(b.data); i++ {\n\t\tfor j := i * st; j < (i+1)*st; j++ {\n\t\t\ta.data[j] = math.Pow(a.data[j], b.data[i])\n\t\t}\n\t}\n\treturn a\n}", "func (z *Float64) Mul(x, y *Float64) *Float64 {\n\ta := (x.l * y.l) + (y.r * x.r)\n\tb := (x.r * y.l) + (y.r * x.l)\n\tz.SetPair(a, b)\n\treturn z\n}", "func p256OrdMul(res, in1, in2 []uint64)", "func p256OrdMul(res, in1, in2 []uint64)", "func (z *Int) Mul(x, y *Int) {\n\n\tvar (\n\t\talfa = &Int{} // Aggregate results\n\t\tbeta = &Int{} // Calculate intermediate\n\t)\n\t// The numbers are internally represented as [ a, b, c, d ]\n\t// We do the following operations\n\t//\n\t// d1 * d2\n\t// d1 * c2 (upshift 64)\n\t// d1 * b2 (upshift 128)\n\t// d1 * a2 (upshift 192)\n\t//\n\t// c1 * d2 (upshift 64)\n\t// c1 * c2 (upshift 128)\n\t// c1 * b2 (upshift 192)\n\t//\n\t// b1 * d2 (upshift 128)\n\t// b1 * c2 (upshift 192)\n\t//\n\t// a1 * d2 (upshift 192)\n\t//\n\t// And we aggregate results into 'alfa'\n\n\t// One optimization, however, is reordering.\n\t// For these ones, we don't care about if they overflow, thus we can use native multiplication\n\t// and set the result immediately into `a` of the result.\n\t// b1 * c2 (upshift 192)\n\t// a1 * d2 (upshift 192)\n\t// d1 * a2 (upshift 192)\n\t// c1 * b2 11(upshift 192)\n\n\t// Remaining ops:\n\t//\n\t// d1 * d2\n\t// d1 * c2 (upshift 64)\n\t// d1 * b2 (upshift 128)\n\t//\n\t// c1 * d2 (upshift 64)\n\t// c1 * c2 (upshift 128)\n\t//\n\t// b1 * d2 (upshift 128)\n\n\talfa.mulIntoLower128(x[0], y[0])\n\talfa.mulIntoUpper128(x[0], y[2])\n\talfa[3] += x[0]*y[3] + x[1]*y[2] + x[2]*y[1] + x[3]*y[0] // Top ones, ignore overflow\n\n\tbeta.mulIntoMiddle128(x[0], y[1])\n\talfa.Add(alfa, beta)\n\n\tbeta.Clear().mulIntoMiddle128(x[1], y[0])\n\talfa.Add(alfa, beta)\n\n\tbeta.Clear().mulIntoUpper128(x[1], y[1])\n\talfa.addHigh128(beta[3], beta[2])\n\n\tbeta.Clear().mulIntoUpper128(x[2], y[0])\n\talfa.addHigh128(beta[3], beta[2])\n\tz.Copy(alfa)\n\n}", "func pointwiseMulAdd(b, e0, e1 [constN]ringelt) [constN]ringelt {\n\tvar v [constN]ringelt\n\tfor i := 0; i < constN; i++ {\n\t\tv[i] = mulMOD(e0[i], b[i])\n\t\tv[i] = addMOD(v[i], e1[i])\n\t}\n\treturn v\n}", "func (z *Rat) Mul(x, y *Rat) *Rat {}", "func (z *Int) Mul(x, y *Int) *Int {}", "func (x Rational) Multiply(y Rational) Rational {\n\treturn NewRational(x.numerator*y.numerator, x.denominator*y.denominator)\n}", "func VGF2P8MULB(ops ...operand.Op) { ctx.VGF2P8MULB(ops...) }", "func mul(x byte, y byte) byte {\n\tif x == 0 || y == 0 {\n\t\treturn 0\n\t}\n\treturn expOp[logOp[x]+logOp[y]]\n}", "func Mul128(x, y uint64) (z1, z0 uint64) {\n\t// Split x and y into 2 halfwords each, multiply\n\t// the halfwords separately while avoiding overflow,\n\t// and return the product as 2 words.\n\n\tconst (\n\t\tW\t= uint(unsafe.Sizeof(x)) * 8;\n\t\tW2\t= W / 2;\n\t\tB2\t= 1 << W2;\n\t\tM2\t= B2 - 1;\n\t)\n\n\tif x < y {\n\t\tx, y = y, x\n\t}\n\n\tif x < B2 {\n\t\t// y < B2 because y <= x\n\t\t// sub-digits of x and y are (0, x) and (0, y)\n\t\t// z = z[0] = x*y\n\t\tz0 = x * y;\n\t\treturn;\n\t}\n\n\tif y < B2 {\n\t\t// sub-digits of x and y are (x1, x0) and (0, y)\n\t\t// x = (x1*B2 + x0)\n\t\t// y = (y1*B2 + y0)\n\t\tx1, x0 := x>>W2, x&M2;\n\n\t\t// x*y = t2*B2*B2 + t1*B2 + t0\n\t\tt0 := x0 * y;\n\t\tt1 := x1 * y;\n\n\t\t// compute result digits but avoid overflow\n\t\t// z = z[1]*B + z[0] = x*y\n\t\tz0 = t1<<W2 + t0;\n\t\tz1 = (t1 + t0>>W2) >> W2;\n\t\treturn;\n\t}\n\n\t// general case\n\t// sub-digits of x and y are (x1, x0) and (y1, y0)\n\t// x = (x1*B2 + x0)\n\t// y = (y1*B2 + y0)\n\tx1, x0 := x>>W2, x&M2;\n\ty1, y0 := y>>W2, y&M2;\n\n\t// x*y = t2*B2*B2 + t1*B2 + t0\n\tt0 := x0 * y0;\n\tt1 := x1*y0 + x0*y1;\n\tt2 := x1 * y1;\n\n\t// compute result digits but avoid overflow\n\t// z = z[1]*B + z[0] = x*y\n\tz0 = t1<<W2 + t0;\n\tz1 = t2 + (t1+t0>>W2)>>W2;\n\treturn;\n}", "func IntMul(z *big.Int, x, y *big.Int,) *big.Int", "func (v1 Vector2) Mul(v2 Vector2) Vector2 {\n\tv1.MulThis(v2)\n\treturn v1\n}", "func (a *Mtx) Mult(b *Mtx) *Mtx {\n\tm := Mtx{}\n\tfor i := 0; i < 4; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\tm.el[j][i] += a.el[k][i] * b.el[j][k]\n\t\t\t}\n\t\t}\n\t}\n\treturn &m\n}", "func Command_Mul(script *rex.Script, params []*rex.Value) {\n\tif len(params) != 2 {\n\t\trex.ErrorParamCount(\"float:mul\", \"2\")\n\t}\n\n\tscript.RetVal = rex.NewValueFloat64(params[0].Float64() * params[1].Float64())\n\treturn\n}", "func RatMul(z *big.Rat, x, y *big.Rat,) *big.Rat", "func (ai *Arith) Mul(decimal1 *ZnDecimal, others ...*ZnDecimal) *ZnDecimal {\n\t// init result from decimal1\n\tvar result = copyZnDecimal(decimal1)\n\tif len(others) == 0 {\n\t\treturn result\n\t}\n\n\tfor _, item := range others {\n\t\tresult.co.Mul(result.co, item.co)\n\t\tresult.exp = result.exp + item.exp\n\t}\n\n\treturn result\n}", "func DoubleScalarDoubleBaseMulPrecomputed64(output *ExtendedGroupElement, s1, s2 []Key, table []PRECOMPUTE_TABLE) {\n\n\tif len(s1) != 64 || len(s2) != 64 || len(table) != 64 {\n\t\tpanic(\"DoubleScalarDoubleBaseMulPrecomputed64 requires 64 members\")\n\t}\n\tvar c CompletedGroupElement\n\tvar p ProjectiveGroupElement\n\n\tvar output_bytes Key\n\t_ = output_bytes\n\n\toutput.Zero()\n\tp.Zero()\n\n\tfor i := 31; i >= 0; i-- {\n\n\t\t// we are processing 4 bits at a time\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\t//c.ToProjective(&p)\n\t\tc.ToExtended(output)\n\n\t\tfor j := 0; j < 64; j++ { // process high nibble first\n\t\t\tpoint := ((s1[j][i] >> 4) & 0xf) | (((s2[j][i] >> 4) & 0xf) << 4)\n\t\t\tif point != 0 { // skip if point is zero\n\t\t\t\tgeAdd(&c, output, &table[j][point])\n\t\t\t\tc.ToExtended(output)\n\t\t\t}\n\n\t\t}\n\t\tc.ToProjective(&p)\n\n\t\t// again 4 bits at a time\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\tc.ToProjective(&p)\n\t\tp.Double(&c)\n\t\t//c.ToProjective(&p)\n\t\tc.ToExtended(output)\n\n\t\tfor j := 0; j < 64; j++ { // process low nibble now\n\t\t\tpoint := ((s1[j][i]) & 0xf) | (((s2[j][i]) & 0xf) << 4)\n\t\t\tif point != 0 { // skip if point is zero\n\t\t\t\t//fmt.Printf(\"%d lpoint %d\\n\",i, point )\n\t\t\t\tgeAdd(&c, output, &table[j][point])\n\t\t\t\tc.ToExtended(output)\n\t\t\t}\n\t\t}\n\t\t//output.ToBytes(&output_bytes)\n\n\t\t//fmt.Printf(\"%d output %s\\n\", i,output_bytes)\n\n\t\toutput.ToProjective(&p) // for doubling\n\n\t}\n\n}", "func sub(a, b Poly) Poly {\n\tvar c Poly\n\tfor i := 0; i < n; i++ {\n\t\tc[i] = a[i] - b[i]\n\t}\n\treturn c\n}", "func Mul(x, y meta.ConstValue) meta.ConstValue {\n\tswitch x.Type {\n\tcase meta.Integer:\n\t\tswitch y.Type {\n\t\tcase meta.Integer:\n\t\t\treturn meta.NewIntConst(x.GetInt() * y.GetInt())\n\t\tcase meta.Float:\n\t\t\treturn meta.NewFloatConst(float64(x.GetInt()) * y.GetFloat())\n\t\t}\n\tcase meta.Float:\n\t\tswitch y.Type {\n\t\tcase meta.Integer:\n\t\t\treturn meta.NewFloatConst(x.GetFloat() * float64(y.GetInt()))\n\t\tcase meta.Float:\n\t\t\treturn meta.NewFloatConst(x.GetFloat() * y.GetFloat())\n\t\t}\n\t}\n\treturn meta.UnknownValue\n}", "func (z *polyGF2) Sub(a, b *polyGF2) *polyGF2 {\n\treturn z.Add(a, b)\n}", "func (z *Perplex) Sub(x, y *Perplex) *Perplex {\n\tz.l.Sub(&x.l, &y.l)\n\tz.r.Sub(&x.r, &y.r)\n\treturn z\n}", "func superPow(a int, b []int) int {\n\tif len(b) < 1 {\n\t\treturn 1\n\t}\n\n\tbase := 1337\n\n\t// (a*b)%k = (a%k)(b%k)%k\n\tmypow := func(a, k int) int {\n\t\t// k is between [0, 10]\n\t\tres := 1\n\n\t\t// may overflow\n\t\t// for i := 0; i < k; i++ {\n\t\t// \ttmp := a % base\n\t\t// \tres *= tmp\n\t\t// }\n\n\t\ttmp := a % base\n\t\tfor i := 0; i < k; i++ {\n\t\t\tres *= tmp\n\t\t\tres %= base\n\t\t}\n\n\t\treturn res\n\t}\n\n\t// a^1234 = a^4 * a^123^10\n\tlast := b[len(b)-1]\n\tb = b[:len(b)-1]\n\n\t// part1 = ((a^last)%base) % base\n\tpart1 := mypow(a, last)\n\tpart2 := mypow(superPow(a, b), 10)\n\n\treturn part1 * part2 % base\n}", "func MULPS(mx, x operand.Op) { ctx.MULPS(mx, x) }", "func (v Posit8x4) Mul(x Posit8x4) Posit8x4 {\n\tout := Posit8x4{impl: make([]Posit8, 4)}\n\tfor i, posit := range v.impl {\n\t\tout.impl[i] = posit.Mul(x.impl[i])\n\t}\n\treturn out\n}", "func MULPD(mx, x operand.Op) { ctx.MULPD(mx, x) }", "func (p *Int64) Mul(q, r *Int64) *Int64 {\n\tx := new(Int64).Set(q)\n\ty := new(Int64).Set(r)\n\tz := NewInt64()\n\tvar l uint64\n\tfor n, a := range x.c {\n\t\tfor m, b := range y.c {\n\t\t\tl = n + m\n\t\t\tif coeff, ok := z.Coeff(l); ok {\n\t\t\t\tz.SetCoeff(l, coeff+(a*b))\n\t\t\t} else {\n\t\t\t\tz.SetCoeff(l, a*b)\n\t\t\t}\n\t\t}\n\t}\n\treturn p.Set(z)\n}", "func (f *Float) Mul(x, y *Float) *Float {\n\tx.doinit()\n\ty.doinit()\n\tf.doinit()\n\tC.mpf_mul(&f.i[0], &x.i[0], &y.i[0])\n\treturn f\n}", "func (z *E2) Mul(x, y *E2) *E2 {\n\tmulGenericE2(z, x, y)\n\treturn z\n}", "func (t1 *Tensor) Multiply(t2 *Tensor) (*Tensor, error) {\n\tif t1.Size.Z != t2.Size.Z || t1.Size.X != t2.Size.Y {\n\t\treturn nil, ErrDimensionsNotFit\n\t}\n\tret := NewTensor(t2.Size.X, t1.Size.Y, t1.Size.Z)\n\tfor z := 0; z < t1.Size.Z; z++ {\n\t\tfor y := 0; y < t1.Size.Y; y++ {\n\t\t\tfor x := 0; x < t2.Size.X; x++ {\n\t\t\t\tvar e float64\n\t\t\t\tfor i := 0; i < t1.Size.X; i++ {\n\t\t\t\t\te += t1.Get(i, y, z) * t2.Get(x, i, z)\n\t\t\t\t}\n\t\t\t\tret.Set(x, y, z, e)\n\t\t\t}\n\t\t}\n\t}\n\treturn ret, nil\n}", "func Pow(base []uint8, exp uint64) []uint8 {\n\tvar result []uint8 = base\n\n\tfor i := exp - 1; i != 0; i-- {\n\t\tresult = Product(result, base)\n\t}\n\treturn result\n}", "func (c curve) CombinedMult(Qx, Qy *big.Int, m, n []byte) (Px, Py *big.Int) {\n\tconst nOmega = uint(5)\n\tvar k big.Int\n\tk.SetBytes(m)\n\tnafM := math.OmegaNAF(&k, baseOmega)\n\tk.SetBytes(n)\n\tnafN := math.OmegaNAF(&k, nOmega)\n\n\tif len(nafM) > len(nafN) {\n\t\tnafN = append(nafN, make([]int32, len(nafM)-len(nafN))...)\n\t} else if len(nafM) < len(nafN) {\n\t\tnafM = append(nafM, make([]int32, len(nafN)-len(nafM))...)\n\t}\n\n\tTabQ := newAffinePoint(Qx, Qy).oddMultiples(nOmega)\n\tvar P, jR jacobianPoint\n\tvar aR affinePoint\n\tfor i := len(nafN) - 1; i >= 0; i-- {\n\t\tP.double()\n\t\t// Generator point\n\t\tif nafM[i] != 0 {\n\t\t\tidxM := absolute(nafM[i]) >> 1\n\t\t\taR = baseOddMultiples[idxM]\n\t\t\tif nafM[i] < 0 {\n\t\t\t\taR.neg()\n\t\t\t}\n\t\t\tP.mixadd(&P, &aR)\n\t\t}\n\t\t// Input point\n\t\tif nafN[i] != 0 {\n\t\t\tidxN := absolute(nafN[i]) >> 1\n\t\t\tjR = TabQ[idxN]\n\t\t\tif nafN[i] < 0 {\n\t\t\t\tjR.neg()\n\t\t\t}\n\t\t\tP.add(&P, &jR)\n\t\t}\n\t}\n\treturn P.toAffine().toInt()\n}", "func (r1cs *R1CS) mulWireByCoeff(res *fr.Element, t r1c.Term) *fr.Element {\n\tcoeffValue := t.CoeffValue()\n\tswitch coeffValue {\n\tcase 1:\n\t\treturn res\n\tcase -1:\n\t\treturn res.Neg(res)\n\tcase 0:\n\t\treturn res.SetZero()\n\tcase 2:\n\t\treturn res.Double(res)\n\tdefault:\n\t\treturn res.Mul(res, &r1cs.Coefficients[t.CoeffID()])\n\t}\n}", "func mul(m ast.Mul, isparam map[ast.Variable]bool) (Operation, error) {\n\t// Expect the second operand to always be a variable.\n\tif _, ok := m.Y.(ast.Variable); !ok {\n\t\treturn nil, errutil.AssertionFailure(\"expect second multiply operand to be variable\")\n\t}\n\n\t// Check for a const multiply.\n\tif c, ok := m.X.(ast.Constant); ok {\n\t\treturn ConstMul(c), nil\n\t}\n\n\t// Check for parameter multiply.\n\tif v, ok := m.X.(ast.Variable); ok && isparam[v] {\n\t\treturn ParamMul(v), nil\n\t}\n\n\tif v, ok := m.Y.(ast.Variable); ok && isparam[v] {\n\t\treturn ParamMul(v), nil\n\t}\n\n\t// Fallback to a generic multiply.\n\treturn Mul{}, nil\n}", "func (s *Scalar) Multiply(x, y *Scalar) *Scalar {\n\ts.s.Mul(&x.s, &y.s)\n\treturn s\n}", "func (parser *Parser) pow() (*SubExpr, error) {\n\tparser.trace(\"POW\")\n\tdefer parser.untrace()\n\n\tnot_expr, err := parser.not_expr()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpow_op, op, err := parser.pow_op()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pow_op == nil {\n\t\treturn not_expr, nil\n\t}\n\n\treturn NewExprSubExpr(NewExpr(op, not_expr, pow_op)), nil\n}", "func (v1 Vector2) Mul(c float32) Vector2 {\n\treturn Vector2{v1.X * c, v1.Y * c}\n}", "func CurveParamsScalarMult(curve *elliptic.CurveParams, Bx, By *big.Int, k []byte) (*big.Int, *big.Int)", "func superPow(a int, b []int) int {\n \n}", "func (a *BigFloatComplex) Mul(b *BigFloatComplex) *BigFloatComplex {\n\tt1 := new(big.Float).Set(a.r)\n\tt1.Mul(t1, b.r)\n\n\tt2 := new(big.Float).Set(a.i)\n\tt2.Mul(t2, b.i)\n\n\tt1.Sub(t1, t2)\n\n\tt3 := new(big.Float).Set(a.r)\n\tt3.Mul(t3, b.i)\n\n\tt4 := new(big.Float).Set(a.i)\n\tt4.Mul(t4, b.r)\n\n\tt3.Add(t3, t4)\n\n\ta.r.Set(t1)\n\ta.i.Set(t3)\n\treturn a\n}", "func AddOpMul(jl *JSONLogic) {\n\tjl.AddOperation(\"*\", opMul)\n}", "func CarryMul(out1 *TightFieldElement, arg1 *LooseFieldElement, arg2 *LooseFieldElement) {\n\tvar x1 uint64\n\tvar x2 uint64\n\tx2, x1 = bits.Mul64(arg1[2], (arg2[2] * 0x5))\n\tvar x3 uint64\n\tvar x4 uint64\n\tx4, x3 = bits.Mul64(arg1[2], (arg2[1] * 0xa))\n\tvar x5 uint64\n\tvar x6 uint64\n\tx6, x5 = bits.Mul64(arg1[1], (arg2[2] * 0xa))\n\tvar x7 uint64\n\tvar x8 uint64\n\tx8, x7 = bits.Mul64(arg1[2], arg2[0])\n\tvar x9 uint64\n\tvar x10 uint64\n\tx10, x9 = bits.Mul64(arg1[1], (arg2[1] * 0x2))\n\tvar x11 uint64\n\tvar x12 uint64\n\tx12, x11 = bits.Mul64(arg1[1], arg2[0])\n\tvar x13 uint64\n\tvar x14 uint64\n\tx14, x13 = bits.Mul64(arg1[0], arg2[2])\n\tvar x15 uint64\n\tvar x16 uint64\n\tx16, x15 = bits.Mul64(arg1[0], arg2[1])\n\tvar x17 uint64\n\tvar x18 uint64\n\tx18, x17 = bits.Mul64(arg1[0], arg2[0])\n\tvar x19 uint64\n\tvar x20 uint64\n\tx19, x20 = bits.Add64(x5, x3, uint64(0x0))\n\tvar x21 uint64\n\tx21, _ = bits.Add64(x6, x4, uint64(uint1(x20)))\n\tvar x23 uint64\n\tvar x24 uint64\n\tx23, x24 = bits.Add64(x17, x19, uint64(0x0))\n\tvar x25 uint64\n\tx25, _ = bits.Add64(x18, x21, uint64(uint1(x24)))\n\tx27 := ((x23 >> 44) | ((x25 << 20) & 0xffffffffffffffff))\n\tx28 := (x23 & 0xfffffffffff)\n\tvar x29 uint64\n\tvar x30 uint64\n\tx29, x30 = bits.Add64(x9, x7, uint64(0x0))\n\tvar x31 uint64\n\tx31, _ = bits.Add64(x10, x8, uint64(uint1(x30)))\n\tvar x33 uint64\n\tvar x34 uint64\n\tx33, x34 = bits.Add64(x13, x29, uint64(0x0))\n\tvar x35 uint64\n\tx35, _ = bits.Add64(x14, x31, uint64(uint1(x34)))\n\tvar x37 uint64\n\tvar x38 uint64\n\tx37, x38 = bits.Add64(x11, x1, uint64(0x0))\n\tvar x39 uint64\n\tx39, _ = bits.Add64(x12, x2, uint64(uint1(x38)))\n\tvar x41 uint64\n\tvar x42 uint64\n\tx41, x42 = bits.Add64(x15, x37, uint64(0x0))\n\tvar x43 uint64\n\tx43, _ = bits.Add64(x16, x39, uint64(uint1(x42)))\n\tvar x45 uint64\n\tvar x46 uint64\n\tx45, x46 = bits.Add64(x27, x41, uint64(0x0))\n\tx47 := (uint64(uint1(x46)) + x43)\n\tx48 := ((x45 >> 43) | ((x47 << 21) & 0xffffffffffffffff))\n\tx49 := (x45 & 0x7ffffffffff)\n\tvar x50 uint64\n\tvar x51 uint64\n\tx50, x51 = bits.Add64(x48, x33, uint64(0x0))\n\tx52 := (uint64(uint1(x51)) + x35)\n\tx53 := ((x50 >> 43) | ((x52 << 21) & 0xffffffffffffffff))\n\tx54 := (x50 & 0x7ffffffffff)\n\tx55 := (x53 * 0x5)\n\tx56 := (x28 + x55)\n\tx57 := (x56 >> 44)\n\tx58 := (x56 & 0xfffffffffff)\n\tx59 := (x57 + x49)\n\tx60 := uint1((x59 >> 43))\n\tx61 := (x59 & 0x7ffffffffff)\n\tx62 := (uint64(x60) + x54)\n\tout1[0] = x58\n\tout1[1] = x61\n\tout1[2] = x62\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func Mul(a, b Expr) Expr {\n\treturn &mulOp{&simpleOperator{a, b, scanner.MUL}}\n}", "func (x f26dot6) mul(y f26dot6) f26dot6 {\n\treturn f26dot6(int64(x) * int64(y) >> 6)\n}", "func lmulFR(w *wideFr, a, b *Fr) {\n\t// Handbook of Applied Cryptography\n\t// Hankerson, Menezes, Vanstone\n\t// 14.12 Algorithm Multiple-precision multiplication\n\n\tvar w0, w1, w2, w3, w4, w5, w6, w7 uint64\n\tvar a0 = a[0]\n\tvar a1 = a[1]\n\tvar a2 = a[2]\n\tvar a3 = a[3]\n\tvar b0 = b[0]\n\tvar b1 = b[1]\n\tvar b2 = b[2]\n\tvar b3 = b[3]\n\tvar u, v, c, t uint64\n\n\t// i = 0, j = 0\n\tc, w0 = bits.Mul64(a0, b0)\n\n\t// i = 0, j = 1\n\tu, v = bits.Mul64(a1, b0)\n\tw1 = v + c\n\tc = u + (v&c|(v|c)&^w1)>>63\n\n\t// i = 0, j = 2\n\tu, v = bits.Mul64(a2, b0)\n\tw2 = v + c\n\tc = u + (v&c|(v|c)&^w2)>>63\n\n\t// i = 0, j = 3\n\tu, v = bits.Mul64(a3, b0)\n\tw3 = v + c\n\tw4 = u + (v&c|(v|c)&^w3)>>63\n\n\t//\n\t// i = 1, j = 0\n\tc, v = bits.Mul64(a0, b1)\n\tt = v + w1\n\tc += (v&w1 | (v|w1)&^t) >> 63\n\tw1 = t\n\n\t// i = 1, j = 1\n\tu, v = bits.Mul64(a1, b1)\n\tt = v + w2\n\tu += (v&w2 | (v|w2)&^t) >> 63\n\tw2 = t + c\n\tc = u + (t&c|(t|c)&^w2)>>63\n\n\t// i = 1, j = 2\n\tu, v = bits.Mul64(a2, b1)\n\tt = v + w3\n\tu += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t + c\n\tc = u + (t&c|(t|c)&^w3)>>63\n\n\t// i = 1, j = 3\n\tu, v = bits.Mul64(a3, b1)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tw5 = u + (t&c|(t|c)&^w4)>>63\n\n\t//\n\t// i = 2, j = 0\n\tc, v = bits.Mul64(a0, b2)\n\tt = v + w2\n\tc += (v&w2 | (v|w2)&^t) >> 63\n\tw2 = t\n\n\t// i = 2, j = 1\n\tu, v = bits.Mul64(a1, b2)\n\tt = v + w3\n\tu += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t + c\n\tc = u + (t&c|(t|c)&^w3)>>63\n\n\t// i = 2, j = 2\n\tu, v = bits.Mul64(a2, b2)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tc = u + (t&c|(t|c)&^w4)>>63\n\n\t// i = 2, j = 3\n\tu, v = bits.Mul64(a3, b2)\n\tt = v + w5\n\tu += (v&w5 | (v|w5)&^t) >> 63\n\tw5 = t + c\n\tw6 = u + (t&c|(t|c)&^w5)>>63\n\n\t//\n\t// i = 3, j = 0\n\tc, v = bits.Mul64(a0, b3)\n\tt = v + w3\n\tc += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t\n\n\t// i = 3, j = 1\n\tu, v = bits.Mul64(a1, b3)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tc = u + (t&c|(t|c)&^w4)>>63\n\n\t// i = 3, j = 2\n\tu, v = bits.Mul64(a2, b3)\n\tt = v + w5\n\tu += (v&w5 | (v|w5)&^t) >> 63\n\tw5 = t + c\n\tc = u + (t&c|(t|c)&^w5)>>63\n\n\t// i = 3, j = 3\n\tu, v = bits.Mul64(a3, b3)\n\tt = v + w6\n\tu += (v&w6 | (v|w6)&^t) >> 63\n\tw6 = t + c\n\tw7 = u + (t&c|(t|c)&^w6)>>63\n\n\tw[0] = w0\n\tw[1] = w1\n\tw[2] = w2\n\tw[3] = w3\n\tw[4] = w4\n\tw[5] = w5\n\tw[6] = w6\n\tw[7] = w7\n}", "func NewMaterialPolynomial(c ...float64) Material {\n\treturn MaterialPolynomial{factors: c}\n}", "func (s *server) Multiply(ctx context.Context, request *proto.Request) (*proto.Response, error) {\n\n\t//user the getters from the proto package we imported again.\n\ta := request.GetA()\n\tb := request.GetB()\n\n\tresult := a * b\n\n\treturn &proto.Response{Result: result}, nil\n\n}", "func CarryMul(out1 *TightFieldElement, arg1 *LooseFieldElement, arg2 *LooseFieldElement) {\n\tx1 := (uint64(arg1[4]) * uint64((arg2[4] * 0x5)))\n\tx2 := (uint64(arg1[4]) * uint64((arg2[3] * 0x5)))\n\tx3 := (uint64(arg1[4]) * uint64((arg2[2] * 0x5)))\n\tx4 := (uint64(arg1[4]) * uint64((arg2[1] * 0x5)))\n\tx5 := (uint64(arg1[3]) * uint64((arg2[4] * 0x5)))\n\tx6 := (uint64(arg1[3]) * uint64((arg2[3] * 0x5)))\n\tx7 := (uint64(arg1[3]) * uint64((arg2[2] * 0x5)))\n\tx8 := (uint64(arg1[2]) * uint64((arg2[4] * 0x5)))\n\tx9 := (uint64(arg1[2]) * uint64((arg2[3] * 0x5)))\n\tx10 := (uint64(arg1[1]) * uint64((arg2[4] * 0x5)))\n\tx11 := (uint64(arg1[4]) * uint64(arg2[0]))\n\tx12 := (uint64(arg1[3]) * uint64(arg2[1]))\n\tx13 := (uint64(arg1[3]) * uint64(arg2[0]))\n\tx14 := (uint64(arg1[2]) * uint64(arg2[2]))\n\tx15 := (uint64(arg1[2]) * uint64(arg2[1]))\n\tx16 := (uint64(arg1[2]) * uint64(arg2[0]))\n\tx17 := (uint64(arg1[1]) * uint64(arg2[3]))\n\tx18 := (uint64(arg1[1]) * uint64(arg2[2]))\n\tx19 := (uint64(arg1[1]) * uint64(arg2[1]))\n\tx20 := (uint64(arg1[1]) * uint64(arg2[0]))\n\tx21 := (uint64(arg1[0]) * uint64(arg2[4]))\n\tx22 := (uint64(arg1[0]) * uint64(arg2[3]))\n\tx23 := (uint64(arg1[0]) * uint64(arg2[2]))\n\tx24 := (uint64(arg1[0]) * uint64(arg2[1]))\n\tx25 := (uint64(arg1[0]) * uint64(arg2[0]))\n\tx26 := (x25 + (x10 + (x9 + (x7 + x4))))\n\tx27 := (x26 >> 26)\n\tx28 := (uint32(x26) & 0x3ffffff)\n\tx29 := (x21 + (x17 + (x14 + (x12 + x11))))\n\tx30 := (x22 + (x18 + (x15 + (x13 + x1))))\n\tx31 := (x23 + (x19 + (x16 + (x5 + x2))))\n\tx32 := (x24 + (x20 + (x8 + (x6 + x3))))\n\tx33 := (x27 + x32)\n\tx34 := (x33 >> 26)\n\tx35 := (uint32(x33) & 0x3ffffff)\n\tx36 := (x34 + x31)\n\tx37 := (x36 >> 26)\n\tx38 := (uint32(x36) & 0x3ffffff)\n\tx39 := (x37 + x30)\n\tx40 := (x39 >> 26)\n\tx41 := (uint32(x39) & 0x3ffffff)\n\tx42 := (x40 + x29)\n\tx43 := uint32((x42 >> 26))\n\tx44 := (uint32(x42) & 0x3ffffff)\n\tx45 := (uint64(x43) * uint64(0x5))\n\tx46 := (uint64(x28) + x45)\n\tx47 := uint32((x46 >> 26))\n\tx48 := (uint32(x46) & 0x3ffffff)\n\tx49 := (x47 + x35)\n\tx50 := uint1((x49 >> 26))\n\tx51 := (x49 & 0x3ffffff)\n\tx52 := (uint32(x50) + x38)\n\tout1[0] = x48\n\tout1[1] = x51\n\tout1[2] = x52\n\tout1[3] = x41\n\tout1[4] = x44\n}", "func Multiply(a float64, b float64) float64 {\n return a*b;\n}", "func Pow(valueA gcv.Value, valueB gcv.Value) gcv.Value {\n\tif valueA.Type() == gcv.Complex || valueB.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Pow(valueA.Complex(), valueB.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Pow(valueA.Real(), valueB.Real()))\n}", "func _mulGeneric(z, x, y *Element) {\n\n\tvar t [12]uint64\n\tvar c [3]uint64\n\t{\n\t\t// round 0\n\t\tv := x[0]\n\t\tc[1], c[0] = bits.Mul64(v, y[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd1(v, y[1], c[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[2], c[1])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[3], c[1])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[4], c[1])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[5], c[1])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[6], c[1])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[7], c[1])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[8], c[1])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[9], c[1])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[10], c[1])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd1(v, y[11], c[1])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 1\n\t\tv := x[1]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 2\n\t\tv := x[2]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 3\n\t\tv := x[3]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 4\n\t\tv := x[4]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 5\n\t\tv := x[5]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 6\n\t\tv := x[6]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 7\n\t\tv := x[7]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 8\n\t\tv := x[8]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 9\n\t\tv := x[9]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 10\n\t\tv := x[10]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], t[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], t[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], t[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], t[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], t[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], t[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], t[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], t[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], t[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], t[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tt[11], t[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\t{\n\t\t// round 11\n\t\tv := x[11]\n\t\tc[1], c[0] = madd1(v, y[0], t[0])\n\t\tm := c[0] * 744663313386281181\n\t\tc[2] = madd0(m, 17626244516597989515, c[0])\n\t\tc[1], c[0] = madd2(v, y[1], c[1], t[1])\n\t\tc[2], z[0] = madd2(m, 16614129118623039618, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[2], c[1], t[2])\n\t\tc[2], z[1] = madd2(m, 1588918198704579639, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[3], c[1], t[3])\n\t\tc[2], z[2] = madd2(m, 10998096788944562424, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[4], c[1], t[4])\n\t\tc[2], z[3] = madd2(m, 8204665564953313070, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[5], c[1], t[5])\n\t\tc[2], z[4] = madd2(m, 9694500593442880912, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[6], c[1], t[6])\n\t\tc[2], z[5] = madd2(m, 274362232328168196, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[7], c[1], t[7])\n\t\tc[2], z[6] = madd2(m, 8105254717682411801, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[8], c[1], t[8])\n\t\tc[2], z[7] = madd2(m, 5945444129596489281, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[9], c[1], t[9])\n\t\tc[2], z[8] = madd2(m, 13341377791855249032, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[10], c[1], t[10])\n\t\tc[2], z[9] = madd2(m, 15098257552581525310, c[2], c[0])\n\t\tc[1], c[0] = madd2(v, y[11], c[1], t[11])\n\t\tz[11], z[10] = madd3(m, 81882988782276106, c[0], c[2], c[1])\n\t}\n\n\t// if z > q --> z -= q\n\t// note: this is NOT constant time\n\tif !(z[11] < 81882988782276106 || (z[11] == 81882988782276106 && (z[10] < 15098257552581525310 || (z[10] == 15098257552581525310 && (z[9] < 13341377791855249032 || (z[9] == 13341377791855249032 && (z[8] < 5945444129596489281 || (z[8] == 5945444129596489281 && (z[7] < 8105254717682411801 || (z[7] == 8105254717682411801 && (z[6] < 274362232328168196 || (z[6] == 274362232328168196 && (z[5] < 9694500593442880912 || (z[5] == 9694500593442880912 && (z[4] < 8204665564953313070 || (z[4] == 8204665564953313070 && (z[3] < 10998096788944562424 || (z[3] == 10998096788944562424 && (z[2] < 1588918198704579639 || (z[2] == 1588918198704579639 && (z[1] < 16614129118623039618 || (z[1] == 16614129118623039618 && (z[0] < 17626244516597989515))))))))))))))))))))))) {\n\t\tvar b uint64\n\t\tz[0], b = bits.Sub64(z[0], 17626244516597989515, 0)\n\t\tz[1], b = bits.Sub64(z[1], 16614129118623039618, b)\n\t\tz[2], b = bits.Sub64(z[2], 1588918198704579639, b)\n\t\tz[3], b = bits.Sub64(z[3], 10998096788944562424, b)\n\t\tz[4], b = bits.Sub64(z[4], 8204665564953313070, b)\n\t\tz[5], b = bits.Sub64(z[5], 9694500593442880912, b)\n\t\tz[6], b = bits.Sub64(z[6], 274362232328168196, b)\n\t\tz[7], b = bits.Sub64(z[7], 8105254717682411801, b)\n\t\tz[8], b = bits.Sub64(z[8], 5945444129596489281, b)\n\t\tz[9], b = bits.Sub64(z[9], 13341377791855249032, b)\n\t\tz[10], b = bits.Sub64(z[10], 15098257552581525310, b)\n\t\tz[11], _ = bits.Sub64(z[11], 81882988782276106, b)\n\t}\n}", "func (wv *Spectrum) Mul(other Spectrum) {\n\t// if wv.Lambda != other.Lambda IS ERROR\n\twv.C[0] *= other.C[0]\n\twv.C[1] *= other.C[1]\n\twv.C[2] *= other.C[2]\n\twv.C[3] *= other.C[3]\n}", "func ADDSUBPD(mx, x operand.Op) { ctx.ADDSUBPD(mx, x) }", "func (t *Dense) Pow(other *Dense, opts ...FuncOpt) (retVal *Dense, err error) {\n\n\tvar ret Tensor\n\tif t.oe != nil {\n\t\tif ret, err = t.oe.Pow(t, other, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do Pow()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"Pow\")\n\t\t}\n\t\treturn\n\t}\n\n\tif power, ok := t.e.(Power); ok {\n\t\tif ret, err = power.Pow(t, other, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do Pow()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"Pow\")\n\t\t}\n\t\treturn\n\t}\n\treturn nil, errors.Errorf(\"Engine does not support Pow()\")\n}", "func (a *BigRatComplex) Mul(b *BigRatComplex) *BigRatComplex {\n\tt1 := new(big.Rat).Set(a.r)\n\tt1.Mul(t1, b.r)\n\n\tt2 := new(big.Rat).Set(a.i)\n\tt2.Mul(t2, b.i)\n\n\tt1.Sub(t1, t2)\n\n\tt3 := new(big.Rat).Set(a.r)\n\tt3.Mul(t3, b.i)\n\n\tt4 := new(big.Rat).Set(a.i)\n\tt4.Mul(t4, b.r)\n\n\tt3.Add(t3, t4)\n\n\ta.r.Set(t1)\n\ta.i.Set(t3)\n\treturn a\n}", "func VFMSUBADD231PS(ops ...operand.Op) { ctx.VFMSUBADD231PS(ops...) }", "func MulInto(ctx *build.Context, z, x, y ir.Int) {\n\tacc := NewAccumulator(ctx, z)\n\tfor i, a := range x.Limbs() {\n\t\tfor j, b := range y.Limbs() {\n\t\t\tlo, hi := ctx.Register(\"lo\"), ctx.Register(\"hi\")\n\t\t\tctx.MUL(a, b, hi, lo)\n\t\t\tacc.AddProduct(hi, lo, i+j)\n\t\t}\n\t\tacc.Flush()\n\t}\n}", "func VFMSUBADD213PS(ops ...operand.Op) { ctx.VFMSUBADD213PS(ops...) }", "func (a Vec2) Mul(b Vec2) Vec2 {\n\treturn Vec2{a.X * b.X, a.Y * b.Y}\n}" ]
[ "0.71954125", "0.610846", "0.5975032", "0.5905304", "0.5821955", "0.58080727", "0.5807356", "0.5800249", "0.57425517", "0.57225454", "0.5719369", "0.5698124", "0.56932354", "0.5620182", "0.5613475", "0.55791473", "0.55630285", "0.55251", "0.55251", "0.55130064", "0.5494358", "0.54839337", "0.5443313", "0.5405032", "0.5395138", "0.53876066", "0.5383222", "0.5377768", "0.5351399", "0.53014606", "0.52973765", "0.5297183", "0.52952296", "0.5290729", "0.5284845", "0.5267552", "0.526605", "0.52629536", "0.52610373", "0.5254296", "0.52485925", "0.5241341", "0.5241341", "0.5232313", "0.522655", "0.5211744", "0.5207859", "0.5206388", "0.51998544", "0.5181628", "0.51733893", "0.515863", "0.51573217", "0.5152679", "0.5151683", "0.5148363", "0.5140565", "0.51228976", "0.51200116", "0.5117791", "0.51145786", "0.51117045", "0.5106887", "0.5106091", "0.51029134", "0.5099353", "0.5096148", "0.50878716", "0.50743383", "0.5071218", "0.5069709", "0.50627863", "0.5052191", "0.50476086", "0.50470966", "0.50410795", "0.50220656", "0.5021691", "0.5018627", "0.50182617", "0.5017517", "0.5014796", "0.50076437", "0.49997157", "0.4998789", "0.49966693", "0.4996183", "0.49790654", "0.49656546", "0.49588755", "0.49531057", "0.4942003", "0.49336892", "0.49332345", "0.49310654", "0.49187326", "0.49186108", "0.49112228", "0.49084663", "0.4905454" ]
0.8326899
0
tomont converts a poly to its montgomery representation
func (p *Poly) toMont() { var f int16 = int16((uint64(1) << 32) % uint64(q)) for i := 0; i < n; i++ { p[i] = montgomeryReduce(int32(p[i]) * int32(f)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func toomEval(p int, f, g *[768]int32) []int32 {\n\ta := make(thinPoly, 128)\n\tb := make(thinPoly, 128)\n\tt := make(thinPoly, 128)\n\n\tfor i,v := range toomEvalCoeffs[p] {\n\t\ta.Inc(t.Mul(v, f[i*128:(i+1)*128]))\n\t\tb.Inc(t.Mul(v, g[i*128:(i+1)*128]))\n\t}\n\n\treturn make(thinPoly, 256).Karatsuba1(a.Freeze(), b.Freeze())\n}", "func PolyMpq(q []MpqT, t []TermT) TermT {\n\tcount := C.uint32_t(len(q))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpqp(count, (*C.mpq_t)(&q[0]), (*C.term_t)(&t[0])))\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func toomInterpolate(points [][]int32, param []int32) []int32 {\n\tt := make(thinPoly, 256)\n\tu := make(thinPoly, 256)\n\n\tfor i := range points {\n\t\tt.Inc(u.Mul(param[i], points[i]))\n\t}\n\n\treturn t.Freeze()\n}", "func makeRenderablePoly(name string, n int, drawType uint, color vec4) *Renderable {\n\t// build poly verts\n\tvertex := makePoly(n)\n\tr := &Renderable{\n\t\tworld.Transform(),\n\t\tworld.Operation(name, &world.Poly{Points: vertex}),\n\t\tworld.MaterialComponent{\n\t\t\tDrawType: drawType,\n\t\t\tProps: map[string]interface{}{\n\t\t\t\t\"color\": world.Color(color),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn r\n}", "func (o *OctahedronGeometry) JSObject() *js.Object { return o.p }", "func (curve *EdCurve) ToMontgomeryPointForm1(sqrtB *big.Int, p *EcPoint) (p1, p2 *EcPoint) {\n\toneSubY := new(big.Int).Sub(ONE, p.Y) // 1-y\n\toneAddY := new(big.Int).Add(ONE, p.Y) // 1+y\n\tp1, p2 = NewPoint(), NewPoint()\n\tp1.X = ModFraction(oneAddY, oneSubY, curve.P) // (1+y)/(1-y)\n\tp1.Y = ModFraction(p1.X, p.X, curve.P) // u/x\n\tp1.Y.Mul(p1.Y, sqrtB) // sqrtB * u/x\n\tp1.Y.Mod(p1.Y, curve.P)\n\n\tp2.X = ModFraction(oneSubY, oneAddY, curve.P) // (1-y)/(1+y)\n\tp2.Y = ModFraction(p2.X, p.X, curve.P) // u/x\n\tp2.Y.Mul(p2.Y, sqrtB) // sqrtB * u/x\n\tp2.Y.Mod(p2.Y, curve.P)\n\treturn\n}", "func (r thinPoly) Toom6(f, g *[768]int32) thinPoly {\n\tvar e = [][]int32 {\n\t\tmake(thinPoly, 256).Karatsuba1(f[0:128], g[0:128]),\n\t\ttoomEval(+1, f, g),\n\t\ttoomEval(-1, f, g),\n\t\ttoomEval(+2, f, g),\n\t\ttoomEval(-2, f, g),\n\t\ttoomEval(+3, f, g),\n\t\ttoomEval(-3, f, g),\n\t\ttoomEval(+4, f, g),\n\t\ttoomEval(-4, f, g),\n\t\ttoomEval(+5, f, g),\n\t\tmake(thinPoly, 256).Karatsuba1(f[640:768], g[640:768]),\n\t}\n\tvar c = [][]int32 {\n\t\te[0],\n\t\ttoomInterpolate(e, toomParam[0]),\n\t\ttoomInterpolate(e, toomParam[1]),\n\t\ttoomInterpolate(e, toomParam[2]),\n\t\ttoomInterpolate(e, toomParam[3]),\n\t\ttoomInterpolate(e, toomParam[4]),\n\t\ttoomInterpolate(e, toomParam[5]),\n\t\ttoomInterpolate(e, toomParam[6]),\n\t\ttoomInterpolate(e, toomParam[7]),\n\t\ttoomInterpolate(e, toomParam[8]),\n\t\te[10],\n\t}\n\n\tcopy(r[:128], c[0])\n\tr[128:].Add(c[0][128:], c[1][:128])\n\tr[256:].Add(c[1][128:], c[2][:128])\n\tr[384:].Add(c[2][128:], c[3][:128])\n\tr[512:].Add(c[3][128:], c[4][:128])\n\tr[640:].Add(c[4][128:], c[5][:128])\n\tr[768:].Add(c[5][128:], c[6][:128])\n\tr[896:].Add(c[6][128:], c[7][:128])\n\tr[1024:].Add(c[7][128:], c[8][:128])\n\tr[1152:].Add(c[8][128:], c[9][:128])\n\tr[1280:].Add(c[9][128:], c[10][:128])\n\tcopy(r[1408:], c[10][128:])\n\n\treturn r\n}", "func (p Poly) Marshal(buf []byte, rem int) ([]byte, int, error) {\n\tbuf, rem, err := surge.MarshalLen(uint32(len(p)), buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.MarshalLen(uint32(cap(p)), buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tfor _, c := range p {\n\t\tbuf, rem, err = c.Marshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func (this *Poly) setType(t int) {\n\tthis.areaAndtype = (this.areaAndtype & 0x3f) | (t << 6)\n}", "func (rot *RotationMatrix) rotate(pt *Vertex) Vertex {\n\t//Get the org for this pt\n\tptOrg := rot.getPtOrg(pt)\n\n\t//Now get this pt relative to the pt org\n\trelPt := pt.minus(&ptOrg)\n\n\t//Now rotate it\n\tvar rotatPt Vertex\n\n\tfor i := 0; i < len(rot.matrix); i++ {\n\t\tfor j := 0; j < len(rot.matrix[i]); j++ {\n\t\t\trotatPt[i] += rot.matrix[i][j] * relPt[j]\n\t\t}\n\t}\n\n\t//Now add the ptOrg back to the point\n\trotatPt.addTo(&ptOrg)\n\n\treturn rotatPt\n\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func MakeTable(poly uint64) *Table {}", "func (z *E12) ToMont() *E12 {\n\tz.C0.ToMont()\n\tz.C1.ToMont()\n\treturn z\n}", "func boxToPoly(b Box2d) polygon {\n\tcen_x, cen_y := b.Position()\n\twidth, height := b.Size()\n\tangle := b.AngleDegrees()\n\n\tpoints := [4]point{}\n\n\tpoints[0] = point{X: getX(-width/2, -height/2, angle) + cen_x,\n\t\tY: getY(-width/2, -height/2, angle) + cen_y}\n\n\tpoints[1] = point{X: getX(width/2, -height/2, angle) + cen_x,\n\t\tY: getY(width/2, -height/2, angle) + cen_y}\n\n\tpoints[2] = point{X: getX(-width/2, height/2, angle) + cen_x,\n\t\tY: getY(-width/2, height/2, angle) + cen_y}\n\n\tpoints[3] = point{X: getX(width/2, height/2, angle) + cen_x,\n\t\tY: getY(width/2, height/2, angle) + cen_y}\n\tz := boxPoly{points: points[:4]}\n\n\treturn z\n}", "func (p thinPoly) Karatsuba1(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 128)\n\tvar z = make(thinPoly, 256)\n\tf0, f1 := f[:64], f[64:]\n\tg0, g1 := g[:64], g[64:]\n\n\tt.Karatsuba2(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba2(f1, g1)\n\tz[64:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[64:].Inc(z.Mul(-1, z)[:192])\n\tt.Karatsuba2(z.Add(f0, f1), z[64:].Add(g0, g1))\n\tp[64:].Inc(t)\n\n\treturn p.Freeze()\n}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func (g *GeoPolygon) toCPtr() *C.GeoPolygon {\n\tif g.v != nil {\n\t\treturn g.v\n\t}\n\n\t// allocate memory for GeoPolygon\n\tpolyPtr := C.malloc(C.sizeof_GeoPolygon)\n\n\tg.v = (*C.GeoPolygon)(polyPtr)\n\n\t// if Exterior is not nil\n\tif g.Exterior != nil {\n\t\tif g.Exterior.GeoCoords != nil {\n\t\t\t// fmt.Printf(\"Before verts: %v\\n\", g.v.geofence.verts)\n\t\t\tg.v.geofence.verts = g.Exterior.GeoCoords.toCPtr()\n\t\t\t// fmt.Printf(\"After verts: %v\\n\", g.v.geofence.verts)\n\t\t\tg.v.geofence.numVerts = C.int(len(g.Exterior.GeoCoords.Coords))\n\t\t\t// fmt.Printf(\"NumHoles: %v\\n\", g.v.geofence.numVerts)\n\t\t}\n\t}\n\n\tif len(g.Holes) > 0 {\n\t\t// malloc the *GeoCoord for the provided coordinates\n\t\tptr := C.malloc(C.size_t(len(g.Holes)) * C.sizeof_Geofence)\n\n\t\tholesArr := (*[1 << 30]C.Geofence)(unsafe.Pointer(ptr))[:len(g.Holes):len(g.Holes)]\n\t\tfor i, hole := range g.Holes {\n\t\t\tholesArr[i].verts = hole.GeoCoords.toCPtr()\n\t\t\tholesArr[i].numVerts = C.int(len(hole.GeoCoords.Coords))\n\t\t}\n\t\tg.v.holes = (*C.Geofence)(ptr)\n\t} else {\n\t\tg.v.holes = nil\n\t}\n\n\tg.v.numHoles = C.int(len(g.Holes))\n\treturn g.v\n}", "func MakeTable(poly uint32) *Table {}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func makerectangle(i int, j int, g *Graph) error {\n\tnodes := i * j //number of vertices\n\n\tif g.numvert < nodes {\n\t\t_, err := g.addVertices(nodes - g.numvert)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tif g.numvert > nodes {\n\t\tlog.Fatal(\"Too many vertices\")\n\t}\n\n\tfrom := 1\n\tto := 2\n\trun := false\n\tdone := false\n\tfor !done {\n\t\ta := Vertex{vert: from}\n\t\tb := Vertex{vert: to}\n\t\tg.addEdge(a, b)\n\t\tfrom++\n\t\tto++\n\t\tif from%j == 0 && !run {\n\t\t\tfrom++\n\t\t\tto++\n\t\t}\n\t\tif run && to > nodes {\n\t\t\tdone = true\n\t\t}\n\t\tif to > nodes {\n\t\t\tfrom = 1\n\t\t\tto = 1 + j\n\t\t\trun = true\n\t\t}\n\t}\n\treturn nil\n}", "func (z *Element22) ToMont() *Element22 {\n\tvar rSquare = Element22{\n\t\t11555390936043306539,\n\t\t958669060063230310,\n\t\t2580977272801836257,\n\t\t1403887552063632943,\n\t\t13867690507567207459,\n\t\t3907927833394869101,\n\t\t10840458828090788374,\n\t\t4883929514287350477,\n\t\t15550705002284641687,\n\t\t204726014467581413,\n\t\t9800326706814271754,\n\t\t15550253209695210297,\n\t\t6763495363949586021,\n\t\t12116376736443678463,\n\t\t15994432058116609212,\n\t\t9284907172179203497,\n\t\t12057222969833993383,\n\t\t7578266974200549103,\n\t\t1045705632585341962,\n\t\t16636233895911641002,\n\t\t10037290343882990384,\n\t\t7731486842628832948,\n\t}\n\treturn z.MulAssign(&rSquare)\n}", "func (e *GT) Marshal() []byte {\n\t// Each value is a 256-bit number.\n\tconst numBytes = 256 / 8\n\n\tif e.p == nil {\n\t\te.p = &gfP12{}\n\t}\n\n\tret := make([]byte, numBytes*12)\n\ttemp := &gfP{}\n\n\tmontDecode(temp, &e.p.x.x.x)\n\ttemp.Marshal(ret)\n\tmontDecode(temp, &e.p.x.x.y)\n\ttemp.Marshal(ret[numBytes:])\n\tmontDecode(temp, &e.p.x.y.x)\n\ttemp.Marshal(ret[2*numBytes:])\n\tmontDecode(temp, &e.p.x.y.y)\n\ttemp.Marshal(ret[3*numBytes:])\n\tmontDecode(temp, &e.p.x.z.x)\n\ttemp.Marshal(ret[4*numBytes:])\n\tmontDecode(temp, &e.p.x.z.y)\n\ttemp.Marshal(ret[5*numBytes:])\n\tmontDecode(temp, &e.p.y.x.x)\n\ttemp.Marshal(ret[6*numBytes:])\n\tmontDecode(temp, &e.p.y.x.y)\n\ttemp.Marshal(ret[7*numBytes:])\n\tmontDecode(temp, &e.p.y.y.x)\n\ttemp.Marshal(ret[8*numBytes:])\n\tmontDecode(temp, &e.p.y.y.y)\n\ttemp.Marshal(ret[9*numBytes:])\n\tmontDecode(temp, &e.p.y.z.x)\n\ttemp.Marshal(ret[10*numBytes:])\n\tmontDecode(temp, &e.p.y.z.y)\n\ttemp.Marshal(ret[11*numBytes:])\n\n\treturn ret\n}", "func (z *Element22) FromMont() *Element22 {\n\n\t// the following lines implement z = z * 1\n\t// with a modified CIOS montgomery multiplication\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\t{\n\t\t// m = z[0]n'[0] mod W\n\t\tm := z[0] * 2085129623399436079\n\t\tC := madd0(m, 9062599614324828209, z[0])\n\t\tC, z[0] = madd2(m, 952425709649632109, z[1], C)\n\t\tC, z[1] = madd2(m, 13987751354083916656, z[2], C)\n\t\tC, z[2] = madd2(m, 9476693002504986527, z[3], C)\n\t\tC, z[3] = madd2(m, 17899356805776864267, z[4], C)\n\t\tC, z[4] = madd2(m, 2607080593922027197, z[5], C)\n\t\tC, z[5] = madd2(m, 6852504016717314360, z[6], C)\n\t\tC, z[6] = madd2(m, 366248478184989226, z[7], C)\n\t\tC, z[7] = madd2(m, 2672987780203805083, z[8], C)\n\t\tC, z[8] = madd2(m, 14115032483094903896, z[9], C)\n\t\tC, z[9] = madd2(m, 8062699450825609015, z[10], C)\n\t\tC, z[10] = madd2(m, 8413249848292746549, z[11], C)\n\t\tC, z[11] = madd2(m, 11172154229712803058, z[12], C)\n\t\tC, z[12] = madd2(m, 18137346262305431037, z[13], C)\n\t\tC, z[13] = madd2(m, 123227702747754650, z[14], C)\n\t\tC, z[14] = madd2(m, 7409464670784690235, z[15], C)\n\t\tC, z[15] = madd2(m, 243347369443125979, z[16], C)\n\t\tC, z[16] = madd2(m, 200317109320159479, z[17], C)\n\t\tC, z[17] = madd2(m, 17492726232193822651, z[18], C)\n\t\tC, z[18] = madd2(m, 17666595880400198649, z[19], C)\n\t\tC, z[19] = madd2(m, 1619463007483089584, z[20], C)\n\t\tC, z[20] = madd2(m, 7910025299994333900, z[21], C)\n\t\tz[21] = C\n\t}\n\n\t// if z > q --> z -= q\n\tif !(z[21] < 7910025299994333900 || (z[21] == 7910025299994333900 && (z[20] < 1619463007483089584 || (z[20] == 1619463007483089584 && (z[19] < 17666595880400198649 || (z[19] == 17666595880400198649 && (z[18] < 17492726232193822651 || (z[18] == 17492726232193822651 && (z[17] < 200317109320159479 || (z[17] == 200317109320159479 && (z[16] < 243347369443125979 || (z[16] == 243347369443125979 && (z[15] < 7409464670784690235 || (z[15] == 7409464670784690235 && (z[14] < 123227702747754650 || (z[14] == 123227702747754650 && (z[13] < 18137346262305431037 || (z[13] == 18137346262305431037 && (z[12] < 11172154229712803058 || (z[12] == 11172154229712803058 && (z[11] < 8413249848292746549 || (z[11] == 8413249848292746549 && (z[10] < 8062699450825609015 || (z[10] == 8062699450825609015 && (z[9] < 14115032483094903896 || (z[9] == 14115032483094903896 && (z[8] < 2672987780203805083 || (z[8] == 2672987780203805083 && (z[7] < 366248478184989226 || (z[7] == 366248478184989226 && (z[6] < 6852504016717314360 || (z[6] == 6852504016717314360 && (z[5] < 2607080593922027197 || (z[5] == 2607080593922027197 && (z[4] < 17899356805776864267 || (z[4] == 17899356805776864267 && (z[3] < 9476693002504986527 || (z[3] == 9476693002504986527 && (z[2] < 13987751354083916656 || (z[2] == 13987751354083916656 && (z[1] < 952425709649632109 || (z[1] == 952425709649632109 && (z[0] < 9062599614324828209))))))))))))))))))))))))))))))))))))))))))) {\n\t\tvar b uint64\n\t\tz[0], b = bits.Sub64(z[0], 9062599614324828209, 0)\n\t\tz[1], b = bits.Sub64(z[1], 952425709649632109, b)\n\t\tz[2], b = bits.Sub64(z[2], 13987751354083916656, b)\n\t\tz[3], b = bits.Sub64(z[3], 9476693002504986527, b)\n\t\tz[4], b = bits.Sub64(z[4], 17899356805776864267, b)\n\t\tz[5], b = bits.Sub64(z[5], 2607080593922027197, b)\n\t\tz[6], b = bits.Sub64(z[6], 6852504016717314360, b)\n\t\tz[7], b = bits.Sub64(z[7], 366248478184989226, b)\n\t\tz[8], b = bits.Sub64(z[8], 2672987780203805083, b)\n\t\tz[9], b = bits.Sub64(z[9], 14115032483094903896, b)\n\t\tz[10], b = bits.Sub64(z[10], 8062699450825609015, b)\n\t\tz[11], b = bits.Sub64(z[11], 8413249848292746549, b)\n\t\tz[12], b = bits.Sub64(z[12], 11172154229712803058, b)\n\t\tz[13], b = bits.Sub64(z[13], 18137346262305431037, b)\n\t\tz[14], b = bits.Sub64(z[14], 123227702747754650, b)\n\t\tz[15], b = bits.Sub64(z[15], 7409464670784690235, b)\n\t\tz[16], b = bits.Sub64(z[16], 243347369443125979, b)\n\t\tz[17], b = bits.Sub64(z[17], 200317109320159479, b)\n\t\tz[18], b = bits.Sub64(z[18], 17492726232193822651, b)\n\t\tz[19], b = bits.Sub64(z[19], 17666595880400198649, b)\n\t\tz[20], b = bits.Sub64(z[20], 1619463007483089584, b)\n\t\tz[21], _ = bits.Sub64(z[21], 7910025299994333900, b)\n\t}\n\treturn z\n}", "func convertMont(u PublicKey) (*edwards25519.Point, error) {\n\tum, err := (&field.Element{}).SetBytes(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// y = (u - 1)/(u + 1)\n\ta := new(field.Element).Subtract(um, one)\n\tb := new(field.Element).Add(um, one)\n\ty := new(field.Element).Multiply(a, b.Invert(b)).Bytes()\n\n\t// Set sign to 0\n\ty[31] &= 0x7F\n\n\treturn (&edwards25519.Point{}).SetBytes(y)\n}", "func (el *Fill) Polyline() {}", "func (p thinPoly) Karatsuba3(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 32)\n\tvar z = make(thinPoly, 64)\n\tf0, f1 := f[:16], f[16:]\n\tg0, g1 := g[:16], g[16:]\n\n\tt.Karatsuba4(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba4(f1, g1)\n\tz[16:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[16:].Inc(z.Mul(-1, z)[:48])\n\tt.Karatsuba4(z.Add(f0, f1), z[16:].Add(g0, g1))\n\tp[16:].Inc(t)\n\n\treturn p\n}", "func (encoder *encoder) RingTToMul(ptRt *PlaintextRingT, ptMul *PlaintextMul) {\n\tif ptRt.value != ptMul.value {\n\t\tcopy(ptMul.value.Coeffs[0], ptRt.value.Coeffs[0])\n\t}\n\tfor i := 1; i < len(encoder.ringQ.Modulus); i++ {\n\t\tcopy(ptMul.value.Coeffs[i], ptRt.value.Coeffs[0])\n\t}\n\n\tencoder.ringQ.NTTLazy(ptMul.value, ptMul.value)\n\tencoder.ringQ.MForm(ptMul.value, ptMul.value)\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func PolyRational32(num []int32, den []uint32, t []TermT) TermT {\n\tcount := C.uint32_t(len(num))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_rational32(count, (*C.int32_t)(&num[0]), (*C.uint32_t)(&den[0]), (*C.term_t)(&t[0])))\n}", "func map_literal_test() {\n\ttype Vertex struct {\n\t\tLat, Long float64\n\t}\n\n\tvar m = map[string]Vertex {\n\t\t\"Andela Lagos\": { 34.44, 334.44},\n\t\t\"Andela Nairobi\": { 40.89, 21.89},\n\t}\n\n\tfmt.Println(m)\n}", "func (curve *EdCurve) ToMontgomeryPointForm2(sqrtB *big.Int, p *EcPoint) (p1, p2 *EcPoint) {\n\tyAddOne := new(big.Int).Add(p.Y, ONE) // y+1\n\tySubOne := new(big.Int).Sub(p.Y, ONE) // y-1\n\tp1, p2 = NewPoint(), NewPoint()\n\tp1.X = ModFraction(yAddOne, ySubOne, curve.P) // (y+1)/(y-1)\n\tp1.Y = ModFraction(p1.X, p.X, curve.P) // u/x\n\tp1.Y.Mul(p1.Y, sqrtB) // sqrtB * u/x\n\tp1.Y.Mod(p1.Y, curve.P)\n\n\tp2.X = ModFraction(ySubOne, yAddOne, curve.P) // (y-1)/(y+1)\n\tp2.Y = ModFraction(p2.X, p.X, curve.P) // u/x\n\tp2.Y.Mul(p2.Y, sqrtB) // sqrtB * u/x\n\tp2.Y.Mod(p2.Y, curve.P)\n\treturn\n}", "func (c *Coord) M() float64 { return c[3] }", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * 1e8))\n}", "func (ks *KZG1Settings) CommitToPoly(coeffs []gmcl.Fr) *gmcl.G1 {\n\tvar out gmcl.G1\n\tgmcl.G1MulVec(&out, ks.PK[:len(coeffs)], coeffs)\n\treturn &out\n}", "func (p thinPoly) Karatsuba2(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 64)\n\tvar z = make(thinPoly, 128)\n\tf0, f1 := f[:32], f[32:]\n\tg0, g1 := g[:32], g[32:]\n\n\tt.Karatsuba3(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba3(f1, g1)\n\tz[32:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[32:].Inc(z.Mul(-1, z)[:96])\n\tt.Karatsuba3(z.Add(f0, f1), z[32:].Add(g0, g1))\n\tp[32:].Inc(t)\n\n\treturn p\n}", "func (z Element22) ToRegular() Element22 {\n\treturn *z.FromMont()\n}", "func pgParsePolygon(a []byte) (out [][2][]byte) {\n\ta = a[1 : len(a)-1] // drop the first `(` and last `)`\n\treturn pgParsePointList(a)\n}", "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * conventionalConversionFactor))\n}", "func (l *LinkedGeoPolygon) toCPtr() *C.LinkedGeoPolygon {\n\tl.v = &C.LinkedGeoPolygon{}\n\treturn l.v\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func MapToOctUV(v vector.Vector3) vector.Vector2 {\n\t// Project the sphere onto the octahedron, and then onto the xy plane\n\t// vec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\n\tp := vector.\n\t\tNewVector2(v.X(), v.Y()).\n\t\tMultByConstant(1.0 / (math.Abs(v.X()) + math.Abs(v.Y()) + math.Abs(v.Z())))\n\tif v.Z() > 0 {\n\t\treturn p\n\t}\n\n\t// Reflect the folds of the lower hemisphere over the diagonals\n\t// return ((1.0 - math.Abs(p.yx)) * signNotZero(p))\n\treturn multVect(signNotZero(p), vector.NewVector2(1.0-math.Abs(p.Y()), 1.0-math.Abs(p.X())))\n}", "func FToM(f Foot) Meter { return Meter(f * 0.3048) }", "func (n *Uint256) toOctal() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits using the fact\n\t// that 3 bits converts directly to a single octal digit.\n\tmaxOutDigits := (n.BitLen() + 2) / 3\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 8 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that partial digit handling is needed in this case because the shift\n\t// amount does not evenly divide the bits per internal word.\n\tconst shift = 3\n\tconst mask = 1<<shift - 1\n\tunconvertedBits := bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\t// Convert full digits.\n\t\tfor ; unconvertedBits >= shift; unconvertedBits -= shift {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\n\t\t// Move to the next input word when there are not any remaining\n\t\t// unconverted bits that need to be handled.\n\t\tif unconvertedBits == 0 {\n\t\t\tinputWord = n.n[inputIdx]\n\t\t\tunconvertedBits = bitsPerInternalWord\n\t\t\tcontinue\n\t\t}\n\n\t\t// Account for the remaining unconverted bits from the current word and\n\t\t// the bits needed from the next word to form a full digit for the next\n\t\t// digit.\n\t\tinputWord |= n.n[inputIdx] << unconvertedBits\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\toutputIdx--\n\n\t\t// Move to the next input word while accounting for the bits already\n\t\t// consumed above by shifting it and updating the unconverted bits\n\t\t// accordingly.\n\t\tinputWord = n.n[inputIdx] >> (shift - unconvertedBits)\n\t\tunconvertedBits = bitsPerInternalWord - (shift - unconvertedBits)\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func ShapeToVertexList(s string) (vertexList []shared.Point2d, length int) {\n\tvar stringArray = StringToStringArray(s)\n\tvar currentPosX = 0\n\tvar currentPosY = 0\n\tvar startPosX = 0\n\tvar startPosY = 0\n\tvar index = 0\n\tvar l float64\n\n\tfor index < len(stringArray) {\n\t\tswitch stringArray[index] {\n\t\tcase \"M\", \"L\", \"m\", \"l\":\n\t\t\ttempX, err := strconv.Atoi(stringArray[index+1])\n\t\t\ttempY, err := strconv.Atoi(stringArray[index+2])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Invalid SVG String\")\n\t\t\t\t// TODO: return InvalidShapeSvgStringError\n\t\t\t}\n\n\t\t\t// Uppercase = absolute pos, lowercase = relative pos\n\t\t\tif stringArray[index] == \"M\" {\n\t\t\t\tstartPosX = tempX\n\t\t\t\tstartPosY = tempY\n\t\t\t\tcurrentPosX = tempX\n\t\t\t\tcurrentPosY = tempY\n\t\t\t} else if stringArray[index] == \"m\" {\n\t\t\t\tstartPosX += tempX\n\t\t\t\tstartPosY += tempY\n\t\t\t\tcurrentPosX += tempX\n\t\t\t\tcurrentPosY += tempY\n\t\t\t} else if stringArray[index] == \"L\" {\n\t\t\t\t// need to calculate the length of x and y\n\t\t\t\tx := math.Abs(float64(currentPosX - tempX))\n\t\t\t\ty := math.Abs(float64(currentPosY - tempY))\n\t\t\t\tl += math.Sqrt(x*x + y*y)\n\t\t\t\tcurrentPosX = tempX\n\t\t\t\tcurrentPosY = tempY\n\t\t\t} else {\n\t\t\t\tl += math.Sqrt(float64(tempX*tempX + tempY*tempY))\n\t\t\t\tcurrentPosX += tempX\n\t\t\t\tcurrentPosY += tempY\n\t\t\t}\n\n\t\t\tindex += 3\n\t\tcase \"H\", \"h\":\n\t\t\ttempX, err := strconv.Atoi(stringArray[index+1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Invalid SVG String\")\n\t\t\t\t// TODO: return InvalidShapeSvgStringError\n\t\t\t}\n\n\t\t\tif stringArray[index] == \"H\" {\n\t\t\t\tx := math.Abs(float64(currentPosX - tempX))\n\t\t\t\tl += x\n\t\t\t\tcurrentPosX = tempX\n\t\t\t} else {\n\t\t\t\tl += math.Abs(float64(tempX))\n\t\t\t\tcurrentPosX += tempX\n\t\t\t}\n\n\t\t\tindex += 2\n\t\tcase \"V\", \"v\":\n\t\t\ttempY, err := strconv.Atoi(stringArray[index+1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Invalid SVG String\")\n\t\t\t\t// TODO: return InvalidShapeSvgStringError\n\t\t\t}\n\n\t\t\tif stringArray[index] == \"V\" {\n\t\t\t\ty := math.Abs(float64(currentPosY - tempY))\n\t\t\t\tl += y\n\t\t\t\tcurrentPosY = tempY\n\t\t\t} else {\n\t\t\t\tl += math.Abs(float64(tempY))\n\t\t\t\tcurrentPosY += tempY\n\t\t\t}\n\n\t\t\tindex += 2\n\t\tcase \"Z\", \"z\":\n\t\t\tx := math.Abs(float64(currentPosX - startPosX))\n\t\t\ty := math.Abs(float64(currentPosY - startPosY))\n\t\t\tl += math.Sqrt(x*x + y*y)\n\t\t\tcurrentPosX = startPosX\n\t\t\tcurrentPosY = startPosY\n\n\t\t\tindex++\n\t\tdefault:\n\t\t\tfmt.Println(\"unsupported svg command\")\n\t\t\t// TODO: return InvalidShapeSvgStringError\n\t\t\tindex++\n\t\t}\n\t\t// Adding a new vertex\n\t\tpoint := shared.Point2d{X: currentPosX, Y: currentPosY}\n\t\tvertexList = append(vertexList, point)\n\t}\n\tlength = int(math.Ceil(l))\n\treturn vertexList, length\n}", "func ConvertPt(pt []float64) []int64 {\n\tnewpt := make([]int64, 2)\n\tnewpt[0] = int64(pt[0] * math.Pow(10.0, 7.0))\n\tnewpt[1] = int64(pt[1] * math.Pow(10.0, 7.0))\n\treturn newpt\n}", "func (encoder *encoder) MulToRingT(pt *PlaintextMul, ptRt *PlaintextRingT) {\n\tencoder.ringQ.InvNTTLvl(0, pt.value, ptRt.value)\n\tencoder.ringQ.InvMFormLvl(0, ptRt.value, ptRt.value)\n}", "func (p thinPoly) Zero() thinPoly {\n\tfor i := range p {\n\t\tp[i] = 0\n\t}\n\treturn p\n}", "func (p *Position) polyglot() (hash, pawnHash uint64) {\n\tboard := p.board\n\tfor board != 0 {\n\t\tsquare := board.pop()\n\t\tpiece := p.pieces[square]\n\t\trandom := piece.polyglot(square)\n\t\thash ^= random\n\t\tif piece.isPawn() {\n\t\t\tpawnHash ^= random\n\t\t}\n\t}\n\n\thash ^= hashCastle[p.castles]\n\tif p.enpassant != 0 {\n\t\thash ^= hashEnpassant[p.enpassant & 7] // p.enpassant column.\n\t}\n\tif p.color == White {\n\t\thash ^= polyglotRandomWhite\n\t}\n\n\treturn\n}", "func (this *DtPoly) GetType() DtPolyTypes {\n\treturn DtPolyTypes(this.AreaAndtype >> 6)\n}", "func spher2cartesian(v mat64.Vector) {\n\t// r := v[0]\n\t// teta := v[1] * math.Pi / 180.0\n\t// phi := v[2] * math.Pi / 180.0\n\t// x := r * math.Sin(teta) * math.Cos(phi)\n\t// y := r * math.Sin(teta) * math.Sin(phi)\n\t// z := r * math.Cos(teta)\n\n\t// fmt.Printf(\"%f %f %f\\n\", x, y, z)\n}", "func (Trng TriangularGenerator) TriangularObj(a, b, c float64) float64 {\r\n\tif !(a < c && c < b) {\r\n\t\tfmt.Println(\"Invalid parameters a,b,c:\", a, b, c)\r\n\t\treturn 0.0\r\n\t}\r\n\turng := Trng.uniform.Float64Range(0.0, 1.0)\r\n\tmode := (c - a) / (b - a)\r\n\tif urng < mode {\r\n\t\treturn a + math.Sqrt(urng*(b-1.0)*(c-a))\r\n\t} else {\r\n\t\treturn b - math.Sqrt((1.0-urng)*(b-a)*(b-c))\r\n\t}\r\n}", "func pinyinToDigit(py string) int {\n\n\tfor _, c := range gConsonant {\n\t\tif strings.HasPrefix(py, c) {\n\t\t\treturn gConsonantNum[c]\n\t\t}\n\n\t}\n\n\treturn 0\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func polyGetNoise(eta int, seed []byte, nonce byte) Poly {\n\toutbuf := make([]byte, eta*n/4)\n\tstate := sha3.NewShake256()\n\tstate.Write(seed[:])\n\tstate.Write([]byte{nonce})\n\tstate.Read(outbuf[:])\n\tvar p Poly\n\tif eta == 3 {\n\t\tp = polyCBD3(outbuf)\n\t}\n\tif eta == 2 {\n\t\tp = polyCBD2(outbuf)\n\t}\n\treturn p\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func (z *Float64) Maclaurin(y *Float64, p *maclaurin.Float64) *Float64 {\n\tif p.Len() == 0 {\n\t\tz = new(Float64)\n\t\treturn z\n\t}\n\tn := p.Degree\n\tvar a float64\n\tif n == 0 {\n\t\tz = new(Float64)\n\t\ta, _ = p.Coeff(n)\n\t\tz.SetReal(a)\n\t\treturn z\n\t}\n\ta, _ = p.Coeff(n)\n\tz.Dilate(y, a)\n\tfor n > 1 {\n\t\tn--\n\t\tif a, ok := p.Coeff(n); ok {\n\t\t\tz.Plus(z, a)\n\t\t}\n\t\tz.Mul(z, y)\n\t}\n\tif a, ok := p.Coeff(0); ok {\n\t\tz.Plus(z, a)\n\t}\n\treturn z\n}", "func (c *core) Marshal(pt *point) []byte {\n\treturn elliptic.MarshalCompressed(c.Curve, pt.X, pt.Y)\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func LemmatiseT(t string) string {\n\tlm := Mots(t)\n\tvar sortie string\n\tfor _, m := range lm {\n\t\tan, echec := Lemmatise(m)\n\t\tif echec {\n\t\t\tan, echec = Lemmatise(Majminmaj(m))\n\t\t}\n\t\tif echec {\n\t\t\tsortie = (\"\\n\" + m + \" échec\")\n\t\t} else {\n\t\t\tsortie += Restostring(an) + \"\\n\"\n\t\t}\n\t}\n\treturn sortie\n}", "func Inverse(lat1, lon1, lat2, lon2 float64) (s12, azi1, azi2 float64) {\n\tlon12 := angNormalize(lon2 - lon1)\n\tlon12 = angRound(lon12)\n\t// Make longitude difference positive.\n\tlonsign := sg(lon12 >= 0)\n\tlon12 *= lonsign\n\tif lon12 == math.Pi {\n\t\tlonsign = 1\n\t}\n\n\t// If really close to the equator, treat as on equator.\n\tlat1 = angRound(lat1)\n\tlat2 = angRound(lat2)\n\n\t// Swap points so that point with higher (abs) latitude is point 1\n\tswapp := sg(math.Abs(lat1) >= math.Abs(lat2))\n\tif swapp < 0 {\n\t\tlonsign *= -1\n\t\tlat1, lat2 = lat2, lat1\n\t}\n\n\t// Make lat1 <= 0\n\tlatsign := sg(lat1 < 0)\n\tlat1 *= latsign\n\tlat2 *= latsign\n\n\t// Now we have\n\t//\n\t// 0 <= lon12 <= 180\n\t// -90 <= lat1 <= 0\n\t// lat1 <= lat2 <= -lat1\n\t//\n\t// lonsign, swapp, latsign register the transformation to bring the\n\t// coordinates to this canonical form. In all cases, false means no change was\n\t// made. We make these transformations so that there are few cases to\n\t// check, e.g., on verifying quadrants in atan2. In addition, this\n\t// enforces some symmetries in the results returned.\n\n\tvar phi, sbet1, cbet1, sbet2, cbet2, s12x, m12x float64\n\n\tphi = lat1\n\t// Ensure cbet1 = +epsilon at poles\n\tsbet1, cbet1 = math.Sincos(phi)\n\tsbet1 *= _f1\n\tif cbet1 == 0. && lat1 < 0 {\n\t\tcbet1 = _tiny\n\t}\n\tsbet1, cbet1 = sinCosNorm(sbet1, cbet1)\n\n\tphi = lat2\n\t// Ensure cbet2 = +epsilon at poles\n\tsbet2, cbet2 = math.Sincos(phi)\n\tsbet2 *= _f1\n\tif cbet2 == 0. {\n\t\tcbet2 = _tiny\n\t}\n\tsbet2, cbet2 = sinCosNorm(sbet2, cbet2)\n\n\t// If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the\n\t// |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is\n\t// a better measure. This logic is used in assigning calp2 in Lambda12.\n\t// Sometimes these quantities vanish and in that case we force bet2 = +/-\n\t// bet1 exactly. An example where is is necessary is the inverse problem\n\t// 48.522876735459 0 -48.52287673545898293 179.599720456223079643\n\t// which failed with Visual Studio 10 (Release and Debug)\n\tif cbet1 < -sbet1 {\n\t\tif cbet2 == cbet1 {\n\t\t\tif sbet2 < 0 {\n\t\t\t\tsbet2 = sbet1\n\t\t\t} else {\n\t\t\t\tsbet2 = -sbet1\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif math.Abs(sbet2) == -sbet1 {\n\t\t\tcbet2 = cbet1\n\t\t}\n\t}\n\n\tlam12 := lon12\n\tslam12, clam12 := math.Sincos(lam12) // lon12 == 90 isn't interesting\n\n\tvar sig12, calp1, salp1, calp2, salp2, omg12 float64\n\t// index zero elements of these arrays are unused\n\tvar (\n\t\tC1a [_nC1 + 1]float64\n\t\tC2a [_nC2 + 1]float64\n\t\tC3a [_nC3]float64\n\t)\n\n\tmeridian := lat1 == -math.Pi/2 || slam12 == 0.0\n\n\tif meridian {\n\n\t\t// Endpoints are on a single full meridian, so the geodesic might lie on\n\t\t// a meridian.\n\n\t\tcalp1, salp2 = clam12, slam12 // Head to the target longitude\n\t\tcalp2, salp2 = 1, 0 // At the target we're heading north\n\n\t\t// tan(bet) = tan(sig) * cos(alp)\n\t\tssig1, csig1 := sbet1, calp1*cbet1\n\t\tssig2, csig2 := sbet2, calp2*cbet2\n\n\t\t// sig12 = sig2 - sig1\n\t\tsig12 = math.Atan2(max(csig1*ssig2-ssig1*csig2, 0), csig1*csig2+ssig1*ssig2)\n\n\t\ts12x, m12x, _ = lengths(_n, sig12, ssig1, csig1, ssig2, csig2, cbet1, cbet2, C1a[:], C2a[:])\n\n\t\t// Add the check for sig12 since zero length geodesics might yield m12 < 0. Test case was\n\t\t//\n\t\t// echo 20.001 0 20.001 0 | Geod -i\n\t\t//\n\t\t// In fact, we will have sig12 > pi/2 for meridional geodesic which is\n\t\t// not a shortest path.\n\t\tif sig12 < 1 || m12x >= 0 {\n\t\t\tm12x *= _a\n\t\t\ts12x *= _b\n\t\t} else {\n\t\t\t// m12 < 0, i.e., prolate and too close to anti-podal\n\t\t\tmeridian = false\n\t\t}\n\n\t}\n\n\tif !meridian && sbet1 == 0 && (_f <= 0 || lam12 <= math.Pi-_f*math.Pi) {\n\n\t\t// Geodesic runs along equator\n\t\tcalp1, salp1, calp2, salp2 = 0, 1, 0, 1\n\t\ts12x = _a * lam12\n\t\tm12x = _b * math.Sin(lam12/_f1)\n\t\tomg12 = lam12 / _f1\n\t\tsig12 = omg12\n\n\t} else if !meridian {\n\n\t\t// Now point1 and point2 belong within a hemisphere bounded by a\n\t\t// meridian and geodesic is neither meridional or equatorial.\n\n\t\t// Figure a starting point for Newton's method\n\t\tsig12, salp1, calp1, salp2, calp2 = inverseStart(sbet1, cbet1, sbet2, cbet2, lam12, salp2, calp2, C1a[:], C2a[:])\n\n\t\tif sig12 >= 0 {\n\n\t\t\t// Short lines (InverseStart sets salp2, calp2)\n\t\t\tw1 := math.Sqrt(1 - _e2*cbet1*cbet1)\n\t\t\ts12x = sig12 * _a * w1\n\t\t\tm12x = w1 * w1 * _a / _f1 * math.Sin(sig12*_f1/w1)\n\t\t\tomg12 = lam12 / w1\n\n\t\t} else {\n\n\t\t\t// Newton's method\n\t\t\tvar ssig1, csig1, ssig2, csig2, eps, ov float64\n\t\t\tnumit := 0\n\t\t\tfor trip := 0; numit < _maxit; numit++ {\n\t\t\t\tvar v, dv float64\n\n\t\t\t\tv, salp2, calp2, sig12, ssig1, csig1, ssig2, csig2, eps, omg12, dv = \n\t\t\t\t\tlambda12(sbet1, cbet1, sbet2, cbet2, salp1, calp1, trip < 1, C1a[:], C2a[:], C3a[:])\n\t\t\t\tv -= lam12\n\n\t\t\t\tif !(math.Abs(v) > _tiny) || !(trip < 1) {\n\t\t\t\t\tif !(math.Abs(v) <= max(_tol1, ov)) {\n\t\t\t\t\t\tnumit = _maxit\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tdalp1 := -v / dv\n\n\t\t\t\tsdalp1, cdalp1 := math.Sincos(dalp1)\n\t\t\t\tnsalp1 := salp1*cdalp1 + calp1*sdalp1\n\t\t\t\tcalp1 = calp1*cdalp1 - salp1*sdalp1\n\t\t\t\tsalp1 = max(0, nsalp1)\n\t\t\t\tsalp1, calp1 = sinCosNorm(salp1, calp1)\n\n\t\t\t\tif !(math.Abs(v) >= _tol1 && v*v >= ov*_tol0) {\n\t\t\t\t\ttrip++\n\t\t\t\t}\n\t\t\t\tov = math.Abs(v)\n\t\t\t}\n\n\t\t\tif numit >= _maxit {\n\t\t\t\treturn math.NaN(), math.NaN(), math.NaN() // Signal failure.\n\t\t\t}\n\n\t\t\ts12x, m12x, _ = lengths(eps, sig12, ssig1, csig1, ssig2, csig2, cbet1, cbet2, C1a[:], C2a[:])\n\n\t\t\tm12x *= _a\n\t\t\ts12x *= _b\n\t\t\tomg12 = lam12 - omg12\n\t\t}\n\t}\n\n\ts12 = 0 + s12x // Convert -0 to 0\n\n\t// Convert calp, salp to azimuth accounting for lonsign, swapp, latsign.\n\tif swapp < 0 {\n\t\tsalp1, salp2 = salp2, salp1\n\t\tcalp1, calp2 = calp2, calp1\n\t}\n\n\tsalp1 *= swapp * lonsign; calp1 *= swapp * latsign;\n\tsalp2 *= swapp * lonsign; calp2 *= swapp * latsign;\n\n\t// minus signs give range [-180, 180). 0- converts -0 to +0.\n\tazi1 = 0 - math.Atan2(-salp1, calp1)\n\tazi2 = 0 - math.Atan2(salp2, -calp2) // make it point backwards\n\n\treturn\n}", "func (outer outer) Shape() []pos.Rel {\r\n\tl := make([]pos.Rel, 2*(outer.Xlen+outer.Ylen))\r\n\tfor i := 0; i < outer.Xlen; i++ {\r\n\t\tl[i] = pos.Rel{Z: i, W: -1}\r\n\t\tl[outer.Xlen+i] = pos.Rel{Z: i, W: outer.Ylen}\r\n\t}\r\n\tfor j := 0; j < outer.Ylen; j++ {\r\n\t\tl[2*outer.Xlen+j] = pos.Rel{Z: -1, W: j}\r\n\t\tl[2*outer.Xlen+outer.Ylen+j] = pos.Rel{Z: outer.Xlen, W: j}\r\n\t}\r\n\treturn l\r\n}", "func NotationToCoord(algebra string) Coord {\n\tif len(algebra) != 2 {\n\t\tpanic(\"Algebraic notation must be 2 characters precisely; got: '\" + algebra + \"'\")\n\t}\n\talgebra = strings.ToUpper(algebra)\n\n\tvar c Coord\n\tfile := algebra[0]\n\trank := algebra[1]\n\n\t// Remember, these are ASCII code points, not numbers\n\tif file < 65 || file > 72 || rank < 48 || rank > 57 {\n\t\tpanic(\"Bad position (\" + algebra + \")\")\n\t}\n\n\tc.Row = int(rank - 48 - 1)\n\tc.Col = int(file - 65)\n\n\treturn c\n}", "func (z *polyGF2) String() string {\n\tif z.coeff.Sign() == 0 {\n\t\treturn \"0\"\n\t}\n\tvar s bytes.Buffer\n\tfor i := z.Degree(); i >= 0; i-- {\n\t\tif z.coeff.Bit(i) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif s.Len() > 0 {\n\t\t\ts.WriteByte('+')\n\t\t}\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\ts.WriteByte('1')\n\t\tcase i == 1:\n\t\t\ts.WriteByte('x')\n\t\tdefault:\n\t\t\tfmt.Fprintf(&s, \"x^%d\", i)\n\t\t}\n\t}\n\treturn s.String()\n}", "func molodensky(ilat, ilon float64, from, to eDatum) (float64, float64) {\n\t// from->WGS84 - to->WGS84 = from->WGS84 + WGS84->to = from->to\n\tdX := Datum[from].dX - Datum[to].dX\n\tdY := Datum[from].dY - Datum[to].dY\n\tdZ := Datum[from].dZ - Datum[to].dZ\n\tslat := math.Sin(ilat)\n\tclat := math.Cos(ilat)\n\tslon := math.Sin(ilon)\n\tclon := math.Cos(ilon)\n\tssqlat := slat * slat\n\n\t//dlat = ((-dx * slat * clon - dy * slat * slon + dz * clat)\n\t// + (da * rn * fromEsq * slat * clat / fromA)\n\t// + (df * (rm * adb + rn / adb )* slat * clat))\n\t// / (rm + from.h);\n\n\tfromF := Datum[from].f\n\tdf := Datum[to].f - fromF\n\tfromA := Datum[from].a\n\tda := Datum[to].a - fromA\n\tfromEsq := Datum[from].esq\n\tadb := 1.0 / (1.0 - fromF)\n\trn := fromA / math.Sqrt(1-fromEsq*ssqlat)\n\trm := fromA * (1 - fromEsq) / math.Pow((1-fromEsq*ssqlat), 1.5)\n\tfromH := 0.0 // we're flat!\n\tdlat := (-dX*slat*clon - dY*slat*slon + dZ*clat + da*rn*fromEsq*slat*clat/fromA +\n\t\t+df*(rm*adb+rn/adb)*slat*clat) /\n\t\t(rm + fromH)\n\n\t// result lat (radians)\n\tolat := ilat + dlat\n\n\t// dlon = (-dx * slon + dy * clon) / ((rn + from.h) * clat);\n\tdlon := (-dX*slon + dY*clon) / ((rn + fromH) * clat)\n\t// result lon (radians)\n\tolon := ilon + dlon\n\treturn olat, olon\n}", "func (p *Poly) reduce() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = barretReduce(p[i])\n\t}\n}", "func text2matrix(set noteMap, figures map[string]figure, txt []string) (channels, notes matrix, figuremap map[int][]midiFigure) {\n\tfiguremap = make(map[int][]midiFigure)\n\tfor _, line := range txt {\n\t\tvar chanV, noteV []int\n\t\tlane := strings.Split(strings.TrimSpace(line), laneSplitStr)\n\t\t// use our own index because we need to be able to decrease it\n\t\t// if we encounter unwanted (uncounted) characters\n\t\tvar i = -1\n\t\tfor _, elem := range lane {\n\t\t\ti++\n\t\t\tif elem == \"\" {\n\t\t\t\ti--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfirst, rest := splitFirstRune(elem)\n\t\t\tif first == figurePrefix {\n\t\t\t\t// generate a micro pattern\n\t\t\t\tfiguremap[i] = append(figuremap[i], translateFigure(set, figures, rest))\n\t\t\t\t// also generate an empty single note\n\t\t\t\tchanV = append(chanV, 0)\n\t\t\t\tnoteV = append(noteV, 0)\n\t\t\t} else {\n\t\t\t\t// generate a normal note\n\t\t\t\tc, n := translateKit(set, elem)\n\t\t\t\tchanV = append(chanV, c)\n\t\t\t\tnoteV = append(noteV, n)\n\t\t\t}\n\t\t}\n\t\tchannels = append(channels, row(chanV))\n\t\tnotes = append(notes, row(noteV))\n\t}\n\tdebugf(\"text2matrix(): figuremap: %v\", figuremap)\n\treturn\n}", "func TestToNGR3(t *testing.T) {\n\tngr, err := NewGridRefFromString(\"JH\")\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error\")\n\t}\n\to1, _ := ngr.ToLatLon()\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error\")\n\t}\n\t// Check for each valid number of digits.\n\tfor n := 1; n < 6; n++ {\n\t\tfor _, o2 := range []GridCoord{\n\t\t\t{o1.Easting + 100000, o1.Northing},\n\t\t\t{o1.Easting, o1.Northing + 100000},\n\t\t\t{o1.Easting + 100000, o1.Northing + 100000},\n\t\t} {\n\t\t\t_, err := o2.ToGridRef(n * 2)\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"Expected error GridCoord%v (nDigits=%d)\", o2, n*2)\n\t\t\t}\n\t\t}\n\t}\n}", "func (z Element22) ToBigIntRegular(res *big.Int) *big.Int {\n\tz.FromMont()\n\tbits := (*[22]big.Word)(unsafe.Pointer(&z))\n\treturn res.SetBits(bits[:])\n}", "func (milTz militaryTimeZones) November() string {return \"Etc/GMT-1\" }", "func PolyRational64(num []int64, den []uint64, t []TermT) TermT {\n\tcount := C.uint32_t(len(num))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\t// do we want to be nannies here?\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_rational64(count, (*C.int64_t)(&num[0]), (*C.uint64_t)(&den[0]), (*C.term_t)(&t[0])))\n}", "func PToXY(c ...float64) ([]float64, error) {\n\tif len(c) < 2 {\n\t\treturn c, ErrCoordsRequire2Values\n\t}\n\t// log.Println(\"Lon/Lat\", c)\n\t//x, y := PLonToX(c[0]), PLatToY(c[1])\n\n\tcrds := []float64{PLonToX(c[0]), PLatToY(c[1])}\n\tcrds = append(crds, c[2:]...)\n\treturn crds, nil\n}", "func MakeMultiPolygon(multipolygon [][][][]float64) ([]byte, []int64) {\n\tgeometryb := []byte{34}\n\tgeometry := []uint64{}\n\twest, south, east, north := 180.0, 90.0, -180.0, -90.0\n\twest, south, east, north = west*powerfactor, south*powerfactor, east*powerfactor, north*powerfactor\n\tbb := []int64{int64(west), int64(south), int64(east), int64(north)}\n\n\tfor _, polygon := range multipolygon {\n\t\tgeometry = append(geometry, uint64(len(polygon)))\n\t\ttempgeom, tempbb := MakePolygon2(polygon)\n\t\tgeometry = append(geometry, tempgeom...)\n\t\tif bb[0] > tempbb[0] {\n\t\t\tbb[0] = tempbb[0]\n\t\t}\n\t\tif bb[1] > tempbb[1] {\n\t\t\tbb[1] = tempbb[1]\n\t\t}\n\t\tif bb[2] < tempbb[2] {\n\t\t\tbb[2] = tempbb[2]\n\t\t}\n\t\tif bb[3] < tempbb[3] {\n\t\t\tbb[3] = tempbb[3]\n\t\t}\n\t}\n\tgeometryb = append(geometryb, WritePackedUint64(geometry)...)\n\treturn geometryb, bb\n}", "func (gps *GPS) Mercator_encrypt( wgsLat float64, wgsLon float64) map[string]float64 {\n x := wgsLon * 20037508.34 / 180.\n y := math.Log(math.Tan((90. + wgsLat) * PI / 360.)) / (PI / 180.)\n y = y * 20037508.34 / 180.\n return map[string]float64{\"lat\": y, \"lon\": x}\n\n}", "func (e *GT) Unmarshal(m []byte) error {\n\t// Each value is a 256-bit number.\n\tconst numBytes = 256 / 8\n\n\tif len(m) != 12*numBytes {\n\t\treturn errors.New(\"bn256.GT: incorrect data length\")\n\t}\n\n\tif e.p == nil {\n\t\te.p = &gfP12{}\n\t}\n\n\te.p.x.x.x.Unmarshal(m)\n\te.p.x.x.y.Unmarshal(m[numBytes:])\n\te.p.x.y.x.Unmarshal(m[2*numBytes:])\n\te.p.x.y.y.Unmarshal(m[3*numBytes:])\n\te.p.x.z.x.Unmarshal(m[4*numBytes:])\n\te.p.x.z.y.Unmarshal(m[5*numBytes:])\n\te.p.y.x.x.Unmarshal(m[6*numBytes:])\n\te.p.y.x.y.Unmarshal(m[7*numBytes:])\n\te.p.y.y.x.Unmarshal(m[8*numBytes:])\n\te.p.y.y.y.Unmarshal(m[9*numBytes:])\n\te.p.y.z.x.Unmarshal(m[10*numBytes:])\n\te.p.y.z.y.Unmarshal(m[11*numBytes:])\n\tmontEncode(&e.p.x.x.x, &e.p.x.x.x)\n\tmontEncode(&e.p.x.x.y, &e.p.x.x.y)\n\tmontEncode(&e.p.x.y.x, &e.p.x.y.x)\n\tmontEncode(&e.p.x.y.y, &e.p.x.y.y)\n\tmontEncode(&e.p.x.z.x, &e.p.x.z.x)\n\tmontEncode(&e.p.x.z.y, &e.p.x.z.y)\n\tmontEncode(&e.p.y.x.x, &e.p.y.x.x)\n\tmontEncode(&e.p.y.x.y, &e.p.y.x.y)\n\tmontEncode(&e.p.y.y.x, &e.p.y.y.x)\n\tmontEncode(&e.p.y.y.y, &e.p.y.y.y)\n\tmontEncode(&e.p.y.z.x, &e.p.y.z.x)\n\tmontEncode(&e.p.y.z.y, &e.p.y.z.y)\n\n\treturn nil\n}", "func (m *MeshBasicMaterial) JSObject() *js.Object { return m.p }", "func OctahedronGeometryFromJSObject(p *js.Object) *OctahedronGeometry {\n\treturn &OctahedronGeometry{p: p}\n}", "func latLon2Grid(lat, lon float64, from eDatum, to gGrid) (int, int) {\n\t// Datum data for Lat/Lon to TM conversion\n\ta := Datum[from].a\n\te := Datum[from].e // sqrt(esq);\n\tb := Datum[from].b\n\n\t//===============\n\t// Lat/Lon -> TM\n\t//===============\n\tslat1 := math.Sin(lat)\n\tclat1 := math.Cos(lat)\n\tclat1sq := clat1 * clat1\n\ttanlat1sq := slat1 * slat1 / clat1sq\n\te2 := e * e\n\te4 := e2 * e2\n\te6 := e4 * e2\n\teg := (e * a / b)\n\teg2 := eg\n\tl1 := 1 - e2/4 - 3*e4/64 - 5*e6/256\n\tl2 := 3*e2/8 + 3*e4/32 + 45*e6/1024\n\tl3 := 15*e4/256 + 45*e6/1024\n\tl4 := 35 * e6 / 3072\n\tM := a * (l1*lat - l2*math.Sin(2*lat) + l3*math.Sin(4*lat) - l4*math.Sin(6*lat))\n\t//double rho = a*(1-e2) / pow((1-(e*slat1)*(e*slat1)),1.5);\n\tnu := a / math.Sqrt(1-(e*slat1)*(e*slat1))\n\tp := lon - grid[to].lon0\n\tk0 := grid[to].k0\n\t// y = northing = K1 + K2p2 + K3p4, where\n\tK1 := M * k0\n\tK2 := k0 * nu * slat1 * clat1 / 2\n\tK3 := (k0 * nu * slat1 * clat1 * clat1sq / 24) * (5 - tanlat1sq + 9*eg2*clat1sq + 4*eg2*eg2*clat1sq*clat1sq)\n\t// ING north\n\tY := K1 + K2*p*p + K3*p*p*p*p - grid[to].falseN\n\n\t// x = easting = K4p + K5p3, where\n\tK4 := k0 * nu * clat1\n\tK5 := (k0 * nu * clat1 * clat1sq / 6) * (1 - tanlat1sq + eg2*clat1*clat1)\n\t// ING east\n\tX := K4*p + K5*p*p*p + grid[to].falseE\n\n\t// final rounded results\n\tE := int(X + 0.5)\n\tN := int(Y + 0.5)\n\treturn E, N\n}", "func (m *MeshStandardMaterial) JSObject() *js.Object { return m.p }", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func (p PolygonZMS) LinearRings() struct {\n\tSrid uint32\n\tPolzm PolygonZM\n} {\n\treturn p\n}", "func Pentagonal(n int) int{\r\n\treturn n*((3*n)-1)/2\r\n}", "func ToCoordinate(l latlong.LatLonger) Coordinate {\n\trlat, rlon := rad(l.Lat()), rad(l.Lon())\n\n\treturn Coordinate{\n\t\tX: deg(math.Cos(rlat) * math.Cos(rlon)),\n\t\tY: deg(math.Cos(rlat) * math.Sin(rlon)),\n\t\tZ: deg(math.Sin(rlat)),\n\t}\n}", "func CreatePolygon(polygon [][][]float64, minp, maxp int) *Poly {\n\twest, south, east, north := 180.0, 90.0, -180.0, -90.0\n\tmaxpmap := map[string]string{}\n\tfor _, cont := range polygon {\n\t\tfor _, pt := range cont {\n\t\t\tx, y := pt[0], pt[1]\n\t\t\t// can only be one condition\n\t\t\t// using else if reduces one comparison\n\t\t\tif x < west {\n\t\t\t\twest = x\n\t\t\t} else if x > east {\n\t\t\t\teast = x\n\t\t\t}\n\n\t\t\tif y < south {\n\t\t\t\tsouth = y\n\t\t\t} else if y > north {\n\t\t\t\tnorth = y\n\t\t\t}\n\t\t\tghash := Geohash(pt, maxp)\n\t\t\tmaxpmap[ghash] = \"\"\n\t\t}\n\t}\n\n\t// logic for creating the smaller maps of each geohash\n\tcurrentmap := maxpmap\n\ttotalmap := map[int]map[string]string{}\n\ttotalmap[maxp] = maxpmap\n\tfor i := maxp - 1; i >= minp; i-- {\n\t\tnewmap := map[string]string{}\n\t\tfor k := range currentmap {\n\t\t\tnewmap[k[:len(k)-1]] = \"\"\n\t\t}\n\t\ttotalmap[i] = newmap\n\t\tcurrentmap = newmap\n\t}\n\n\treturn &Poly{\n\t\tPolygon: polygon,\n\t\tExtrema: Extrema{N: north, S: south, E: east, W: west},\n\t\tMap: totalmap,\n\t\tMin: minp,\n\t\tMax: maxp,\n\t}\n}", "func linearMap() {\n\tdt := 1.0\n\talpha := 0.01\n\tn := 1000\n\tN := make([]float64, n)\n\n\tN[0] = 0.0001\n\n\tfor i := 1; i < n; i++ {\n\t\tN[i] = N[i-1] * (1 + alpha*dt)\n\t}\n\n\twrite(N)\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func (g GeoPoint) MilesTo(point GeoPoint) float64 {\n\treturn g.RadiansTo(point) * 3958.8\n}", "func PolyMin(k float64) MinFunc {\n\treturn func(a, b float64) float64 {\n\t\treturn poly(a, b, k)\n\t}\n}", "func (crs AlbersEqualAreaConic) ToLonLat(east, north float64, gs GeodeticSpheroid) (lon, lat float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\teast -= crs.Eastf\n\tnorth -= crs.Northf\n\tρi := math.Sqrt(east*east + math.Pow(crs._ρ(radian(crs.Latf), s)-north, 2))\n\tqi := (crs._C(s) - ρi*ρi*crs._n(s)*crs._n(s)/s.A2()) / crs._n(s)\n\tφ := math.Asin(qi / 2)\n\tfor i := 0; i < 5; i++ {\n\t\tφ += math.Pow(1-s.E2()*sin2(φ), 2) /\n\t\t\t(2 * math.Cos(φ)) * (qi/(1-s.E2()) -\n\t\t\tmath.Sin(φ)/(1-s.E2()*sin2(φ)) +\n\t\t\t1/(2*s.E())*math.Log((1-s.E()*math.Sin(φ))/(1+s.E()*math.Sin(φ))))\n\t}\n\tθ := math.Atan(east / (crs._ρ(radian(crs.Latf), s) - north))\n\treturn degree(radian(crs.Lonf) + θ/crs._n(s)), degree(φ)\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func Pow12(in *big.Float) *big.Float {\n\treturn Pow(in, 12)\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\n\tret := make([]byte, 1+byteLen)\n\tret[0] = 2 // compressed point\n\n\txBytes := x.Bytes()\n\tcopy(ret[1+byteLen-len(xBytes):], xBytes)\n\tret[0] += byte(y.Bit(0))\n\treturn ret\n}" ]
[ "0.5804648", "0.56931895", "0.5389444", "0.5275881", "0.5147504", "0.4998657", "0.497802", "0.49655664", "0.49521396", "0.49195278", "0.487392", "0.48720428", "0.48540086", "0.48172206", "0.4795784", "0.4760868", "0.4749574", "0.47306368", "0.47300404", "0.47182947", "0.47105595", "0.4691122", "0.46765828", "0.46597692", "0.46514764", "0.46325624", "0.4626302", "0.46229053", "0.46201974", "0.46114382", "0.45920324", "0.4585565", "0.45505428", "0.45460778", "0.4534083", "0.45198113", "0.45157206", "0.45078012", "0.44738787", "0.44574973", "0.43920562", "0.43920562", "0.439117", "0.43889678", "0.43826327", "0.438187", "0.43810797", "0.43620425", "0.43578485", "0.43502116", "0.4343535", "0.43339396", "0.43320116", "0.43264413", "0.4319141", "0.43019703", "0.42992836", "0.4282882", "0.42825326", "0.42720672", "0.427185", "0.4258921", "0.42550373", "0.42460418", "0.42328954", "0.4226538", "0.4220217", "0.4216378", "0.4206987", "0.4199072", "0.41888", "0.4173445", "0.41713148", "0.4168344", "0.41576913", "0.41565704", "0.41392708", "0.4137338", "0.41306245", "0.4120332", "0.41190785", "0.4112288", "0.41058666", "0.4104645", "0.40951577", "0.4092475", "0.40910798", "0.4090676", "0.4081009", "0.4077653", "0.40727833", "0.40666744", "0.40648353", "0.40604883", "0.4058781", "0.40557808", "0.40521842", "0.40511674", "0.40441638", "0.40434533" ]
0.7422653
0
polyFromMsg converts a msg into polynomial representation
func polyFromMsg(msg []byte) Poly { var p Poly for i := 0; i < n/8; i++ { for j := 0; j < 8; j++ { mask := -int16((msg[i] >> j) & 1) p[8*i+j] = mask & int16((q+1)/2) } } return p }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func DecodeMsg(data []byte, expectedFlags uint8) (interface{}, error) {\n\tif len(data) < 1 {\n\t\treturn nil, fmt.Errorf(\"wrong message\")\n\t}\n\tvar ret Message\n\n\tmsgType := MessageType(data[0])\n\tif uint8(msgType)&expectedFlags == 0 {\n\t\treturn nil, fmt.Errorf(\"unexpected message\")\n\t}\n\n\tswitch msgType {\n\tcase msgTypeChunk:\n\t\tret = &MsgChunk{}\n\n\tcase msgTypePostTransaction:\n\t\tret = &MsgPostTransaction{}\n\n\tcase msgTypeSubscribe:\n\t\tret = &MsgUpdateSubscriptions{}\n\n\tcase msgTypeGetConfirmedTransaction:\n\t\tret = &MsgGetConfirmedTransaction{}\n\n\tcase msgTypeGetTxInclusionState:\n\t\tret = &MsgGetTxInclusionState{}\n\n\tcase msgTypeGetBacklog:\n\t\tret = &MsgGetBacklog{}\n\n\tcase msgTypeSetID:\n\t\tret = &MsgSetID{}\n\n\tcase msgTypeTransaction:\n\t\tret = &MsgTransaction{}\n\n\tcase msgTypeTxInclusionState:\n\t\tret = &MsgTxInclusionState{}\n\n\tcase msgTypeGetConfirmedOutput:\n\t\tret = &MsgGetConfirmedOutput{}\n\n\tcase msgTypeGetUnspentAliasOutput:\n\t\tret = &MsgGetUnspentAliasOutput{}\n\n\tcase msgTypeOutput:\n\t\tret = &MsgOutput{}\n\n\tcase msgTypeUnspentAliasOutput:\n\t\tret = &MsgUnspentAliasOutput{}\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown message type %d\", msgType)\n\t}\n\tif err := ret.Read(marshalutil.New(data[1:])); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func MakeParamsFromMsg(params map[string]interface{}, paramName string, msg proto.Message) error {\n\tcv := make(map[string]interface{})\n\n\tinrec, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjson.Unmarshal(inrec, &cv)\n\n\tparams[paramName] = cv\n\n\treturn nil\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func (p *protocol) readMsg() (tcp.ProtocolMessage, error) {\n\tvar header [8]byte\n\n\tif _, err := p.conn.Read(header[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Grab length of message\n\tbodyLength := binary.BigEndian.Uint32(header[4:8])\n\n\tvar newFunc func(tcp.Connection, uint32) (tcp.ProtocolMessage, error)\n\tswitch {\n\tcase bytes.Equal(header[0:4], []byte(\"????\")): // UNKN\n\t\tnewFunc = newProtocolUNKN\n\tcase bytes.Equal(header[0:4], []byte(\"HELO\")):\n\t\tnewFunc = newProtocolHELO\n\tcase bytes.Equal(header[0:4], []byte(\"VERS\")):\n\t\tnewFunc = newProtocolVERS\n\tcase bytes.Equal(header[0:4], []byte(\"PING\")):\n\t\tnewFunc = newProtocolPING\n\tcase bytes.Equal(header[0:4], []byte(\"PONG\")):\n\t\tnewFunc = newProtocolPONG\n\tcase bytes.Equal(header[0:4], []byte(\"ACKN\")):\n\t\tnewFunc = newProtocolACKN\n\tcase bytes.Equal(header[0:4], []byte(\"JDAT\")):\n\t\tif p.isClient {\n\t\t\treturn nil, errors.New(\"protocol error: Unexpected JDAT message received on client connection\")\n\t\t}\n\t\tnewFunc = newProtocolJDAT\n\tcase bytes.Equal(header[0:4], []byte(\"EVNT\")):\n\t\tif p.isClient {\n\t\t\treturn nil, errors.New(\"protocol error: Unexpected JDAT message received on client connection\")\n\t\t}\n\t\tnewFunc = newProtocolEVNT\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unexpected message code: %s\", header[0:4])\n\t}\n\n\treturn newFunc(p.conn, bodyLength)\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func EncodeMsg(pb proto.Message) ([]byte, error) {\n\tif um, ok := pb.(p2p.Wrapper); ok {\n\t\tpb = um.Wrap()\n\t}\n\tbz, err := proto.Marshal(pb)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to marshal %T: %w\", pb, err)\n\t}\n\n\treturn bz, nil\n}", "func newMsg(t string) ([]byte, error) {\n\tswitch t {\n\tcase \"version\":\n\t\treturn newVersion()\n\tcase \"verack\":\n\t\treturn newVerack()\n\tcase \"getheaders\":\n\t\treturn newHeadersReq()\n\tcase \"getaddr\":\n\t\treturn newGetAddr()\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func protoPlainMsgToMessage(msg *bpb.PlainChatMessage) (db.Message, error) {\n\tm := db.Message{\n\t\tID: msg.MessageID,\n\t\tMessage: msg.Message,\n\t\tCreatedAt: msg.CreatedAt,\n\t\tVersion: uint(msg.Version),\n\t\tGroupChatID: msg.GroupChatID,\n\t}\n\n\tif msg.AddUserPrivChat != nil {\n\t\tm.AddUserToChat = &db.AddUserToChat{}\n\t\tm.AddUserToChat.ChatID = msg.AddUserPrivChat.ChatID\n\t\tfor _, user := range msg.AddUserPrivChat.Users {\n\t\t\tm.AddUserToChat.Users = append(m.AddUserToChat.Users, user)\n\t\t}\n\t\tm.AddUserToChat.ChatName = msg.AddUserPrivChat.GroupName\n\t}\n\n\tif isDAppMessage(msg) {\n\t\tm.DApp = &db.DAppMessage{\n\t\t\tDAppPublicKey: msg.DAppPublicKey,\n\t\t\tType: msg.Type,\n\t\t\tParams: map[string]interface{}{},\n\t\t}\n\t\t// unmarshal params\n\t\tif msg.Params != nil {\n\t\t\tif err := json.Unmarshal(msg.Params, &m.DApp.Params); err != nil {\n\t\t\t\treturn db.Message{}, err\n\t\t\t}\n\t\t}\n\t\t// make sure that there is no message text\n\t\t// since the protocol doesn't allow it\n\t\tm.Message = nil\n\t}\n\n\treturn m, nil\n\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func NewOperationMsg(msg sdk.Msg, ok bool, comment string) OperationMsg {\n\tmsgType := sdk.MsgTypeURL(msg)\n\tmoduleName := sdk.GetModuleNameFromTypeURL(msgType)\n\tif moduleName == \"\" {\n\t\tmoduleName = msgType\n\t}\n\tprotoBz, err := proto.Marshal(msg)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"failed to marshal proto message: %w\", err))\n\t}\n\n\treturn NewOperationMsgBasic(moduleName, msgType, comment, ok, protoBz)\n}", "func Msg2Map(msg proto.Message) map[string]interface{} {\n\tt := reflect.TypeOf(msg)\n\tv := reflect.ValueOf(msg)\n\n\treturn buildStruct(t, v)\n}", "func GetMsgFromParam(params graphql.ResolveParams, paramName string, msg proto.Message) error {\n\tci, isok := params.Args[paramName].(map[string]interface{})\n\tif !isok {\n\t\treturn ErrParamIsNotMap\n\t}\n\n\tif err := mapstructure.Decode(ci, msg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DecodeMsg(bz []byte) (proto.Message, error) {\n\tpb := &bcproto.Message{}\n\n\terr := proto.Unmarshal(bz, pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pb.Unwrap()\n}", "func parseMsg(message string, terms []string) ([]byte, []string, string, []*db.WebLink) {\n\tl := createMsgLexer(\"msgLex\", message, LexMsg)\n\tslashTag := \"\"\n\tweblinks := []*db.WebLink{}\n\tvar seen map[string]bool\n\tvar item lex.Item\n\tvar val string\n\tvar prefix string\n\tdomly := db.Domly{}\n\n\tfor {\n\t\titem = <-l.Items\n\t\tswitch item.Typ {\n\t\tcase ItemWord:\n\t\t\tprefix = db.WordTerm\n\t\tcase ItemEspraURI:\n\t\t\tprefix = db.EspraURITerm\n\t\tcase ItemHashTag:\n\t\t\tprefix = db.HashTagTerm\n\t\tcase ItemURI:\n\t\t\tprefix = db.URITerm\n\t\tcase ItemSlashTag:\n\t\t\tprefix = db.SlashTagTerm\n\t\t}\n\n\t\tval = prefix + strings.ToLower(item.Val)\n\t\tif !seen[val] {\n\t\t\tseen[val] = true\n\t\t}\n\t\tterms = append(terms, item.Val)\n\n\t}\n\treturn []byte(\"[]\"), terms, slashTag, weblinks\n}", "func PolyMpq(q []MpqT, t []TermT) TermT {\n\tcount := C.uint32_t(len(q))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpqp(count, (*C.mpq_t)(&q[0]), (*C.term_t)(&t[0])))\n}", "func (mp JSONMsgPacker) UnpackMsg(data []byte, msg interface{}) error {\n\terr := json.Unmarshal(data, msg)\n\treturn err\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func (mp JSONMsgPacker) PackMsg(msg interface{}, buf []byte) ([]byte, error) {\n\tbuffer := bytes.NewBuffer(buf)\n\tjsonEncoder := json.NewEncoder(buffer)\n\terr := jsonEncoder.Encode(msg)\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tbuf = buffer.Bytes()\n\treturn buf[:len(buf)-1], nil // encoder always put '\\n' at the end, we trim it\n}", "func msgToKey(m *dns.Msg) (b []byte) {\n\tq := m.Question[0]\n\tname := q.Name\n\tb = make([]byte, packedMsgLenSz+packedMsgLenSz+len(name))\n\n\t// Put QTYPE, QCLASS, and QNAME.\n\tbinary.BigEndian.PutUint16(b, q.Qtype)\n\tbinary.BigEndian.PutUint16(b[packedMsgLenSz:], q.Qclass)\n\tcopy(b[2*packedMsgLenSz:], strings.ToLower(name))\n\n\treturn b\n}", "func Test005ConversionToAndFromMsgpackAndJson(t *testing.T) {\n\n\tcv.Convey(`from gl we should be able to create a known Go struct,\n\ntype Event struct {\n\tId int\n\tUser Person\n\tFlight string\n\tPilot []string\n}\n\n Event{}, and fill in its fields`, t, func() {\n\t\tevent := `(eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`\n\t\tenv := NewZlisp()\n\t\tdefer env.Close()\n\n\t\tenv.StandardSetup()\n\n\t\tx, err := env.EvalString(event)\n\t\tpanicOn(err)\n\n\t\tcv.So(x.SexpString(nil), cv.ShouldEqual, ` (eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`)\n\n\t\tjsonBy := SexpToJson(x)\n\t\tcv.So(string(jsonBy), cv.ShouldEqual, `{\"Atype\":\"eventdemo\", \"id\":123, \"user\":{\"Atype\":\"persondemo\", \"first\":\"Liz\", \"last\":\"C\", \"zKeyOrder\":[\"first\", \"last\"]}, \"flight\":\"AZD234\", \"pilot\":[\"Roger\", \"Ernie\"], \"cancelled\":true, \"zKeyOrder\":[\"id\", \"user\", \"flight\", \"pilot\", \"cancelled\"]}`)\n\t\tmsgpack, goObj := SexpToMsgpack(x)\n\t\t// msgpack field ordering is random, so can't expect a match the serialization byte-for-byte\n\t\t//cv.So(msgpack, cv.ShouldResemble, expectedMsgpack)\n\t\tgoObj2, err := MsgpackToGo(msgpack)\n\t\tpanicOn(err)\n\t\t// the ordering of jsonBack is canonical, so won't match ours\n\t\t// cv.So(string(jsonBack), cv.ShouldResemble, `{\"id\":123, \"user\":{\"first\":\"Liz\", \"last\":\"C\"}, \"flight\":\"AZD234\", \"pilot\":[\"Roger\", \"Ernie\"]}`)\n\n\t\tfmt.Printf(\"goObj = '%#v'\\n\", goObj)\n\t\tfmt.Printf(\"goObj2 = '%#v'\\n\", goObj2)\n\n\t\tcv.So(goObj, cv.ShouldResemble, goObj2)\n\n\t\tiface, err := MsgpackToGo(msgpack)\n\t\tpanicOn(err)\n\t\tsexp, err := GoToSexp(iface, env)\n\t\tpanicOn(err)\n\t\t// must get into same order to have sane comparison, so borrow the KeyOrder to be sure.\n\t\thhh := sexp.(*SexpHash)\n\t\thhh.KeyOrder = x.(*SexpHash).KeyOrder\n\t\tsexpStr := sexp.SexpString(nil)\n\t\texpectedSexpr := ` (eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`\n\t\tcv.So(sexpStr, cv.ShouldResemble, expectedSexpr)\n\n\t\tfmt.Printf(\"\\n Unmarshaling from msgpack into pre-defined go struct should succeed.\\n\")\n\n\t\tvar goEvent Event\n\t\tdec := codec.NewDecoderBytes(msgpack, &msgpHelper.mh)\n\t\terr = dec.Decode(&goEvent)\n\t\tpanicOn(err)\n\t\tfmt.Printf(\"from msgpack, goEvent = '%#v'\\n\", goEvent)\n\t\tcv.So(goEvent.Id, cv.ShouldEqual, 123)\n\t\tcv.So(goEvent.Flight, cv.ShouldEqual, \"AZD234\")\n\t\tcv.So(goEvent.Pilot[0], cv.ShouldEqual, \"Roger\")\n\t\tcv.So(goEvent.Pilot[1], cv.ShouldEqual, \"Ernie\")\n\t\tcv.So(goEvent.User.First, cv.ShouldEqual, \"Liz\")\n\t\tcv.So(goEvent.User.Last, cv.ShouldEqual, \"C\")\n\n\t\tgoEvent = Event{}\n\t\tjdec := codec.NewDecoderBytes([]byte(jsonBy), &msgpHelper.jh)\n\t\terr = jdec.Decode(&goEvent)\n\t\tpanicOn(err)\n\t\tfmt.Printf(\"from json, goEvent = '%#v'\\n\", goEvent)\n\t\tcv.So(goEvent.Id, cv.ShouldEqual, 123)\n\t\tcv.So(goEvent.Flight, cv.ShouldEqual, \"AZD234\")\n\t\tcv.So(goEvent.Pilot[0], cv.ShouldEqual, \"Roger\")\n\t\tcv.So(goEvent.Pilot[1], cv.ShouldEqual, \"Ernie\")\n\t\tcv.So(goEvent.User.First, cv.ShouldEqual, \"Liz\")\n\t\tcv.So(goEvent.User.Last, cv.ShouldEqual, \"C\")\n\t\tcv.So(goEvent.Cancelled, cv.ShouldEqual, true)\n\n\t\tfmt.Printf(\"\\n And directly from Go to S-expression via GoToSexp() should work.\\n\")\n\t\tsexp2, err := GoToSexp(goObj2, env)\n\t\tcv.So(sexp2.SexpString(nil), cv.ShouldEqual, expectedSexpr)\n\t\tfmt.Printf(\"\\n Result: directly from Go map[string]interface{} -> sexpr via GoMapToSexp() produced: '%s'\\n\", sexp2.SexpString(nil))\n\n\t\tfmt.Printf(\"\\n And the reverse direction, from S-expression to go map[string]interface{} should work.\\n\")\n\t\tgoMap3 := SexpToGo(sexp2, env, nil).(map[string]interface{})\n\n\t\t// detailed diff\n\t\tgoObj2map := goObj2.(map[string]interface{})\n\n\t\t// looks like goMap3 has an int, whereas goObj2map has an int64\n\n\t\t// compare goMap3 and goObj2\n\t\tfor k3, v3 := range goMap3 {\n\t\t\tv2 := goObj2map[k3]\n\t\t\tcv.So(v3, cv.ShouldResemble, v2)\n\t\t}\n\n\t\tfmt.Printf(\"\\n Directly Sexp -> msgpack -> pre-established Go struct Event{} should work.\\n\")\n\n\t\tswitch asHash := sexp2.(type) {\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"value must be a hash or defmap\")\n\t\t\tpanic(err)\n\t\tcase *SexpHash:\n\t\t\ttn := asHash.TypeName\n\t\t\tfactory, hasMaker := GoStructRegistry.Registry[tn]\n\t\t\tif !hasMaker {\n\t\t\t\terr = fmt.Errorf(\"type '%s' not registered in GoStructRegistry\", tn)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tnewStruct, err := factory.Factory(env, asHash)\n\t\t\tpanicOn(err)\n\n\t\t\t// What didn't work here was going through msgpack, because\n\t\t\t// ugorji msgpack encode, when writing, will turn signed ints into unsigned ints,\n\t\t\t// which is a problem for msgp decoding. Hence cut out the middle men\n\t\t\t// and decode straight from jsonBytes into our newStruct.\n\t\t\tjsonBytes := []byte(SexpToJson(asHash))\n\n\t\t\tjsonDecoder := json.NewDecoder(bytes.NewBuffer(jsonBytes))\n\t\t\terr = jsonDecoder.Decode(newStruct)\n\t\t\tswitch err {\n\t\t\tcase io.EOF:\n\t\t\tcase nil:\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"error during jsonDecoder.Decode() on type '%s': '%s'\", tn, err))\n\t\t\t}\n\t\t\tasHash.SetGoStructFactory(factory)\n\n\t\t\tfmt.Printf(\"from json via factory.Make(), newStruct = '%#v'\\n\", newStruct)\n\t\t\tcv.So(newStruct, cv.ShouldResemble, &goEvent)\n\t\t}\n\t})\n}", "func NewProtoMessage(msg proto.Message) (starlark.Value, error) {\n\treturn protomodule.NewMessage(msg)\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func unmarshalMessage(buf []byte) (*pb.KVRequest, *pb.KVResponse, *pb.Msg, error) {\n\treqMsg := pb.Msg{}\n\treqPay := pb.KVRequest{}\n\tresPay := pb.KVResponse{}\n\n\terr := proto.Unmarshal(buf, &reqMsg)\n\tif err != nil {\n\t\tfmt.Println(self.Addr.String(), \"unmarshalMessage Failed to unmarshal \", len(buf))\n\t\treturn nil, nil, nil, err\n\t}\n\n\tcheckSum := getChecksum(reqMsg.MessageID, reqMsg.Payload)\n\tif checkSum != reqMsg.CheckSum {\n\t\treturn nil, nil, nil, fmt.Errorf(\"wrong checksum\")\n\t}\n\n\tif reqMsg.Type == 1 {\n\t\t// response\n\t\terr = proto.Unmarshal(reqMsg.Payload, &resPay)\n\t\tif err == nil {\n\t\t\treturn nil, &resPay, &reqMsg, nil\n\t\t} else {\n\t\t\tfmt.Println(\"unmarshalMessage, failed to unmarshal response \", err)\n\t\t}\n\t} else if reqMsg.Type == 0 {\n\t\t// request\n\t\terr = proto.Unmarshal(reqMsg.Payload, &reqPay)\n\t\tif err == nil {\n\t\t\treturn &reqPay, nil, &reqMsg, nil\n\t\t}else {\n\t\t\tfmt.Println(\"unmarshalMessage, failed to unmarshal request \", err)\n\t\t}\n\t} else if reqMsg.Type == 2 {\n\t\t// ack\n\t}\n\treturn nil, nil, nil, err\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func decode(msg mqtt.Message) (*driver.Message, error) {\n\tif msg == nil {\n\t\treturn nil, errInvalidMessage\n\t}\n\n\tvar dm driver.Message\n\tif err := decodeMessage(msg.Payload(), &dm); err != nil {\n\t\treturn nil, err\n\t}\n\tdm.AckID = msg.MessageID() // uint16\n\tdm.AsFunc = messageAsFunc(msg)\n\treturn &dm, nil\n}", "func _messsageDecode(b *[]byte) (*Message, error) {\n\n\tmessage := Message{}\n\n\tmsg := bytes.Split(*b, elemSep)\n\t// if the length of msg slice is less than the message is invalid\n\tif len(msg) < 2 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : invalid msg len %d\", len(msg)))\n\t}\n\n\t// elemCount counts the number of elements added to the message like MsgType,Msg etc..\n\t// the elemCount should be equal to len(msg) after the loop coming\n\tvar elemCount int\n\n\t// loop until the last element\n\t// the last element is the payload\n\tfor index, element := range msg {\n\n\t\tif (index + 1) == len(msg) {\n\n\t\t\tmessage.Msg = element\n\t\t\telemCount++\n\t\t\tbreak\n\n\t\t}\n\n\t\telem := bytes.Split(element, keyValSep)\n\n\t\tif len(elem) < 2 {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : invalid length %d elemCounted %d\",len(elem),elemCount))\n\t\t}\n\n\t\t// find the approprite elem of message\n\t\t// if unknown elem is sent then this is an errors\n\t\tswitch string(elem[0]) {\n\n\t\tcase \"ClientID\":\n\n\t\t\tmessage.ClientID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"ReceiverID\":\n\n\t\t\tmessage.ReceiverID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"RoomID\":\n\n\t\t\tmessage.RoomID = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"Info\":\n\n\t\t\tmessage.Info = string(elem[1])\n\t\t\telemCount++\n\n\t\tcase \"MsgType\":\n\n\t\t\tmsgType, err := strconv.ParseInt(string(elem[1]), 10, 16)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tmessage.MsgType = int(msgType)\n\t\t\telemCount++\n\n\t\tdefault: // unknown elemetn which is a error\n\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid message : Unknown Elem(%s)\", string(elem[0])))\n\n\t\t} // switch case ends\n\n\t} // for loop ends\n\n\tif elemCount != len(msg) {\n\t\treturn nil, errors.New(\"Invalid message\")\n\t}\n\n\t// Now we have a valid message\n\n\treturn &message, nil\n\n}", "func (order *Order) FromBinary(msg []byte) error {\n\treturn proto.Unmarshal(msg, order)\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func (c *JSONCodec) ReceiveMsg() (network.PackInf, error) {\n\tvar msg jsonIn\n\terr := c.decoder.Decode(&msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar body interface{}\n\tif msg.Head != \"\" {\n\t\tif t, ok := c.p.types[msg.Head]; ok {\n\t\t\tbody = reflect.New(t).Interface()\n\t\t}\n\t}\n\tjson.Unmarshal(msg.Body, body)\n\tpack := new(network.BasePack)\n\tpack.SetPackBody(body)\n\treturn pack, nil\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func boxToPoly(b Box2d) polygon {\n\tcen_x, cen_y := b.Position()\n\twidth, height := b.Size()\n\tangle := b.AngleDegrees()\n\n\tpoints := [4]point{}\n\n\tpoints[0] = point{X: getX(-width/2, -height/2, angle) + cen_x,\n\t\tY: getY(-width/2, -height/2, angle) + cen_y}\n\n\tpoints[1] = point{X: getX(width/2, -height/2, angle) + cen_x,\n\t\tY: getY(width/2, -height/2, angle) + cen_y}\n\n\tpoints[2] = point{X: getX(-width/2, height/2, angle) + cen_x,\n\t\tY: getY(-width/2, height/2, angle) + cen_y}\n\n\tpoints[3] = point{X: getX(width/2, height/2, angle) + cen_x,\n\t\tY: getY(width/2, height/2, angle) + cen_y}\n\tz := boxPoly{points: points[:4]}\n\n\treturn z\n}", "func (c *codec) ReadMessage(msg *birpc.Message) error {\n\tc.rmu.Lock()\n\tdefer c.rmu.Unlock()\n\n\tfor {\n\t\tif c.sub == nil {\n\t\t\terr := c.setupSubscription()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tresult, err := c.sub.Pop()\n\t\tif err != nil {\n\t\t\tc.sub = nil\n\t\t\treturn err\n\t\t}\n\n\t\tif result.Value.IsNil() {\n\t\t\tcontinue\n\t\t}\n\n\t\tb := result.Value.Bytes()\n\t\tm := &mpc.Message{}\n\t\t_, err = m.UnmarshalMsg(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsg.ID = m.ID\n\t\tmsg.Func = m.Func\n\t\tmsg.Args = m.Args\n\t\tmsg.Result = m.Result\n\t\tif m.Error != nil {\n\t\t\t*msg.Error = birpc.Error{Msg: m.Error.Msg}\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func RecvMsg(miningConn MiningConn) (Message, error) {\n\tvar msg Message\n\terr := miningConn.Dec.Decode(&msg)\n\treturn msg, err\n}", "func (c *channel) pubMsgToMsgProto(pm *pb.PubMsg, seq uint64) *pb.MsgProto {\n\tm := &pb.MsgProto{\n\t\tSequence: seq,\n\t\tSubject: pm.Subject,\n\t\tReply: pm.Reply,\n\t\tData: pm.Data,\n\t\tTimestamp: time.Now().UnixNano(),\n\t}\n\tif c.lTimestamp > 0 && m.Timestamp < c.lTimestamp {\n\t\tm.Timestamp = c.lTimestamp\n\t}\n\tc.lTimestamp = m.Timestamp\n\treturn m\n}", "func decodeMessage(bz []byte) (msgType byte, msg interface{}) {\n\tn, err := new(int64), new(error)\n\t// log.Debug(\"decoding msg bytes: %X\", bz)\n\tmsgType = bz[0]\n\tswitch msgType {\n\tcase msgTypeBlockPart:\n\t\tmsg = readBlockPartMessage(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeKnownBlockParts:\n\t\tmsg = readKnownBlockPartsMessage(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVote:\n\t\tmsg = ReadVote(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVoteAskRank:\n\t\tmsg = ReadVote(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVoteRank:\n\t\tmsg = readVoteRankMessage(bytes.NewReader(bz[1:]), n, err)\n\tdefault:\n\t\tmsg = nil\n\t}\n\treturn\n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\treturn codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)\n}", "func getMessage(doc bson.M) (*kafka.Message, error) {\n\tmsgValue, err := ConvertToOldFormat(doc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toutput, err := json.Marshal(msgValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg := kafka.Message{Value: output}\n\treturn &msg, nil\n}", "func RandomPolynomial(r io.Reader, degree uint64) (*Polynomial, error) {\n\tcoefficients := []*big.Int{}\n\tfor i := uint64(0); i < degree+1; i++ {\n\t\tc, err := rand.Int(r, bn256.Order)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tcoefficients = append(coefficients, c)\n\t}\n\treturn NewPolynomial(coefficients)\n}", "func DecryptMsg(staticKeyPair noise.DHKey, peerStaticPublic []byte, msg string) (string, error) {\n\thandshake := newHandshake(staticKeyPair, peerStaticPublic, false)\n\tpayload, _, _, err := handshake.ReadMessage(make([]byte, 0), []byte(msg))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(payload), nil\n}", "func (v *RoomsOnlineMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecode20191OPGPlus2InternalPkgModels10(l, v)\n}", "func decodeMsgPack(buf []byte, out interface{}) error {\n\tr := bytes.NewBuffer(buf)\n\thd := MsgpackHandle{}\n\tdec := NewDecoder(r, &hd)\n\treturn dec.Decode(out)\n}", "func NewPolynomial(num int, b, step float64, a ...float64) model.Collection {\n\n\tpolynomial := NewPolynomialGenerator(b, step, a...)\n\tcollection := polynomial.Num(num)\n\n\treturn collection\n}", "func DecryptMsg(msg string, entList openpgp.EntityList) string {\n\tplain, err := base64.StdEncoding.DecodeString(msg)\n\tif err != nil {\n\t\tfmt.Println(\"Base64 Decode Fail.\")\n\t\tlog.Fatal(err)\n\t}\n\n\tmdigest, err := openpgp.ReadMessage(bytes.NewBuffer(plain), entList, nil, nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading message with key.\")\n\t\tlog.Fatal(err)\n\t}\n\n\tbytes, err := ioutil.ReadAll(mdigest.UnverifiedBody)\n\treturn string(bytes)\n}", "func Decode(msg []byte) (Message, error) {\n\tvar m Message\n\n\tl := len(msg)\n\n\t// trim trailing carriage return if present\n\tif l > 0 && msg[l-1] == '\\r' {\n\t\tl--\n\t\tmsg = msg[:l]\n\t}\n\n\tif l < 2 {\n\t\treturn m, errors.New(\"Decode: message too short\")\n\t}\n\n\tm.typ = codeToMsg[string(msg[:2])]\n\tif m.typ == MsgUnknown {\n\t\treturn m, fmt.Errorf(\"Decode: unknown message code: %q\", string(msg[:2]))\n\t}\n\n\tif l < minMsgLength[m.typ] {\n\t\treturn m, fmt.Errorf(\"Decode: message too short to contain required fields for %v: %d < %d\", m.typ, len(msg), minMsgLength[m.typ])\n\t}\n\n\tm.fields = make(map[fieldType]string)\n\tm.repeateableFields = make(map[fieldType][]string)\n\n\t// Parse fixed-length fields:\n\tp := 2 // byte position in message\n\tfor _, f := range msgDefinitions[m.typ].RequiredFixed {\n\t\tend := p + fixedFieldLengths[f] // end of token\n\t\tm.fields[f] = string(msg[p:end])\n\t\tp = end\n\t}\n\n\t// Parse variable-length fields:\nouter:\n\tfor len(msg) > p {\n\t\tstart := p + 2 // start of current field\n\t\tf := codeToField[string(msg[p:start])]\n\t\tp = start\n\t\tif f == FieldUnknown {\n\t\t\t// store unknown codes in message value\n\t\t\tstart -= 2\n\t\t}\n\n\t\tfor {\n\t\t\tr, w := utf8.DecodeRune(msg[p:])\n\t\t\tp += w\n\t\t\tif r == '|' {\n\t\t\t\tif repeatableField[f] {\n\t\t\t\t\tm.repeateableFields[f] = append(m.repeateableFields[f], string(msg[start:p-1]))\n\t\t\t\t} else {\n\t\t\t\t\tm.fields[f] = string(msg[start : p-1])\n\t\t\t\t}\n\t\t\t\tif p == l {\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t\tcontinue outer\n\t\t\t} else if p == l {\n\t\t\t\tif repeatableField[f] {\n\t\t\t\t\tm.repeateableFields[f] = append(m.repeateableFields[f], string(msg[start:l]))\n\t\t\t\t} else {\n\t\t\t\t\tm.fields[f] = string(msg[start:l])\n\t\t\t\t}\n\t\t\t\tbreak outer\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn m, nil\n}", "func (this *DtNavMesh) DecodePolyIdPoly(ref DtPolyRef) uint32 {\n\tpolyMask := (uint32(1) << this.m_polyBits) - 1\n\treturn (uint32(ref) & polyMask)\n}", "func CalcMessageHash12(msg []byte, protocol string) Hash12 {\n\treturn CalcHash12(append(msg, protocol...))\n}", "func outputProtoJSON(msg interface{}) {\n\tm := &jsonpb.Marshaler{EmitDefaults: true}\n\tif pMsg, ok := msg.(proto.Message); ok {\n\t\tstr, err := m.MarshalToString(pMsg)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(str)\n\t} else {\n\t\tfmt.Println(msg)\n\t\tpanic(\"Error: bad data received\")\n\t}\n}", "func (this *jsonEncodedInput) ReadBoltMsg(metadata *messages.BoltMsgMeta, contentStructs ...interface{}) (err error) {\n\tboltMsg := &messages.BoltMsg{\n\t\tBoltMsgJson: &messages.BoltMsgJson{\n\t\t\tBoltMsgMeta: metadata,\n\t\t\tContents: this.constructInput(contentStructs...),\n\t\t},\n\t}\n\terr = this.ReadMsg(boltMsg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tthis.decodeInput(boltMsg.BoltMsgJson.Contents, contentStructs...)\n\treturn nil\n}", "func fromJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar ctor starlark.Value\n\tvar text starlark.String\n\tif err := starlark.UnpackArgs(\"from_jsonpb\", args, kwargs, \"ctor\", &ctor, \"text\", &text); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, ok := ctor.(*messageCtor)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: got %s, expecting a proto message constructor\", ctor.Type())\n\t}\n\ttyp := c.typ\n\n\tprotoMsg := typ.NewProtoMessage().Interface().(proto.Message)\n\tu := jsonpb.Unmarshaler{AllowUnknownFields: true}\n\tif err := u.Unmarshal(strings.NewReader(text.GoString()), protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\n\tmsg := NewMessage(typ)\n\tif err := msg.FromProto(protoMsg); err != nil {\n\t\treturn nil, fmt.Errorf(\"from_jsonpb: %s\", err)\n\t}\n\treturn msg, nil\n}", "func (decNum *Decimal) UnmarshalMsgpack(b []byte) error {\n\t// Decimal values can be encoded to fixext MessagePack, where buffer\n\t// has a fixed length encoded by first byte, and ext MessagePack, where\n\t// buffer length is not fixed and encoded by a number in a separate\n\t// field:\n\t//\n\t// +--------+-------------------+------------+===============+\n\t// | MP_EXT | length (optional) | MP_DECIMAL | PackedDecimal |\n\t// +--------+-------------------+------------+===============+\n\tdigits, err := decodeStringFromBCD(b)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"msgpack: can't decode string from BCD buffer (%x): %w\", b, err)\n\t}\n\tdec, err := decimal.NewFromString(digits)\n\t*decNum = *NewDecimal(dec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"msgpack: can't encode string (%s) to a decimal number: %w\", digits, err)\n\t}\n\n\treturn nil\n}", "func msgToKeyWithSubnet(m *dns.Msg, ecsIP net.IP, mask int) (key []byte) {\n\tq := m.Question[0]\n\tkeyLen := keyIPIndex + len(q.Name)\n\tmasked := mask != 0\n\tif masked {\n\t\tkeyLen += len(ecsIP)\n\t}\n\n\t// Initialize the slice.\n\tkey = make([]byte, keyLen)\n\n\t// Put DO.\n\topt := m.IsEdns0()\n\tkey[0] = mathutil.BoolToNumber[byte](opt != nil && opt.Do())\n\n\t// Put Qtype.\n\t//\n\t// TODO(d.kolyshev): We should put Qtype in key[1:].\n\tbinary.BigEndian.PutUint16(key[:], q.Qtype)\n\n\t// Put Qclass.\n\tbinary.BigEndian.PutUint16(key[1+packedMsgLenSz:], q.Qclass)\n\n\t// Add mask.\n\tkey[keyMaskIndex] = uint8(mask)\n\tk := keyIPIndex\n\tif masked {\n\t\tk += copy(key[keyIPIndex:], ecsIP)\n\t}\n\n\tcopy(key[k:], strings.ToLower(q.Name))\n\n\treturn key\n}", "func Serialize(msg Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\tencoder := json.NewEncoder(&b)\n\terr := encoder.Encode(msg)\n\treturn b.Bytes(), err\n}", "func readMessage(r io.Reader) (value []byte, err error) {\n\treturn readProtoMsg(r, maxMsgSize)\n}", "func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}", "func readMessage(conn *websocket.Conn) (*data.Request, error) {\n\t// read message from client.\n\t_, bytes, err := conn.ReadMessage()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read message: %v\", err)\n\t}\n\n\t// handle the message if map or number.\n\tvar o interface{}\n\tif err := json.Unmarshal(bytes, &o); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal message %s: %v\", string(bytes), err)\n\t}\n\n\t// finally return a request model by bytes.\n\ttoReq := func(bytes []byte) (*data.Request, error) {\n\t\tvar r *data.Request\n\t\tif err := json.Unmarshal(bytes, &r); err != nil {\n\t\t\tlog.Printf(\"failed to unmarshal to request: %v\", err)\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn r, nil\n\t}\n\n\tswitch v := o.(type) {\n\tcase map[string]interface{}:\n\t\t// if the message is a json map, directly return.\n\t\treturn toReq(bytes)\n\tcase float64:\n\t\tif v == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\t// try read message with given count.\n\t\tvar buffer []byte\n\t\tfor i := 0; i < int(v); i++ {\n\t\t\t// append the bytes into buffer\n\t\t\t_, bytes, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to read message: %v\", err)\n\t\t\t}\n\t\t\tbuffer = append(buffer, bytes...)\n\t\t}\n\n\t\t// unmarshal the collected buffer.\n\t\treturn toReq(buffer)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid message: %v\", o)\n\t}\n}", "func MessageToJSON(msg Message) string {\n\tvar jl string\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjl = string(b)\n\treturn jl\n}", "func (eth *Eth) Msg(addr string, data []string) (string, error) {\n\tpacked := PackTxDataArgs(data...)\n\tkeys := eth.fetchKeyPair()\n\t//addr = ethutil.StripHex(addr)\n\tbyte_addr := ethutil.Hex2Bytes(addr)\n\thash, err := eth.pipe.Transact(keys, byte_addr, ethutil.NewValue(ethutil.Big(\"350\")), ethutil.NewValue(ethutil.Big(\"200000000000\")), ethutil.NewValue(ethutil.Big(\"1000000\")), []byte(packed))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ethutil.Bytes2Hex(hash), nil\n}", "func (rw *pssRPCRW) WriteMsg(msg p2p.Msg) error {\n\tlog.Trace(\"got writemsg pssclient\", \"msg\", msg)\n\tif rw.closed {\n\t\treturn fmt.Errorf(\"connection closed\")\n\t}\n\trlpdata := make([]byte, msg.Size)\n\tmsg.Payload.Read(rlpdata)\n\tpmsg, err := rlp.EncodeToBytes(pss.ProtocolMsg{\n\t\tCode: msg.Code,\n\t\tSize: msg.Size,\n\t\tPayload: rlpdata,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the keys we have\n\tvar symkeyids []string\n\terr = rw.Client.rpc.Call(&symkeyids, \"pss_getHandshakeKeys\", rw.pubKeyId, rw.topic, false, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check the capacity of the first key\n\tvar symkeycap uint16\n\tif len(symkeyids) > 0 {\n\t\terr = rw.Client.rpc.Call(&symkeycap, \"pss_getHandshakeKeyCapacity\", symkeyids[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = rw.Client.rpc.Call(nil, \"pss_sendSym\", symkeyids[0], rw.topic, hexutil.Encode(pmsg))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If this is the last message it is valid for, initiate new handshake\n\tif symkeycap == 1 {\n\t\tvar retries int\n\t\tvar sync bool\n\t\t// if it's the only remaining key, make sure we don't continue until we have new ones for further writes\n\t\tif len(symkeyids) == 1 {\n\t\t\tsync = true\n\t\t}\n\t\t// initiate handshake\n\t\t_, err := rw.handshake(retries, sync, false)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"failing\", \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewMessage(protoMessage *protobuf.Message) Message {\n\tm := &message{\n\t\tprotoMessage: protoMessage,\n\n\t\tfullyQualifiedName: \"\",\n\n\t\tnestedEnumNameToEnum: make(map[string]Enum),\n\t\tnestedMessageNameToMessage: make(map[string]Message),\n\n\t\tfieldNameToField: make(map[string]*MessageField),\n\t\toneofFieldNameToOneofField: make(map[string]Oneof),\n\t\tmapFieldNameToMapField: make(map[string]*MapField),\n\n\t\tlineToField: make(map[int]*MessageField),\n\t\tlineToOneofField: make(map[int]Oneof),\n\t\tlineToMapField: make(map[int]*MapField),\n\n\t\tmu: &sync.RWMutex{},\n\t}\n\n\tfor _, e := range protoMessage.Elements {\n\t\tswitch v := e.(type) {\n\n\t\tcase *protobuf.NormalField:\n\t\t\tf := NewMessageField(v)\n\t\t\tm.fields = append(m.fields, f)\n\n\t\tcase *protobuf.Oneof:\n\t\t\tf := NewOneof(v)\n\t\t\tm.oneofs = append(m.oneofs, f)\n\n\t\tcase *protobuf.MapField:\n\t\t\tf := NewMapField(v)\n\t\t\tm.mapFields = append(m.mapFields, f)\n\n\t\tdefault:\n\t\t}\n\t}\n\n\tfor _, f := range m.fields {\n\t\tm.fieldNameToField[f.ProtoField.Name] = f\n\t\tm.lineToField[f.ProtoField.Position.Line] = f\n\t}\n\n\tfor _, f := range m.oneofs {\n\t\tm.oneofFieldNameToOneofField[f.Protobuf().Name] = f\n\t\tm.lineToOneofField[f.Protobuf().Position.Line] = f\n\t}\n\n\tfor _, f := range m.mapFields {\n\t\tm.mapFieldNameToMapField[f.ProtoMapField.Name] = f\n\t\tm.lineToMapField[f.ProtoMapField.Position.Line] = f\n\t}\n\n\treturn m\n}", "func UnmarshalCapnpMessage(in io.Reader) (*capnp.Message, error) {\n\tdecompressor, _ := zlib.NewReader(in)\n\tdecoder := capnp.NewPackedDecoder(decompressor)\n\tmsg, err := decoder.Decode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn msg, nil\n}", "func NewMsg(typ string) Msg {\n\treturn Msg{\n\t\tID: uuid.New().String(),\n\t\tType: typ,\n\t\tTimestamp: time.Now().UTC(),\n\t}\n}", "func Unmarshal(curve elliptic.Curve, data []byte) (*big.Int, *big.Int)", "func ValidateMsg(pb proto.Message) error {\n\tif pb == nil {\n\t\treturn errors.New(\"message cannot be nil\")\n\t}\n\n\tswitch msg := pb.(type) {\n\tcase *bcproto.BlockRequest:\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\tcase *bcproto.BlockResponse:\n\t\t_, err := types.BlockFromProto(msg.Block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *bcproto.NoBlockResponse:\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\tcase *bcproto.StatusResponse:\n\t\tif msg.Base < 0 {\n\t\t\treturn errors.New(\"negative Base\")\n\t\t}\n\t\tif msg.Height < 0 {\n\t\t\treturn errors.New(\"negative Height\")\n\t\t}\n\t\tif msg.Base > msg.Height {\n\t\t\treturn fmt.Errorf(\"base %v cannot be greater than height %v\", msg.Base, msg.Height)\n\t\t}\n\tcase *bcproto.StatusRequest:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown message type %T\", msg)\n\t}\n\treturn nil\n}", "func makeRenderablePoly(name string, n int, drawType uint, color vec4) *Renderable {\n\t// build poly verts\n\tvertex := makePoly(n)\n\tr := &Renderable{\n\t\tworld.Transform(),\n\t\tworld.Operation(name, &world.Poly{Points: vertex}),\n\t\tworld.MaterialComponent{\n\t\t\tDrawType: drawType,\n\t\t\tProps: map[string]interface{}{\n\t\t\t\t\"color\": world.Color(color),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn r\n}", "func GetOfpMsgVersion(msg OfpMessage) (uint8, error) {\n\tb, err := msg.MarshalBinary()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn GetMessageVersion(b)\n}", "func (v *Msg) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels6(l, v)\n}", "func MsgKey(R, P *btcec.PublicKey, m []byte) *btcec.PublicKey {\n\th := Hash(R.SerializeCompressed(), m)\n\th = new(big.Int).Mod(new(big.Int).Neg(h), btcec.S256().N)\n\thP := new(btcec.PublicKey)\n\thP.X, hP.Y = btcec.S256().ScalarMult(P.X, P.Y, h.Bytes())\n\treturn SumPubs(R, hP)\n}", "func protoDec(t reflect.Type, in []byte) (T, error) {\n\tvar p protoreflect.ProtoMessage\n\tswitch it := reflect.New(t.Elem()).Interface().(type) {\n\tcase protoreflect.ProtoMessage:\n\t\tp = it\n\tcase protov1.Message:\n\t\tp = protov1.MessageV2(it)\n\t}\n\terr := protov2.UnmarshalOptions{}.Unmarshal(in, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p, nil\n}", "func ProtoRecv(ws *websocket.Conn, msg proto.Message) error {\n\tif ws == nil {\n\t\treturn fmt.Errorf(\"Empty websocket connection\")\n\t}\n\n\tmt, r, err := ws.NextReader()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif mt != websocket.BinaryMessage {\n\t\treturn fmt.Errorf(\"Only binary messages allowed\")\n\t}\n\n\tbuf, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proto.Unmarshal(buf, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ParseMessage(msg string) Message {\n\tvar message Message\n\tmsgBytes := []byte(msg)\n\terr := json.Unmarshal(msgBytes, &message)\n\thandleErr(err)\n\tfmt.Println(\"Person\", message)\n\treturn message\n}", "func (msg Msg) Decode(val interface{}) error {\n\ts := rlp.NewStream(msg.Payload, uint64(msg.Size))\n\tif err := s.Decode(val); err != nil {\n\t\treturn newPeerError(errInvalidMsg, \"(code %d) (size %d) %v\", msg.Code, msg.Size, err)\n\t\t// return errors.New(\"(code %x) (size %d) %v\")\n\t}\n\treturn nil\n}", "func stringToSpec(ja3 string) (*tls.ClientHelloSpec, error) {\n\ttokens := strings.Split(ja3, \",\")\n\n\tversion := tokens[0]\n\tciphers := strings.Split(tokens[1], \"-\")\n\textensions := strings.Split(tokens[2], \"-\")\n\tcurves := strings.Split(tokens[3], \"-\")\n\tif len(curves) == 1 && curves[0] == \"\" {\n\t\tcurves = []string{}\n\t}\n\tpointFormats := strings.Split(tokens[4], \"-\")\n\tif len(pointFormats) == 1 && pointFormats[0] == \"\" {\n\t\tpointFormats = []string{}\n\t}\n\n\t// parse curves\n\tvar targetCurves []tls.CurveID\n\tfor _, c := range curves {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetCurves = append(targetCurves, tls.CurveID(cid))\n\t}\n\textMap[\"10\"] = &tls.SupportedCurvesExtension{targetCurves}\n\n\t// parse point formats\n\tvar targetPointFormats []byte\n\tfor _, p := range pointFormats {\n\t\tpid, err := strconv.ParseUint(p, 10, 8)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetPointFormats = append(targetPointFormats, byte(pid))\n\t}\n\textMap[\"11\"] = &tls.SupportedPointsExtension{SupportedPoints: targetPointFormats}\n\n\t// build extenions list\n\tvar exts []tls.TLSExtension\n\tfor _, e := range extensions {\n\t\tte, ok := extMap[e]\n\t\tif !ok {\n\t\t\treturn nil, ErrExtensionNotExist(e)\n\t\t}\n\t\texts = append(exts, te)\n\t}\n\t// build SSLVersion\n\tvid64, err := strconv.ParseUint(version, 10, 16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvid := uint16(vid64)\n\n\t// build CipherSuites\n\tvar suites []uint16\n\tfor _, c := range ciphers {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsuites = append(suites, uint16(cid))\n\t}\n\n\treturn &tls.ClientHelloSpec{\n\t\tTLSVersMin: vid,\n\t\tTLSVersMax: vid,\n\t\tCipherSuites: suites,\n\t\tCompressionMethods: []byte{0},\n\t\tExtensions: exts,\n\t\tGetSessionID: sha256.Sum256,\n\t}, nil\n}", "func (z *polyGF2) String() string {\n\tif z.coeff.Sign() == 0 {\n\t\treturn \"0\"\n\t}\n\tvar s bytes.Buffer\n\tfor i := z.Degree(); i >= 0; i-- {\n\t\tif z.coeff.Bit(i) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif s.Len() > 0 {\n\t\t\ts.WriteByte('+')\n\t\t}\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\ts.WriteByte('1')\n\t\tcase i == 1:\n\t\t\ts.WriteByte('x')\n\t\tdefault:\n\t\t\tfmt.Fprintf(&s, \"x^%d\", i)\n\t\t}\n\t}\n\treturn s.String()\n}", "func stringToSpec(ja3 string) (*tls.ClientHelloSpec, error) {\n\ttokens := strings.Split(ja3, \",\")\n\n\tversion := tokens[0]\n\tciphers := strings.Split(tokens[1], \"-\")\n\textensions := strings.Split(tokens[2], \"-\")\n\tcurves := strings.Split(tokens[3], \"-\")\n\tif len(curves) == 1 && curves[0] == \"\" {\n\t\tcurves = []string{}\n\t}\n\tpointFormats := strings.Split(tokens[4], \"-\")\n\tif len(pointFormats) == 1 && pointFormats[0] == \"\" {\n\t\tpointFormats = []string{}\n\t}\n\n\t// parse curves\n\tvar targetCurves []tls.CurveID\n\tfor _, c := range curves {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetCurves = append(targetCurves, tls.CurveID(cid))\n\t}\n\textMap[\"10\"] = &tls.SupportedCurvesExtension{Curves: targetCurves}\n\n\t// parse point formats\n\tvar targetPointFormats []byte\n\tfor _, p := range pointFormats {\n\t\tpid, err := strconv.ParseUint(p, 10, 8)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetPointFormats = append(targetPointFormats, byte(pid))\n\t}\n\textMap[\"11\"] = &tls.SupportedPointsExtension{SupportedPoints: targetPointFormats}\n\n\t// build extenions list\n\tvar exts []tls.TLSExtension\n\tfor _, e := range extensions {\n\t\tte, ok := extMap[e]\n\t\tif !ok {\n\t\t\treturn nil, ErrExtensionNotExist(e)\n\t\t}\n\t\texts = append(exts, te)\n\t}\n\t// build SSLVersion\n\tvid64, err := strconv.ParseUint(version, 10, 16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvid := uint16(vid64)\n\n\t// build CipherSuites\n\tvar suites []uint16\n\tfor _, c := range ciphers {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsuites = append(suites, uint16(cid))\n\t}\n\n\treturn &tls.ClientHelloSpec{\n\t\tTLSVersMin: vid,\n\t\tTLSVersMax: vid,\n\t\tCipherSuites: suites,\n\t\tCompressionMethods: []byte{0},\n\t\tExtensions: exts,\n\t\tGetSessionID: sha256.Sum256,\n\t}, nil\n}", "func obToMSG(ob Value) unsafe.Pointer {\n\tp := heap.Alloc(nMsg)\n\t*(*stMsg)(p) = stMsg{\n\t\thwnd: getUintptr(ob, \"hwnd\"),\n\t\tmessage: uint32(getInt(ob, \"message\")),\n\t\twParam: getUintptr(ob, \"wParam\"),\n\t\tlParam: getUintptr(ob, \"lParam\"),\n\t\ttime: uint32(getInt(ob, \"time\")),\n\t\tpt: getPoint(ob, \"pt\"),\n\t}\n\treturn p\n}", "func MarshalJSON(msg proto.Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\terr := JSONMarshaler.Marshal(&b, msg)\n\treturn b.Bytes(), errors.Trace(err)\n}", "func (v *CodeMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi112(l, v)\n}", "func NewMsgExercise(auth types.AccAddress, id AccountID, amount Coin) MsgExerciseCoin {\n\treturn MsgExerciseCoin{\n\t\t*msg.MustNewKuMsg(\n\t\t\tRouterKeyName,\n\t\t\tmsg.WithAuth(auth),\n\t\t\tmsg.WithData(Cdc(), &MsgExerciseCoinData{\n\t\t\t\tID: id,\n\t\t\t\tAmount: amount,\n\t\t\t}),\n\t\t),\n\t}\n}", "func NewMsg(v NodeID, i SlotID, q QSet, t Topic) *Msg {\n\tc := atomic.AddInt32(&msgCounter, 1)\n\treturn &Msg{\n\t\tC: c,\n\t\tV: v,\n\t\tI: i,\n\t\tQ: q,\n\t\tT: t,\n\t}\n}", "func newPolyGF2(coeffs uint64) *polyGF2 {\n\tvar p polyGF2\n\tp.coeff.SetUint64(coeffs)\n\treturn &p\n}", "func protocolToMessage(c net.Conn, s string) {\n\tfmt.Print(\"Recieved: \" + s) // Used to verify what was being received\n\tmessage := strings.Split(s, \"\\t\") // Split the received message into an array of strings by \\t\n\tusername := \"\" // Empty string that will contain the specified username\n\tregisterCount := 0 // Counter for the amount of times TCCHAT_REGISTER is received\n\t\n\tif len(message) > 1 { // If message has only one string in it, it's necessarily a disconnect call\n\t\t// Replace \"\\n\" in message by \"\" as many times as necessary (-1)\n\t\t// if -1 was 'n', it would replace \"\\n\" only 'n' times, no more\n\t\tusername = strings.Replace(message[1], \"\\n\", \"\", -1)\n\t}\n\t\n\t// Check if the connection has only sent 1 TCCHAT_REGISTER\n\tif registerCount > 1 {\n\t\tfmt.Println(\"Corrupted connection detected !\")\n\t\tc.Close()\n\t\tfmt.Println(\"Connection closed\")\n\t}\n\t// Prettier if else if loop checking the contents of message[0] which contains the prefix\n\t// of the protocol message\n\tswitch message[0] {\n\tcase \"TCCHAT_REGISTER\": // A new user has joined the server\n\t\tregisterUser(c, username)\n\t\tregisterCount += 1 // Increment counter by 1\n\t\t\n\tcase \"TCCHAT_MESSAGE\": // A message has been received from a connected client\n\t\tsendMessageAll(c, message[1])\n\n\tcase \"TCCHAT_DISCONNECT\\n\": // In case of a disconnect, the \\n will still be part of the message\n\t\tuserDisconnect(userMap[c])\n\t\t\n\tdefault: // Message received is not of the correct form, close the connection\n\t\tif err := c.Close(); err == nil {\n\t\t\tc.Close()\n\t\t}\n\t}\n}", "func readMsg(br *bufio.Reader) (byte, [][]byte, error) {\n\tvar b []byte\n\tvar data [][]byte\n\tflag, err := br.ReadByte()\n\n\tswitch flag {\n\tcase '+', '-', ':':\n\t\tb, err = readLine(br)\n\t\tdata = [][]byte{b}\n\tcase '$':\n\t\tb, err = readBulk(br)\n\t\tdata = [][]byte{b}\n\tcase '*':\n\t\tdata, err = readMultiBulk(br)\n\tdefault:\n\t\terr = PROTOCOL_ERROR\n\t}\n\n\treturn flag, data, err\n}", "func stringToMatrix(msg string) myParameters {\n\tclientid := (int(msg[0]) - '0')\n\ti := 4\n\theight := 0\n\twidth := 0\n\tturn := 0\n\tthread := 0\n\n\tfor i < len(msg) && msg[i] != ' ' {\n\t\theight = height*10 + (int(msg[i]) - '0')\n\t\ti++\n\t}\n\ti++\n\tfor i < len(msg) && msg[i] != ' ' {\n\t\twidth = width*10 + (int(msg[i]) - '0')\n\t\ti++\n\t}\n\ti++\n\tfor i < len(msg) && msg[i] != ' ' {\n\t\tturn = turn*10 + (int(msg[i]) - '0')\n\t\ti++\n\t}\n\ti++\n\tfor i < len(msg) && msg[i] != ' ' {\n\t\tthread = thread*10 + (int(msg[i]) - '0')\n\t\ti++\n\t}\n\ti++\n\tnr := i\n\tworld := make([][]byte, height)\n\tfor i := range world {\n\t\tworld[i] = make([]byte, width)\n\t}\n\tfor i := 0; i < height; i++ {\n\t\tfor j := 0; j < width; j++ {\n\t\t\tworld[i][j] = msg[nr] - '0'\n\t\t\tnr++\n\n\t\t}\n\t\tnr++\n\t}\n\treturn myParameters{\n\t\tclientid,\n\t\tworld,\n\t\theight,\n\t\twidth,\n\t\tturn,\n\t\tthread,\n\t}\n\n}", "func messageFromMap(input *dynamic.Message, data *map[string]interface{}) error {\n\tstrData, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = jsonpb.UnmarshalString(string(strData), input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) RunProtocol(ctx context.Context, proto *p2p.Protocol) error {\n\ttopicobj := pss.BytesToTopic([]byte(fmt.Sprintf(\"%s:%d\", proto.Name, proto.Version)))\n\ttopichex := topicobj.String()\n\tmsgC := make(chan pss.APIMsg)\n\tc.peerPool[topicobj] = make(map[string]*pssRPCRW)\n\tsub, err := c.rpc.Subscribe(ctx, \"pss\", msgC, \"receive\", topichex, false, false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pss event subscription failed: %v\", err)\n\t}\n\tc.subs = append(c.subs, sub)\n\terr = c.rpc.Call(nil, \"pss_addHandshake\", topichex)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pss handshake activation failed: %v\", err)\n\t}\n\n\t// dispatch incoming messages\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-msgC:\n\t\t\t\t// we only allow sym msgs here\n\t\t\t\tif msg.Asymmetric {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// we get passed the symkeyid\n\t\t\t\t// need the symkey itself to resolve to peer's pubkey\n\t\t\t\tvar pubkeyid string\n\t\t\t\terr = c.rpc.Call(&pubkeyid, \"pss_getHandshakePublicKey\", msg.Key)\n\t\t\t\tif err != nil || pubkeyid == \"\" {\n\t\t\t\t\tlog.Trace(\"proto err or no pubkey\", \"err\", err, \"symkeyid\", msg.Key)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// if we don't have the peer on this protocol already, create it\n\t\t\t\t// this is more or less the same as AddPssPeer, less the handshake initiation\n\t\t\t\tif c.peerPool[topicobj][pubkeyid] == nil {\n\t\t\t\t\tvar addrhex string\n\t\t\t\t\terr := c.rpc.Call(&addrhex, \"pss_getAddress\", topichex, false, msg.Key)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Trace(err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\taddrbytes, err := hexutil.Decode(addrhex)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Trace(err.Error())\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\taddr := pss.PssAddress(addrbytes)\n\t\t\t\t\trw, err := c.newpssRPCRW(pubkeyid, addr, topicobj)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tc.peerPool[topicobj][pubkeyid] = rw\n\t\t\t\t\tp := p2p.NewPeer(enode.ID{}, fmt.Sprintf(\"%v\", addr), []p2p.Cap{})\n\t\t\t\t\tgo proto.Run(p, c.peerPool[topicobj][pubkeyid])\n\t\t\t\t}\n\t\t\t\tgo func() {\n\t\t\t\t\tc.peerPool[topicobj][pubkeyid].msgC <- msg.Msg\n\t\t\t\t}()\n\t\t\tcase <-c.quitC:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tc.protos[topicobj] = proto\n\treturn nil\n}", "func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\tif (data[0] &^ 1) != 2 {\n\t\treturn // unrecognized point encoding\n\t}\n\tif len(data) != 1+byteLen {\n\t\treturn\n\t}\n\n\t// Based on Routine 2.2.4 in NIST Mathematical routines paper\n\tparams := curve.Params()\n\ttx := new(big.Int).SetBytes(data[1 : 1+byteLen])\n\ty2 := y2(params, tx)\n\tsqrt := defaultSqrt\n\tty := sqrt(y2, params.P)\n\tif ty == nil {\n\t\treturn // \"y^2\" is not a square: invalid point\n\t}\n\tvar y2c big.Int\n\ty2c.Mul(ty, ty).Mod(&y2c, params.P)\n\tif y2c.Cmp(y2) != 0 {\n\t\treturn // sqrt(y2)^2 != y2: invalid point\n\t}\n\tif ty.Bit(0) != uint(data[0]&1) {\n\t\tty.Sub(params.P, ty)\n\t}\n\n\tx, y = tx, ty // valid point: return it\n\treturn\n}", "func EncodeMsg(msg Message) []byte {\n\tm := marshalutil.New()\n\tm.WriteByte(byte(msg.Type()))\n\tmsg.Write(m)\n\treturn m.Bytes()\n}", "func TestMessage(t *testing.T) {\n\t// Create the various types of messages to test.\n\n\t// MsgVersion.\n\taddrYou := &net.TCPAddr{IP: net.ParseIP(\"192.168.0.1\"), Port: 8333}\n\tyou, err := wire.NewNetAddress(addrYou, 1, wire.SFNodeNetwork)\n\tif err != nil {\n\t\tt.Errorf(\"NewNetAddress: %v\", err)\n\t}\n\tyou.Timestamp = time.Time{} // Version message has zero value timestamp.\n\taddrMe := &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 8333}\n\tme, err := wire.NewNetAddress(addrMe, 1, wire.SFNodeNetwork)\n\tif err != nil {\n\t\tt.Errorf(\"NewNetAddress: %v\", err)\n\t}\n\t// A version message that is decoded comes out a little different than\n\t// the original data structure, so we need to create a slightly different\n\t// message to test against.\n\tme.Timestamp = time.Time{} // Version message has zero value timestamp.\n\tyouExpected, err := wire.NewNetAddress(addrYou, 0, wire.SFNodeNetwork)\n\tif err != nil {\n\t\tt.Errorf(\"NewNetAddress: %v\", err)\n\t}\n\tyouExpected.Timestamp = time.Time{} // Version message has zero value timestamp.\n\tmeExpected, err := wire.NewNetAddress(addrMe, 0, wire.SFNodeNetwork)\n\tif err != nil {\n\t\tt.Errorf(\"NewNetAddress: %v\", err)\n\t}\n\tmeExpected.Timestamp = time.Time{} // Version message has zero value timestamp.\n\tmsgVersion := wire.NewMsgVersion(me, you, 123123, []uint32{1})\n\tmsgVersionExpected := wire.NewMsgVersion(meExpected, youExpected, 123123, []uint32{1})\n\n\tmsgVerack := wire.NewMsgVerAck()\n\tmsgPong := wire.NewMsgPong()\n\tmsgAddr := wire.NewMsgAddr()\n\tmsgInv := wire.NewMsgInv()\n\tmsgGetData := wire.NewMsgGetData()\n\n\t// ripe-based getpubkey message\n\tripeBytes := make([]byte, 20)\n\tripeBytes[0] = 1\n\tripe, err := wire.NewRipeHash(ripeBytes)\n\tif err != nil {\n\t\tt.Fatalf(\"could not make a ripe hash %s\", err)\n\t}\n\texpires := time.Unix(0x495fab29, 0) // 2009-01-03 12:15:05 -0600 CST)\n\tmsgGetPubKey := wire.NewMsgGetPubKey(123123, expires, 2, 1, ripe, nil)\n\n\tpub1Bytes, pub2Bytes := make([]byte, 64), make([]byte, 64)\n\tpub2Bytes[0] = 1\n\tpub1, err := wire.NewPubKey(pub1Bytes)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create a pubkey %s\", err)\n\t}\n\tpub2, err := wire.NewPubKey(pub2Bytes)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create a pubkey %s\", err)\n\t}\n\tmsgPubKey := wire.NewMsgPubKey(123123, expires, 2, 1, 0, pub1, pub2, 0, 0, nil, nil, nil)\n\n\tenc := make([]byte, 99)\n\tmsgMsg := wire.NewMsgMsg(123123, expires, 2, 1, enc, 0, 0, 0, nil, nil, 0, 0, nil, 0, nil, nil, nil)\n\n\tmsgBroadcast := wire.NewMsgBroadcast(123123, expires, 2, 1, nil, enc, 0, 0, 0, nil, nil, 0, 0, 0, nil, nil)\n\n\ttests := []struct {\n\t\tin wire.Message // Value to encode\n\t\tout wire.Message // Expected decoded value\n\t\tbmnet wire.BitmessageNet // Network to use for wire.encoding\n\t\tbytes int // Expected num bytes read/written\n\t}{\n\t\t{msgVersion, msgVersionExpected, wire.MainNet, 119},\n\t\t{msgVerack, msgVerack, wire.MainNet, 24},\n\t\t{msgPong, msgPong, wire.MainNet, 24},\n\t\t{msgAddr, msgAddr, wire.MainNet, 25},\n\t\t{msgInv, msgInv, wire.MainNet, 25},\n\t\t{msgGetData, msgGetData, wire.MainNet, 25},\n\t\t{msgGetPubKey, msgGetPubKey, wire.MainNet, 66},\n\t\t{msgPubKey, msgPubKey, wire.MainNet, 178},\n\t\t{msgMsg, msgMsg, wire.MainNet, 145},\n\t\t{msgBroadcast, msgBroadcast, wire.MainNet, 145},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\t// Encode to wire.format.\n\t\tvar buf bytes.Buffer\n\t\tnw, err := wire.WriteMessageN(&buf, test.in, test.bmnet)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"WriteMessage #%d error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the number of bytes written match the expected value.\n\t\tif nw != test.bytes {\n\t\t\tt.Errorf(\"WriteMessage #%d unexpected num bytes \"+\n\t\t\t\t\"written - got %d, want %d\", i, nw, test.bytes)\n\t\t}\n\n\t\t// Decode from wire.format.\n\t\trbuf := bytes.NewReader(buf.Bytes())\n\t\tnr, msg, _, err := wire.ReadMessageN(rbuf, test.bmnet)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ReadMessage #%d error %v, msg %v\", i, err,\n\t\t\t\tspew.Sdump(msg))\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(msg, test.out) {\n\t\t\tt.Errorf(\"ReadMessage #%d\\n got: %v want: %v\", i,\n\t\t\t\tspew.Sdump(msg), spew.Sdump(test.out))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the number of bytes read match the expected value.\n\t\tif nr != test.bytes {\n\t\t\tt.Errorf(\"ReadMessage #%d unexpected num bytes read - \"+\n\t\t\t\t\"got %d, want %d\", i, nr, test.bytes)\n\t\t}\n\t}\n\n\t// Do the same thing for Read/WriteMessage, but ignore the bytes since\n\t// they don't return them.\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\t// Encode to wire.format.\n\t\tvar buf bytes.Buffer\n\t\terr := wire.WriteMessage(&buf, test.in, test.bmnet)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"WriteMessage #%d error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Decode from wire.format.\n\t\trbuf := bytes.NewReader(buf.Bytes())\n\t\tmsg, _, err := wire.ReadMessage(rbuf, test.bmnet)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ReadMessage #%d error %v, msg %v\", i, err,\n\t\t\t\tspew.Sdump(msg))\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(msg, test.out) {\n\t\t\tt.Errorf(\"ReadMessage #%d\\n got: %v want: %v\", i,\n\t\t\t\tspew.Sdump(msg), spew.Sdump(test.out))\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func NewMaterialPolynomial(c ...float64) Material {\n\treturn MaterialPolynomial{factors: c}\n}", "func (c *peerConn) readHelloRequestMsg() (*helloRequestMsg, error) {\n\tmsg, err := c.readMessage()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif msg.Type() != typeHelloRequest {\n\t\treturn nil, err\n\t}\n\tnMsg := new(helloRequestMsg)\n\traw, _ := ioutil.ReadAll(msg.RawReader())\n\tif !nMsg.unmarshal(raw) {\n\t\treturn nil, errors.New(\"parse hello request err\")\n\t}\n\treturn nMsg, nil\n}" ]
[ "0.7199156", "0.53708965", "0.5206927", "0.5028563", "0.502022", "0.5014482", "0.49818343", "0.49690765", "0.49207023", "0.49053973", "0.4890348", "0.4889232", "0.4790647", "0.47545308", "0.47308874", "0.4728229", "0.47087368", "0.47006485", "0.464911", "0.464827", "0.46434894", "0.46351275", "0.4569297", "0.45588598", "0.45468584", "0.4534502", "0.45252287", "0.45099983", "0.44945514", "0.44841665", "0.44825038", "0.4472037", "0.4462184", "0.44582254", "0.4455123", "0.44511616", "0.44485486", "0.44295594", "0.44254825", "0.4401649", "0.43976507", "0.43780062", "0.43770665", "0.43764105", "0.43764105", "0.43756837", "0.43654737", "0.43568763", "0.4349028", "0.43487966", "0.43455744", "0.43343452", "0.43265948", "0.43218684", "0.4318893", "0.43174687", "0.43082842", "0.43064794", "0.42893538", "0.42819208", "0.4275277", "0.4261648", "0.42611584", "0.4254769", "0.4252039", "0.42464134", "0.42391178", "0.42308563", "0.42296436", "0.42284435", "0.42206958", "0.42005804", "0.42001843", "0.42001083", "0.41967958", "0.4195748", "0.41850194", "0.41706625", "0.41594768", "0.41583332", "0.41574383", "0.41572315", "0.41559353", "0.4153122", "0.41480377", "0.4126662", "0.4122909", "0.41201746", "0.41182208", "0.4114679", "0.41139078", "0.410677", "0.41013515", "0.40981856", "0.4083269", "0.40810293", "0.40779945", "0.4077015", "0.4075482", "0.4075001" ]
0.8222638
0
polyToMsg converts a polynomial to a byte array
func polyToMsg(p Poly) []byte { msg := make([]byte, 32) var t uint16 var tmp byte p.reduce() for i := 0; i < n/8; i++ { tmp = 0 for j := 0; j < 8; j++ { t = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1 tmp |= byte(t << j) } msg[i] = tmp } return msg }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func (p *Proof) ProofBytes() []byte {\n\tbuff := new(bytes.Buffer)\n\n\t// The solution we serialise depends on the size of the cuckoo graph. The\n\t// cycle is always of length 42, but each vertex takes up more bits on\n\t// larger graphs, nonceLengthBits is this number of bits.\n\tnonceLengthBits := uint(p.EdgeBits)\n\n\t// Make a slice just large enough to fit all of the POW bits.\n\tbitvecLengthBits := nonceLengthBits * uint(ProofSize)\n\tbitvec := make([]uint8, (bitvecLengthBits+7)/8)\n\n\tfor n, nonce := range p.Nonces {\n\t\t// Pack this nonce into the bit stream.\n\t\tfor bit := uint(0); bit < nonceLengthBits; bit++ {\n\t\t\t// If this bit is set, then write it to the correct position in the\n\t\t\t// stream.\n\t\t\tif nonce&(1<<bit) != 0 {\n\t\t\t\toffsetBits := uint(n)*nonceLengthBits + bit\n\t\t\t\tbitvec[offsetBits/8] |= 1 << (offsetBits % 8)\n\t\t\t}\n\t\t}\n\t}\n\n\tif _, err := buff.Write(bitvec); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\treturn buff.Bytes()\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func (n *Uint256) toBin() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits.\n\tmaxOutDigits := n.BitLen()\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 2 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that no partial digit handling is needed in this case because the shift\n\t// amount evenly divides the bits per internal word.\n\tconst shift = 1\n\tconst mask = 1<<shift - 1\n\tconst digitsPerInternalWord = bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\tfor i := 0; i < digitsPerInternalWord; i++ {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\t\tinputWord = n.n[inputIdx]\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func getHandshakeMessage(info_hash string, peer_id string) []byte {\n\tprotocol_name := \"BitTorrent protocol\"\n\thandshake_msg := make([]byte, 68)\n\t//start with protocol name length\n\thandshake_msg[0] = byte(len(protocol_name))\n\tcopy(handshake_msg[1:], []byte(protocol_name))\n\t//8 bytes are reserved\n\tcopy(handshake_msg[20:27], []byte{0, 0, 0, 0, 0, 0, 0, 0})\n\tcopy(handshake_msg[28:48], []byte(info_hash))\n\tcopy(handshake_msg[48:68], []byte(peer_id))\n\treturn handshake_msg\n}", "func (s Message) ToBytes() ([]byte, error) {\n\tj, e := json.Marshal(s)\n\treturn j, e\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func (m *Message) ToBytes() []byte {\n\tdata := make([]byte, 0, 0)\n\n\tdata = append(data, m.Header.ToBytes()...)\n\tdata = append(data, m.Question.ToBytes()...)\n\n\tfor _, answer := range m.Answers {\n\t\tdata = append(data, answer.ToBytes()...)\n\t}\n\n\tfor _, authority := range m.Authority {\n\t\tdata = append(data, authority.ToBytes()...)\n\t}\n\n\tfor _, additional := range m.Additional {\n\t\tdata = append(data, additional.ToBytes()...)\n\t}\n\n\treturn data\n}", "func ToJSONByteSlice(message MessageInterface) []byte {\n\tmarshalled, err := json.Marshal(message)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn marshalled\n}", "func (self *EV3Message) getBytes() []byte {\n\tself.commandSize = uint16(len(self.byteCodes)) + EV3MessageHeaderSize - 2 // 2 means commandSize = uint16 that should not be counted\n\tbuf := make([]byte, EV3MessageHeaderSize)\n\tbinary.LittleEndian.PutUint16(buf[0:], self.commandSize)\n\tbinary.LittleEndian.PutUint16(buf[2:], self.messageCount)\n\tbuf[4] = self.commandType\n\tbinary.LittleEndian.PutUint16(buf[5:], self.variablesReservation)\n\tbuf = append(buf, self.byteCodes...)\n\treturn buf\n}", "func outputProtoJSON(msg interface{}) {\n\tm := &jsonpb.Marshaler{EmitDefaults: true}\n\tif pMsg, ok := msg.(proto.Message); ok {\n\t\tstr, err := m.MarshalToString(pMsg)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(str)\n\t} else {\n\t\tfmt.Println(msg)\n\t\tpanic(\"Error: bad data received\")\n\t}\n}", "func (pub *PublicKey) ToBytes() (b []byte) {\n\t/* See Certicom SEC1 2.3.3, pg. 10 */\n\n\tx := pub.X.Bytes()\n\n\t/* Pad X to 32-bytes */\n\tpadded_x := append(bytes.Repeat([]byte{0x3f}, 32-len(x)), x...)\n\n\t/* Add prefix 0x02 or 0x03 depending on ylsb */\n\tif pub.Y.Bit(0) == 0 {\n\t\treturn append([]byte{0x02}, padded_x...)\n\t}\n\n\treturn append([]byte{0x03}, padded_x...)\n}", "func (v Msg) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjsonD2b7633eEncodeBackendInternalModels6(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func marshal(msgType uint8, msg interface{}) []byte {\n\tvar out []byte\n\tout = append(out, msgType)\n\n\tv := reflect.ValueOf(msg)\n\tstructType := v.Type()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\t\tt := field.Type()\n\t\tswitch t.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tvar v uint8\n\t\t\tif field.Bool() {\n\t\t\t\tv = 1\n\t\t\t}\n\t\t\tout = append(out, v)\n\t\tcase reflect.Array:\n\t\t\tif t.Elem().Kind() != reflect.Uint8 {\n\t\t\t\tpanic(\"array of non-uint8\")\n\t\t\t}\n\t\t\tfor j := 0; j < t.Len(); j++ {\n\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tu32 := uint32(field.Uint())\n\t\t\tout = append(out, byte(u32>>24))\n\t\t\tout = append(out, byte(u32>>16))\n\t\t\tout = append(out, byte(u32>>8))\n\t\t\tout = append(out, byte(u32))\n\t\tcase reflect.String:\n\t\t\ts := field.String()\n\t\t\tout = append(out, byte(len(s)>>24))\n\t\t\tout = append(out, byte(len(s)>>16))\n\t\t\tout = append(out, byte(len(s)>>8))\n\t\t\tout = append(out, byte(len(s)))\n\t\t\tout = append(out, s...)\n\t\tcase reflect.Slice:\n\t\t\tswitch t.Elem().Kind() {\n\t\t\tcase reflect.Uint8:\n\t\t\t\tlength := field.Len()\n\t\t\t\tif structType.Field(i).Tag.Get(\"ssh\") != \"rest\" {\n\t\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\t\tout = append(out, byte(length))\n\t\t\t\t}\n\t\t\t\tfor j := 0; j < length; j++ {\n\t\t\t\t\tout = append(out, byte(field.Index(j).Uint()))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tvar length int\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tlength++ /* comma */\n\t\t\t\t\t}\n\t\t\t\t\tlength += len(field.Index(j).String())\n\t\t\t\t}\n\n\t\t\t\tout = append(out, byte(length>>24))\n\t\t\t\tout = append(out, byte(length>>16))\n\t\t\t\tout = append(out, byte(length>>8))\n\t\t\t\tout = append(out, byte(length))\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\tif j != 0 {\n\t\t\t\t\t\tout = append(out, ',')\n\t\t\t\t\t}\n\t\t\t\t\tout = append(out, field.Index(j).String()...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(\"slice of unknown type\")\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif t == bigIntType {\n\t\t\t\tvar n *big.Int\n\t\t\t\tnValue := reflect.ValueOf(&n)\n\t\t\t\tnValue.Elem().Set(field)\n\t\t\t\tneeded := intLength(n)\n\t\t\t\toldLength := len(out)\n\n\t\t\t\tif cap(out)-len(out) < needed {\n\t\t\t\t\tnewOut := make([]byte, len(out), 2*(len(out)+needed))\n\t\t\t\t\tcopy(newOut, out)\n\t\t\t\t\tout = newOut\n\t\t\t\t}\n\t\t\t\tout = out[:oldLength+needed]\n\t\t\t\tmarshalInt(out[oldLength:], n)\n\t\t\t} else {\n\t\t\t\tpanic(\"pointer to unknown type\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}", "func (msg MsgProof) GetSignBytes() []byte {\n\treturn sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}", "func (ks *KZG1Settings) CommitToPoly(coeffs []gmcl.Fr) *gmcl.G1 {\n\tvar out gmcl.G1\n\tgmcl.G1MulVec(&out, ks.PK[:len(coeffs)], coeffs)\n\treturn &out\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func (sg *SubGraph) ToProtocolBuffer(l *Latency) (*graph.Node, error) {\n\tvar seedNode *protoOutputNode\n\tif sg.SrcUIDs == nil {\n\t\treturn seedNode.New(sg.Attr).(*protoOutputNode).Node, nil\n\t}\n\n\tx.AssertTrue(len(sg.uidMatrix) == 1)\n\tn := seedNode.New(sg.Attr)\n\tul := sg.uidMatrix[0]\n\tif sg.Params.GetUID || sg.Params.isDebug {\n\t\tn.SetUID(ul.Uids[0])\n\t}\n\n\tif rerr := sg.preTraverse(ul.Uids[0], n); rerr != nil {\n\t\treturn n.(*protoOutputNode).Node, rerr\n\t}\n\n\tl.ProtocolBuffer = time.Since(l.Start) - l.Parsing - l.Processing\n\treturn n.(*protoOutputNode).Node, nil\n}", "func (op *OptDHCPv4Msg) ToBytes() []byte {\n\treturn op.Msg.ToBytes()\n}", "func encodeMsgPack(msg interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)\n\treturn buf.Bytes(), err\n}", "func encodeMsgPack(msg interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\terr := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)\n\treturn buf.Bytes(), err\n}", "func EncodeMsg(pb proto.Message) ([]byte, error) {\n\tif um, ok := pb.(p2p.Wrapper); ok {\n\t\tpb = um.Wrap()\n\t}\n\tbz, err := proto.Marshal(pb)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to marshal %T: %w\", pb, err)\n\t}\n\n\treturn bz, nil\n}", "func MessageToBytes(m *SimpleMessage) (b []byte, err error) {\n\tcontent, e := json.Marshal(m)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn content, nil\n}", "func (msg MsgCreateTable) GetSignBytes() []byte {\n return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}", "func ToBytes(message interface{}) ([]byte, error) {\n\n\tswitch r := message.(type) {\n\tcase io.Reader:\n\t\treturn ioutil.ReadAll(r)\n\tcase []byte:\n\t\treturn r, nil\n\tcase [][]byte:\n\t\tbuffer := bytes.NewBuffer(nil)\n\t\tfor _, b := range r {\n\t\t\tbuffer.Write(b)\n\t\t}\n\t\treturn buffer.Bytes(), nil\n\tcase string:\n\t\treturn []byte(r), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unrecognized type: %T\", message)\n\t}\n}", "func (mp *MerkleProof) ToBytes() ([]byte, error) {\r\n\tindex := bt.VarInt(mp.Index)\r\n\r\n\ttxOrID, err := hex.DecodeString(mp.TxOrID)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\ttxOrID = bt.ReverseBytes(txOrID)\r\n\r\n\ttarget, err := hex.DecodeString(mp.Target)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\ttarget = bt.ReverseBytes(target)\r\n\r\n\tnodeCount := len(mp.Nodes)\r\n\r\n\tnodes := []byte{}\r\n\r\n\tfor _, n := range mp.Nodes {\r\n\t\tif n == \"*\" {\r\n\t\t\tnodes = append(nodes, []byte{1}...)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tnodes = append(nodes, []byte{0}...)\r\n\t\tnb, err := hex.DecodeString(n)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tnodes = append(nodes, bt.ReverseBytes(nb)...)\r\n\r\n\t}\r\n\r\n\tvar flags uint8\r\n\r\n\tvar txLength []byte\r\n\tif len(mp.TxOrID) > 64 { // tx bytes instead of txid\r\n\t\t// set bit at index 0\r\n\t\tflags |= (1 << 0)\r\n\r\n\t\ttxLength = bt.VarInt(uint64(len(txOrID)))\r\n\t}\r\n\r\n\tif mp.TargetType == \"header\" {\r\n\t\t// set bit at index 1\r\n\t\tflags |= (1 << 1)\r\n\t} else if mp.TargetType == \"merkleRoot\" {\r\n\t\t// set bit at index 2\r\n\t\tflags |= (1 << 2)\r\n\t}\r\n\r\n\t// ignore proofType and compositeType for this version\r\n\r\n\tbytes := []byte{}\r\n\tbytes = append(bytes, flags)\r\n\tbytes = append(bytes, index...)\r\n\tbytes = append(bytes, txLength...)\r\n\tbytes = append(bytes, txOrID...)\r\n\tbytes = append(bytes, target...)\r\n\tbytes = append(bytes, byte(nodeCount))\r\n\tbytes = append(bytes, nodes...)\r\n\r\n\treturn bytes, nil\r\n}", "func (msg MsgRagnarok) GetSignBytes() []byte {\n\treturn cosmos.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}", "func (d *Dense) ToProto() *bb84pb.DenseBitArray {\n\treturn &bb84pb.DenseBitArray{\n\t\tBits: d.Data(),\n\t\tLen: int32(d.len),\n\t}\n}", "func (msg MsgCreateIndex) GetSignBytes() []byte {\n return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}", "func ToCompatibleMessage(message MessageInterface) []byte {\n\tcompatibleMessage := CompatibleBaseMessage{\n\t\tPayload: message,\n\t\tMessageType: \"\",\n\t\tTimestamp: time.Now().Format(TimeFormat),\n\t}\n\treturn ToJSONByteSlice(compatibleMessage)\n\n}", "func MustToBytes(message interface{}) []byte {\n\tr, err := ToBytes(message)\n\tif nil != err {\n\t\tAssert(err)\n\t}\n\treturn r\n}", "func msgToKey(m *dns.Msg) (b []byte) {\n\tq := m.Question[0]\n\tname := q.Name\n\tb = make([]byte, packedMsgLenSz+packedMsgLenSz+len(name))\n\n\t// Put QTYPE, QCLASS, and QNAME.\n\tbinary.BigEndian.PutUint16(b, q.Qtype)\n\tbinary.BigEndian.PutUint16(b[packedMsgLenSz:], q.Qclass)\n\tcopy(b[2*packedMsgLenSz:], strings.ToLower(name))\n\n\treturn b\n}", "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func ExampleMarshal_toarray() {\n\ttype Record struct {\n\t\t_ struct{} `cbor:\",toarray\"`\n\t\tName string\n\t\tUnit string\n\t\tMeasurement int\n\t}\n\trec := Record{Name: \"current\", Unit: \"V\", Measurement: 1}\n\tb, err := cbor.Marshal(rec)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tfmt.Printf(\"%x\\n\", b)\n\t// Output:\n\t// 836763757272656e74615601\n}", "func (p *Proof) Bytes() []byte {\n\tbuff := new(bytes.Buffer)\n\n\t// Write size of cuckoo graph.\n\tif err := binary.Write(buff, binary.BigEndian, p.EdgeBits); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\tbuff.Write(p.ProofBytes())\n\n\treturn buff.Bytes()\n}", "func (message *Message) generateByte() []byte {\n\n\treturn message.encode()\n\n}", "func _proto_marshal(obj proto.Message) []byte {\n\tbuf, err := proto.Marshal(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func (mp JSONMsgPacker) PackMsg(msg interface{}, buf []byte) ([]byte, error) {\n\tbuffer := bytes.NewBuffer(buf)\n\tjsonEncoder := json.NewEncoder(buffer)\n\terr := jsonEncoder.Encode(msg)\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tbuf = buffer.Bytes()\n\treturn buf[:len(buf)-1], nil // encoder always put '\\n' at the end, we trim it\n}", "func (eth *Eth) Msg(addr string, data []string) (string, error) {\n\tpacked := PackTxDataArgs(data...)\n\tkeys := eth.fetchKeyPair()\n\t//addr = ethutil.StripHex(addr)\n\tbyte_addr := ethutil.Hex2Bytes(addr)\n\thash, err := eth.pipe.Transact(keys, byte_addr, ethutil.NewValue(ethutil.Big(\"350\")), ethutil.NewValue(ethutil.Big(\"200000000000\")), ethutil.NewValue(ethutil.Big(\"1000000\")), []byte(packed))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ethutil.Bytes2Hex(hash), nil\n}", "func Serialize(msg Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\tencoder := json.NewEncoder(&b)\n\terr := encoder.Encode(msg)\n\treturn b.Bytes(), err\n}", "func messageToAny(t *testing.T, msg proto.Message) *any.Any {\n\ts, err := ptypes.MarshalAny(msg)\n\tif err != nil {\n\t\tt.Fatalf(\"transfer failed: %v\", err)\n\t\treturn nil\n\t}\n\treturn s\n}", "func (message *Message) str() []byte {\n\n\tmessage.MsgType = norStrMsg\n\n\treturn message.generateByte()\n}", "func (msg MsgTest) GetSignBytes() []byte {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn sdk.MustSortJSON(b)\n}", "func (n *Uint256) toOctal() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits using the fact\n\t// that 3 bits converts directly to a single octal digit.\n\tmaxOutDigits := (n.BitLen() + 2) / 3\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 8 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that partial digit handling is needed in this case because the shift\n\t// amount does not evenly divide the bits per internal word.\n\tconst shift = 3\n\tconst mask = 1<<shift - 1\n\tunconvertedBits := bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\t// Convert full digits.\n\t\tfor ; unconvertedBits >= shift; unconvertedBits -= shift {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\n\t\t// Move to the next input word when there are not any remaining\n\t\t// unconverted bits that need to be handled.\n\t\tif unconvertedBits == 0 {\n\t\t\tinputWord = n.n[inputIdx]\n\t\t\tunconvertedBits = bitsPerInternalWord\n\t\t\tcontinue\n\t\t}\n\n\t\t// Account for the remaining unconverted bits from the current word and\n\t\t// the bits needed from the next word to form a full digit for the next\n\t\t// digit.\n\t\tinputWord |= n.n[inputIdx] << unconvertedBits\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\toutputIdx--\n\n\t\t// Move to the next input word while accounting for the bits already\n\t\t// consumed above by shifting it and updating the unconverted bits\n\t\t// accordingly.\n\t\tinputWord = n.n[inputIdx] >> (shift - unconvertedBits)\n\t\tunconvertedBits = bitsPerInternalWord - (shift - unconvertedBits)\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func ProtoString(value proto.Message) (string, error) {\n\tm := jsonpb.Marshaler{}\n\treturn m.MarshalToString(value)\n}", "func (t *SPOTuple) Serialize() []byte {\n\n\tout, err := proto.Marshal(t)\n\tif err != nil {\n\t\tlog.Println(\"tuple-serialize: protobuf encoding error: \", err)\n\t}\n\treturn out\n\n}", "func MarshalJSON(msg proto.Message) ([]byte, error) {\n\tvar b bytes.Buffer\n\terr := JSONMarshaler.Marshal(&b, msg)\n\treturn b.Bytes(), errors.Trace(err)\n}", "func writeMessage(data interface{}, w io.Writer) error {\n\n\tresBytes, err := jsoniter.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn encodeByteSlice(w, resBytes)\n}", "func ConvertSubscriptionToBytes(sub *pb.SubRequest) []byte {\n\tvar buf bytes.Buffer\n\tsubscriberID := make([]byte, 8)\n\ttopicID := make([]byte, 8)\n\n\tbinary.PutUvarint(subscriberID, sub.SubscriberID)\n\n\t// Write subscription information to buffer\n\tbuf.Write(subscriberID)\n\tfor _, topic := range sub.TopicIDs {\n\t\tbinary.PutUvarint(topicID, topic)\n\t\tbuf.Write(topicID)\n\t}\n\n\treturn buf.Bytes()\n}", "func TestProtocolMessageEncodeZeroSerials(t *testing.T) {\n\tmsg := ably.ProtocolMessage{\n\t\tID: \"test\",\n\t\tMsgSerial: 0,\n\t\tConnectionSerial: 0,\n\t}\n\tencoded, err := ablyutil.MarshalMsgpack(msg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// expect a 3-element map with both the serial fields set to zero\n\texpected := []byte(\"\\x83\\xB0connectionSerial\\x00\\xA2id\\xA4test\\xA9msgSerial\\x00\")\n\tif !bytes.Equal(encoded, expected) {\n\t\tt.Fatalf(\"unexpected msgpack encoding\\nexpected: %x\\nactual: %x\", expected, encoded)\n\t}\n}", "func publicKeyToBytes(pub interface{}) []byte {\r\n\tvar b []byte\r\n\tswitch k := pub.(type) {\r\n\tcase *rsa.PublicKey:\r\n\t\tb = k.N.Bytes()\r\n\tcase *dsa.PublicKey:\r\n\t\tb = k.Y.Bytes()\r\n\tcase *ecdsa.PublicKey:\r\n\t\tb = append(k.X.Bytes(), k.Y.Bytes()...)\r\n\t}\r\n\treturn b\r\n}", "func (m *Message) BytesOnWire() ([]byte, error) {\n\tjsonBytes, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"message error - fail to marshal message to bytes, error: %v\", err)\n\t}\n\n\tjsonLen := len(jsonBytes)\n\tif jsonLen > MaxJSONLen {\n\t\treturn nil, fmt.Errorf(\"message error - message length %v is greather than %v\", jsonLen, MaxJSONLen)\n\t}\n\n\tlenBytes := []byte(fmt.Sprintf(\"%05d\", jsonLen))\n\treturn append(lenBytes, jsonBytes...), nil\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\n\tret := make([]byte, 1+byteLen)\n\tret[0] = 2 // compressed point\n\n\txBytes := x.Bytes()\n\tcopy(ret[1+byteLen-len(xBytes):], xBytes)\n\tret[0] += byte(y.Bit(0))\n\treturn ret\n}", "func EncodeMessage(msg *Message)[] byte{\n\t//一个字节就是8个bit,两位十六进制\n\tfirst3bytes := []byte{0xab, 0xba, 0x00}\n\theaderBytes, _ := msgpack.Marshal(msg.Header)\n\n\t//totolLen = headerLen + bodyLen + header_length(4)\n\ttotalLen := 4 + len(headerBytes) + len(msg.Data)\n\ttotalLenBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(totalLenBytes, uint32(totalLen))\n\n\tdata := make([]byte, totalLen+7)\n\tstart := 0\n\tcopyFullWithOffset(data, first3bytes, &start)\n\tcopyFullWithOffset(data, totalLenBytes, &start)\n\n\theaderLenBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(headerLenBytes, uint32(len(headerBytes)))\n\tcopyFullWithOffset(data, headerLenBytes, &start)\n\tcopyFullWithOffset(data, headerBytes, &start)\n\tcopyFullWithOffset(data, msg.Data, &start)\n\n\treturn data\n}", "func (z *polyGF2) String() string {\n\tif z.coeff.Sign() == 0 {\n\t\treturn \"0\"\n\t}\n\tvar s bytes.Buffer\n\tfor i := z.Degree(); i >= 0; i-- {\n\t\tif z.coeff.Bit(i) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif s.Len() > 0 {\n\t\t\ts.WriteByte('+')\n\t\t}\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\ts.WriteByte('1')\n\t\tcase i == 1:\n\t\t\ts.WriteByte('x')\n\t\tdefault:\n\t\t\tfmt.Fprintf(&s, \"x^%d\", i)\n\t\t}\n\t}\n\treturn s.String()\n}", "func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}", "func ConvertMessageToBuffer(message *Message) *bytes.Buffer {\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(&message)\n\treturn b\n}", "func (m MessageType) ToBytes() []byte {\n\treturn []byte{byte(m)}\n}", "func (p PeerRegistrationReplyPacket) ToArray() []byte {\r\n\ta := make([]byte, 9)\r\n\ta[0] = byte(p.Command)\r\n\ta[1] = byte(p.ID >> 24)\r\n\ta[2] = byte(p.ID >> 16)\r\n\ta[3] = byte(p.ID >> 8)\r\n\ta[4] = byte(p.ID)\r\n\ta[5] = byte(p.LinkType)\r\n\ta[6] = 0x06\r\n\ta[7] = byte(p.LinkType)\r\n\treturn a\r\n}", "func Encode(msg MessageTemp) string{\n var r = make([]string,15)\n i := 0\n r[i] = \"35=\"+msg.order_type\n i++\n if msg.order_type==\"trade\"{\n r[i] = fmt.Sprintf(\"44=%d\", msg.price)\n i++\n r[i] = fmt.Sprintf(\"11=%d\", msg.stock_id)\n i++\n r[i] = fmt.Sprintf(\"38=%d\", msg.quantity)\n i++\n if msg.trade_type == \"buy\"{\n r[i] = \"54=1\"\n i++\n } else if msg.trade_type == \"sell\"{\n r[i] = \"54=2\"\n i++\n }\n } else if msg.order_type==\"user\"{\n r[i] = \"5001=\"+msg.username\n i++\n r[i] = \"5002=\"+msg.password\n i++\n }\n\n var result string\n for ;i>=0;i--{\n result += r[i] + \";\"\n }\n //fmt.Println(result)\n return result\n}", "func toJSONPb(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar msg *Message\n\tvar emitDefaults starlark.Bool\n\tif err := starlark.UnpackArgs(\"to_jsonpb\", args, kwargs, \"msg\", &msg, \"emit_defaults?\", &emitDefaults); err != nil {\n\t\treturn nil, err\n\t}\n\tpb, err := msg.ToProto()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// More jsonpb Marshaler options may be added here as needed.\n\tvar jsonMarshaler = &jsonpb.Marshaler{Indent: \"\\t\", EmitDefaults: bool(emitDefaults)}\n\tstr, err := jsonMarshaler.MarshalToString(pb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn starlark.String(str), nil\n}", "func newMsg(t string) ([]byte, error) {\n\tswitch t {\n\tcase \"version\":\n\t\treturn newVersion()\n\tcase \"verack\":\n\t\treturn newVerack()\n\tcase \"getheaders\":\n\t\treturn newHeadersReq()\n\tcase \"getaddr\":\n\t\treturn newGetAddr()\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func Test005ConversionToAndFromMsgpackAndJson(t *testing.T) {\n\n\tcv.Convey(`from gl we should be able to create a known Go struct,\n\ntype Event struct {\n\tId int\n\tUser Person\n\tFlight string\n\tPilot []string\n}\n\n Event{}, and fill in its fields`, t, func() {\n\t\tevent := `(eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`\n\t\tenv := NewZlisp()\n\t\tdefer env.Close()\n\n\t\tenv.StandardSetup()\n\n\t\tx, err := env.EvalString(event)\n\t\tpanicOn(err)\n\n\t\tcv.So(x.SexpString(nil), cv.ShouldEqual, ` (eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`)\n\n\t\tjsonBy := SexpToJson(x)\n\t\tcv.So(string(jsonBy), cv.ShouldEqual, `{\"Atype\":\"eventdemo\", \"id\":123, \"user\":{\"Atype\":\"persondemo\", \"first\":\"Liz\", \"last\":\"C\", \"zKeyOrder\":[\"first\", \"last\"]}, \"flight\":\"AZD234\", \"pilot\":[\"Roger\", \"Ernie\"], \"cancelled\":true, \"zKeyOrder\":[\"id\", \"user\", \"flight\", \"pilot\", \"cancelled\"]}`)\n\t\tmsgpack, goObj := SexpToMsgpack(x)\n\t\t// msgpack field ordering is random, so can't expect a match the serialization byte-for-byte\n\t\t//cv.So(msgpack, cv.ShouldResemble, expectedMsgpack)\n\t\tgoObj2, err := MsgpackToGo(msgpack)\n\t\tpanicOn(err)\n\t\t// the ordering of jsonBack is canonical, so won't match ours\n\t\t// cv.So(string(jsonBack), cv.ShouldResemble, `{\"id\":123, \"user\":{\"first\":\"Liz\", \"last\":\"C\"}, \"flight\":\"AZD234\", \"pilot\":[\"Roger\", \"Ernie\"]}`)\n\n\t\tfmt.Printf(\"goObj = '%#v'\\n\", goObj)\n\t\tfmt.Printf(\"goObj2 = '%#v'\\n\", goObj2)\n\n\t\tcv.So(goObj, cv.ShouldResemble, goObj2)\n\n\t\tiface, err := MsgpackToGo(msgpack)\n\t\tpanicOn(err)\n\t\tsexp, err := GoToSexp(iface, env)\n\t\tpanicOn(err)\n\t\t// must get into same order to have sane comparison, so borrow the KeyOrder to be sure.\n\t\thhh := sexp.(*SexpHash)\n\t\thhh.KeyOrder = x.(*SexpHash).KeyOrder\n\t\tsexpStr := sexp.SexpString(nil)\n\t\texpectedSexpr := ` (eventdemo id:123 user: (persondemo first:\"Liz\" last:\"C\") flight:\"AZD234\" pilot:[\"Roger\" \"Ernie\"] cancelled:true)`\n\t\tcv.So(sexpStr, cv.ShouldResemble, expectedSexpr)\n\n\t\tfmt.Printf(\"\\n Unmarshaling from msgpack into pre-defined go struct should succeed.\\n\")\n\n\t\tvar goEvent Event\n\t\tdec := codec.NewDecoderBytes(msgpack, &msgpHelper.mh)\n\t\terr = dec.Decode(&goEvent)\n\t\tpanicOn(err)\n\t\tfmt.Printf(\"from msgpack, goEvent = '%#v'\\n\", goEvent)\n\t\tcv.So(goEvent.Id, cv.ShouldEqual, 123)\n\t\tcv.So(goEvent.Flight, cv.ShouldEqual, \"AZD234\")\n\t\tcv.So(goEvent.Pilot[0], cv.ShouldEqual, \"Roger\")\n\t\tcv.So(goEvent.Pilot[1], cv.ShouldEqual, \"Ernie\")\n\t\tcv.So(goEvent.User.First, cv.ShouldEqual, \"Liz\")\n\t\tcv.So(goEvent.User.Last, cv.ShouldEqual, \"C\")\n\n\t\tgoEvent = Event{}\n\t\tjdec := codec.NewDecoderBytes([]byte(jsonBy), &msgpHelper.jh)\n\t\terr = jdec.Decode(&goEvent)\n\t\tpanicOn(err)\n\t\tfmt.Printf(\"from json, goEvent = '%#v'\\n\", goEvent)\n\t\tcv.So(goEvent.Id, cv.ShouldEqual, 123)\n\t\tcv.So(goEvent.Flight, cv.ShouldEqual, \"AZD234\")\n\t\tcv.So(goEvent.Pilot[0], cv.ShouldEqual, \"Roger\")\n\t\tcv.So(goEvent.Pilot[1], cv.ShouldEqual, \"Ernie\")\n\t\tcv.So(goEvent.User.First, cv.ShouldEqual, \"Liz\")\n\t\tcv.So(goEvent.User.Last, cv.ShouldEqual, \"C\")\n\t\tcv.So(goEvent.Cancelled, cv.ShouldEqual, true)\n\n\t\tfmt.Printf(\"\\n And directly from Go to S-expression via GoToSexp() should work.\\n\")\n\t\tsexp2, err := GoToSexp(goObj2, env)\n\t\tcv.So(sexp2.SexpString(nil), cv.ShouldEqual, expectedSexpr)\n\t\tfmt.Printf(\"\\n Result: directly from Go map[string]interface{} -> sexpr via GoMapToSexp() produced: '%s'\\n\", sexp2.SexpString(nil))\n\n\t\tfmt.Printf(\"\\n And the reverse direction, from S-expression to go map[string]interface{} should work.\\n\")\n\t\tgoMap3 := SexpToGo(sexp2, env, nil).(map[string]interface{})\n\n\t\t// detailed diff\n\t\tgoObj2map := goObj2.(map[string]interface{})\n\n\t\t// looks like goMap3 has an int, whereas goObj2map has an int64\n\n\t\t// compare goMap3 and goObj2\n\t\tfor k3, v3 := range goMap3 {\n\t\t\tv2 := goObj2map[k3]\n\t\t\tcv.So(v3, cv.ShouldResemble, v2)\n\t\t}\n\n\t\tfmt.Printf(\"\\n Directly Sexp -> msgpack -> pre-established Go struct Event{} should work.\\n\")\n\n\t\tswitch asHash := sexp2.(type) {\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"value must be a hash or defmap\")\n\t\t\tpanic(err)\n\t\tcase *SexpHash:\n\t\t\ttn := asHash.TypeName\n\t\t\tfactory, hasMaker := GoStructRegistry.Registry[tn]\n\t\t\tif !hasMaker {\n\t\t\t\terr = fmt.Errorf(\"type '%s' not registered in GoStructRegistry\", tn)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tnewStruct, err := factory.Factory(env, asHash)\n\t\t\tpanicOn(err)\n\n\t\t\t// What didn't work here was going through msgpack, because\n\t\t\t// ugorji msgpack encode, when writing, will turn signed ints into unsigned ints,\n\t\t\t// which is a problem for msgp decoding. Hence cut out the middle men\n\t\t\t// and decode straight from jsonBytes into our newStruct.\n\t\t\tjsonBytes := []byte(SexpToJson(asHash))\n\n\t\t\tjsonDecoder := json.NewDecoder(bytes.NewBuffer(jsonBytes))\n\t\t\terr = jsonDecoder.Decode(newStruct)\n\t\t\tswitch err {\n\t\t\tcase io.EOF:\n\t\t\tcase nil:\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Errorf(\"error during jsonDecoder.Decode() on type '%s': '%s'\", tn, err))\n\t\t\t}\n\t\t\tasHash.SetGoStructFactory(factory)\n\n\t\t\tfmt.Printf(\"from json via factory.Make(), newStruct = '%#v'\\n\", newStruct)\n\t\t\tcv.So(newStruct, cv.ShouldResemble, &goEvent)\n\t\t}\n\t})\n}", "func (p *powerCtl) toByte() (bits uint8) {\n\tbits = 0x00\n\tbits = bits | (p.link << 5)\n\tbits = bits | (p.autoSleep << 4)\n\tbits = bits | (p.measure << 3)\n\tbits = bits | (p.sleep << 2)\n\tbits = bits | p.wakeUp\n\n\treturn bits\n}", "func ToByteArr(v interface{}) (result []byte) {\n\tresult = []byte(\"\")\n\tif v == nil {\n\t\treturn result\n\t}\n\n\tswitch v := v.(type) {\n\tcase string:\n\t\tresult = []byte(v)\n\tcase int:\n\t\tresult = []byte(strconv.Itoa(v))\n\tcase int64:\n\t\tresult = []byte(strconv.FormatInt(v, 10))\n\tcase bool:\n\t\tresult = []byte(strconv.FormatBool(v))\n\tcase float64:\n\t\tresult = []byte(strconv.FormatFloat(v, 'E', -1, 64))\n\tcase []uint8:\n\t\tresult = v\n\tdefault:\n\t\tresultJSON, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tresult = resultJSON\n\t\t} else {\n\t\t\tlog.Println(\"func ToByteArr\", err)\n\t\t}\n\t}\n\n\treturn result\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func (m *BallotProofMsg) SignedBytes() []byte {\n\tdata, err := codec.Encode(&m.InnerMsg)\n\tif err != nil {\n\t\tlog.With().Fatal(\"failed to serialize MultiBlockProposalsMsg\", log.Err(err))\n\t}\n\treturn data\n}", "func ToBytes(inter interface{}) []byte {\n\treqBodyBytes := new(bytes.Buffer)\n\tjson.NewEncoder(reqBodyBytes).Encode(inter)\n\tfmt.Println(reqBodyBytes.Bytes()) // this is the []byte\n\tfmt.Println(string(reqBodyBytes.Bytes())) // converted back to show it's your original object\n\treturn reqBodyBytes.Bytes()\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func (smsg *SignedMessage) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tif err := smsg.MarshalCBOR(buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (e *wireFormatEncoder) BinaryToWireFormat(avroInput []byte) ([]byte, error) {\n\tconst op = errors.Op(\"avroutil.wireFormatEncoder.BinaryToWireFormat\")\n\n\tbuf := new(bytes.Buffer)\n\n\tif err := buf.WriteByte(0x00); err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\n\tif err := binary.Write(buf, binary.BigEndian, int32(e.writerSchemaID)); err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\n\tif _, err := buf.Write(avroInput); err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (msg *Any) JSON() []byte {\n\tjsonBytes, err := json.Marshal(*msg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jsonBytes\n}", "func kobPubToBytes(pubList []*koblitz.PublicKey) (retList [][33]byte) {\n\t// We know the length so we can do fun indexing rather than appending all the time\n\t// and actually preserve order\n\tretList = make([][33]byte, len(pubList))\n\tvar currSerialized [33]byte\n\tfor i, pubkey := range pubList {\n\t\tcopy(currSerialized[:], pubkey.SerializeCompressed())\n\t\tretList[i] = currSerialized\n\t}\n\n\treturn\n}", "func (p *Parameters) UnMarshalBinary(data []byte) error {\n\tif len(data) < 3 {\n\t\treturn errors.New(\"invalid parameters encoding\")\n\t}\n\tb := utils.NewBuffer(data)\n\tp.N = 1 << uint64(b.ReadUint8())\n\tif p.N > MaxN {\n\t\treturn errors.New(\"polynomial degree is too large\")\n\t}\n\tlenQi := uint64(b.ReadUint8())\n\tif lenQi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Qi) is larger than %d\", MaxModuliCount)\n\t}\n\tlenPi := uint64(b.ReadUint8())\n\tif lenPi > MaxModuliCount {\n\t\treturn fmt.Errorf(\"len(Pi) is larger than %d\", MaxModuliCount)\n\t}\n\tp.T = b.ReadUint64()\n\tp.Sigma = math.Round((float64(b.ReadUint64())/float64(1<<32))*100) / 100\n\tp.Qi = make([]uint64, lenQi, lenQi)\n\tp.Pi = make([]uint64, lenPi, lenPi)\n\tb.ReadUint64Slice(p.Qi)\n\tb.ReadUint64Slice(p.Pi)\n\treturn nil\n}", "func protoPlainMsgToMessage(msg *bpb.PlainChatMessage) (db.Message, error) {\n\tm := db.Message{\n\t\tID: msg.MessageID,\n\t\tMessage: msg.Message,\n\t\tCreatedAt: msg.CreatedAt,\n\t\tVersion: uint(msg.Version),\n\t\tGroupChatID: msg.GroupChatID,\n\t}\n\n\tif msg.AddUserPrivChat != nil {\n\t\tm.AddUserToChat = &db.AddUserToChat{}\n\t\tm.AddUserToChat.ChatID = msg.AddUserPrivChat.ChatID\n\t\tfor _, user := range msg.AddUserPrivChat.Users {\n\t\t\tm.AddUserToChat.Users = append(m.AddUserToChat.Users, user)\n\t\t}\n\t\tm.AddUserToChat.ChatName = msg.AddUserPrivChat.GroupName\n\t}\n\n\tif isDAppMessage(msg) {\n\t\tm.DApp = &db.DAppMessage{\n\t\t\tDAppPublicKey: msg.DAppPublicKey,\n\t\t\tType: msg.Type,\n\t\t\tParams: map[string]interface{}{},\n\t\t}\n\t\t// unmarshal params\n\t\tif msg.Params != nil {\n\t\t\tif err := json.Unmarshal(msg.Params, &m.DApp.Params); err != nil {\n\t\t\t\treturn db.Message{}, err\n\t\t\t}\n\t\t}\n\t\t// make sure that there is no message text\n\t\t// since the protocol doesn't allow it\n\t\tm.Message = nil\n\t}\n\n\treturn m, nil\n\n}", "func boxToPoly(b Box2d) polygon {\n\tcen_x, cen_y := b.Position()\n\twidth, height := b.Size()\n\tangle := b.AngleDegrees()\n\n\tpoints := [4]point{}\n\n\tpoints[0] = point{X: getX(-width/2, -height/2, angle) + cen_x,\n\t\tY: getY(-width/2, -height/2, angle) + cen_y}\n\n\tpoints[1] = point{X: getX(width/2, -height/2, angle) + cen_x,\n\t\tY: getY(width/2, -height/2, angle) + cen_y}\n\n\tpoints[2] = point{X: getX(-width/2, height/2, angle) + cen_x,\n\t\tY: getY(-width/2, height/2, angle) + cen_y}\n\n\tpoints[3] = point{X: getX(width/2, height/2, angle) + cen_x,\n\t\tY: getY(width/2, height/2, angle) + cen_y}\n\tz := boxPoly{points: points[:4]}\n\n\treturn z\n}", "func (topicInfo TopicInfo) ToBytes() []byte {\n\tdata, err := protobuf.Marshal(topicInfo._ToProtobuf())\n\tif err != nil {\n\t\treturn make([]byte, 0)\n\t}\n\n\treturn data\n}", "func (p Poly) Marshal(buf []byte, rem int) ([]byte, int, error) {\n\tbuf, rem, err := surge.MarshalLen(uint32(len(p)), buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.MarshalLen(uint32(cap(p)), buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tfor _, c := range p {\n\t\tbuf, rem, err = c.Marshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func (pk PublicKey) Bytes() []byte {\n\tbuf := elliptic.Marshal(pk.PubKey.Curve, pk.PubKey.X, pk.PubKey.Y)\n\t//fmt.Printf(\"end pub key marshal, len=%v, data=%v\\n\", len(buf), buf)\n\treturn buf\n}", "func (msg MsgInsertRow) GetSignBytes() []byte {\n return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg))\n}", "func (pm Msg) pack() []byte {\n\tout := new(bytes.Buffer)\n\n\tfmt.Fprintf(out, \"%s\\n%s\\n%s\\n%s\\n%s\\n\", pm.Src, pm.Dst, pm.Wdir, pm.Type, pm.Attr.pack())\n\tln := len(pm.Data)\n\tfmt.Fprintf(out, \"%d\\n%s\", ln, pm.Data[:ln])\n\n\treturn out.Bytes()\n}", "func Serialize(msgTx *wire.MsgTx) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\n\terr := msgTx.Serialize(&buffer)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot serialize transaction [%s]\", err)\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (msg MsgUnjail) GetSignBytes() []byte {\n\tbz := ModuleCdc.MustMarshalJSON(msg)\n\treturn sdk.MustSortJSON(bz)\n}", "func (p *Poll) EncodeToByte() []byte {\n\tb, _ := json.Marshal(p)\n\treturn b\n}", "func (message *Message) Bytes() ([]byte, error) {\n\treturn json.Marshal(*message) // Return encoded\n}", "func (v Boo) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson42239ddeEncodeMsgpJson(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (v Msg) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeBackendInternalModels6(w, v)\n}", "func BytesToPublicKey(data []byte) (pk *PublicKey) {\n\tpk = new(PublicKey)\n\tpk.PubKey.Curve = getDefaultCurve()\n\t//fmt.Printf(\"begin pub key unmarshal, len=%v, data=%v.\\n\", len(data), data)\n\tx, y := elliptic.Unmarshal(pk.PubKey.Curve, data)\n\tif x == nil || y == nil {\n\t\tpanic(\"unmarshal public key failed.\")\n\t}\n\tpk.PubKey.X = x\n\tpk.PubKey.Y = y\n\treturn\n}", "func obToMSG(ob Value) unsafe.Pointer {\n\tp := heap.Alloc(nMsg)\n\t*(*stMsg)(p) = stMsg{\n\t\thwnd: getUintptr(ob, \"hwnd\"),\n\t\tmessage: uint32(getInt(ob, \"message\")),\n\t\twParam: getUintptr(ob, \"wParam\"),\n\t\tlParam: getUintptr(ob, \"lParam\"),\n\t\ttime: uint32(getInt(ob, \"time\")),\n\t\tpt: getPoint(ob, \"pt\"),\n\t}\n\treturn p\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func (msg MsgMint) GetSignBytes() []byte {\n\treturn sdk.MustSortJSON(msgCdc.MustMarshalJSON(msg))\n}", "func (m *AtxProofMsg) SignedBytes() []byte {\n\tdata, err := codec.Encode(&m.InnerMsg)\n\tif err != nil {\n\t\tlog.With().Fatal(\"failed to serialize AtxProofMsg\", log.Err(err))\n\t}\n\treturn data\n}", "func encode(message interface{}) *bytes.Buffer {\n\tbuffer := &bytes.Buffer{}\n\t// Write struct's data as bytes\n\terr := binary.Write(buffer, binary.BigEndian, message)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn buffer\n}", "func (p *Poly) toMont() {\n\tvar f int16 = int16((uint64(1) << 32) % uint64(q))\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = montgomeryReduce(int32(p[i]) * int32(f))\n\t}\n}", "func (msg *Message) GetData() []byte {\n\treturn msg.data\n}", "func (m *OutMessage) Bytes() []byte {\n\tl := m.Len()\n\tsh := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(&m.header)),\n\t\tLen: l,\n\t\tCap: l,\n\t}\n\n\treturn *(*[]byte)(unsafe.Pointer(&sh))\n}" ]
[ "0.6873866", "0.5624386", "0.5447636", "0.5395681", "0.52409434", "0.5102153", "0.5080956", "0.5073594", "0.50528485", "0.49486172", "0.49464923", "0.49420258", "0.49371678", "0.49129784", "0.48999622", "0.48946768", "0.48854995", "0.4874926", "0.4871658", "0.4859851", "0.4821973", "0.4821894", "0.48030278", "0.48030278", "0.47955045", "0.47951722", "0.47900012", "0.47807312", "0.4766608", "0.47498345", "0.47488263", "0.47437066", "0.47417644", "0.4721371", "0.4673041", "0.46725965", "0.4664508", "0.4656923", "0.4655539", "0.46536055", "0.4652", "0.4646893", "0.46396467", "0.4638787", "0.4637674", "0.463748", "0.46326345", "0.46202904", "0.4619117", "0.4618925", "0.46092582", "0.46071845", "0.46071264", "0.4599221", "0.45982265", "0.45950118", "0.45940804", "0.45939058", "0.45816764", "0.45768735", "0.45761454", "0.45756474", "0.45677307", "0.45566547", "0.45551127", "0.45491618", "0.4544667", "0.45443103", "0.45365807", "0.45363167", "0.45357707", "0.45305434", "0.45252398", "0.45247206", "0.4520983", "0.45172614", "0.45125315", "0.4507467", "0.45000675", "0.4497189", "0.4493152", "0.44911522", "0.44906813", "0.44875288", "0.44870782", "0.44847852", "0.44838813", "0.44791445", "0.44736022", "0.44730192", "0.44690546", "0.44687822", "0.44647765", "0.44635734", "0.44626155", "0.445465", "0.4453753", "0.44525605", "0.44426727", "0.44404453" ]
0.8315796
0
compress packs a polynomial into a byte array using d bits per coefficient
func (p *Poly) compress(d int) []byte { c := make([]byte, n*d/8) switch d { case 3: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { for j := 0; j < 8; j++ { t[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/ uint32(q)) & ((1 << 3) - 1) } c[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6) c[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7) c[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5) id += 3 } case 4: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { for j := 0; j < 8; j++ { t[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/ uint32(q)) & ((1 << 4) - 1) } c[id] = byte(t[0]) | byte(t[1]<<4) c[id+1] = byte(t[2]) | byte(t[3]<<4) c[id+2] = byte(t[4]) | byte(t[5]<<4) c[id+3] = byte(t[6]) | byte(t[7]<<4) id += 4 } case 5: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { for j := 0; j < 8; j++ { t[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/ uint32(q)) & ((1 << 5) - 1) } c[id] = byte(t[0]) | byte(t[1]<<5) c[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7) c[id+2] = byte(t[3]>>1) | byte(t[4]<<4) c[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6) c[id+4] = byte(t[6]>>2) | byte(t[7]<<3) id += 5 } case 6: var t [4]uint16 id := 0 for i := 0; i < n/4; i++ { for j := 0; j < 4; j++ { t[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/ uint32(q)) & ((1 << 6) - 1) } c[id] = byte(t[0]) | byte(t[1]<<6) c[id+1] = byte(t[1]>>2) | byte(t[2]<<4) c[id+2] = byte(t[2]>>2) | byte(t[3]<<2) id += 3 } case 10: var t [4]uint16 id := 0 for i := 0; i < n/4; i++ { for j := 0; j < 4; j++ { t[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/ uint32(q)) & ((1 << 10) - 1) } c[id] = byte(t[0]) c[id+1] = byte(t[0]>>8) | byte(t[1]<<2) c[id+2] = byte(t[1]>>6) | byte(t[2]<<4) c[id+3] = byte(t[2]>>4) | byte(t[3]<<6) c[id+4] = byte(t[3] >> 2) id += 5 } case 11: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { for j := 0; j < 8; j++ { t[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/ uint32(q)) & ((1 << 11) - 1) } c[id] = byte(t[0]) c[id+1] = byte(t[0]>>8) | byte(t[1]<<3) c[id+2] = byte(t[1]>>5) | byte(t[2]<<6) c[id+3] = byte(t[2] >> 2) c[id+4] = byte(t[2]>>10) | byte(t[3]<<1) c[id+5] = byte(t[3]>>7) | byte(t[4]<<4) c[id+6] = byte(t[4]>>4) | byte(t[5]<<7) c[id+7] = byte(t[5] >> 1) c[id+8] = byte(t[5]>>9) | byte(t[6]<<2) c[id+9] = byte(t[6]>>6) | byte(t[7]<<5) c[id+10] = byte(t[7] >> 3) id += 11 } default: panic("bad d value") } return c[:] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decompressPoly(c []byte, d int) Poly {\n\tvar p Poly\n\tswitch d {\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = uint16(c[id]) >> 3\n\t\t\tt[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2)\n\t\t\tt[3] = uint16(c[id+1]) >> 1\n\t\t\tt[4] = uint16(c[id+1]) >> 4\n\t\t\tt[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1)\n\t\t\tt[6] = uint16(c[id+2]) >> 2\n\t\t\tt[7] = uint16(c[id+2]) >> 5\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 2) +\n\t\t\t\t\tuint32(t[j]&((1<<3)-1))*uint32(q)) >> 3)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\tcase 4:\n\t\tfor i := 0; i < n/2; i++ {\n\t\t\tp[2*i] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]&15)*uint32(q)) >> 4)\n\t\t\tp[2*i+1] = int16(((1 << 3) +\n\t\t\t\tuint32(c[i]>>4)*uint32(q)) >> 4)\n\t\t}\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3))\n\t\t\tt[2] = uint16(c[id+1]) >> 2\n\t\t\tt[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1))\n\t\t\tt[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4))\n\t\t\tt[5] = uint16(c[id+3]) >> 1\n\t\t\tt[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2))\n\t\t\tt[7] = uint16(c[id+4]) >> 3\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 4) +\n\t\t\t\t\tuint32(t[j]&((1<<5)-1))*uint32(q)) >> 5)\n\t\t\t}\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id])\n\t\t\tt[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2))\n\t\t\tt[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4)\n\t\t\tt[3] = uint16(c[id+2]) >> 2\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 5) +\n\t\t\t\t\tuint32(t[j]&((1<<6)-1))*uint32(q)) >> 6)\n\t\t\t}\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6)\n\t\t\tt[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4)\n\t\t\tt[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2)\n\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tp[4*i+j] = int16(((1 << 9) +\n\t\t\t\t\tuint32(t[j]&((1<<10)-1))*uint32(q)) >> 10)\n\t\t\t}\n\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tt[0] = uint16(c[id]) | (uint16(c[id+1]) << 8)\n\t\t\tt[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5)\n\t\t\tt[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10)\n\t\t\tt[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7)\n\t\t\tt[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4)\n\t\t\tt[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9)\n\t\t\tt[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6)\n\t\t\tt[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3)\n\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tp[8*i+j] = int16(((1 << 10) +\n\t\t\t\t\tuint32(t[j]&((1<<11)-1))*uint32(q)) >> 11)\n\t\t\t}\n\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn p\n}", "func CompressWithBitSize(src []int32, bitSize int) []byte {\n}", "func encode(size int, input []byte, position int, numberOfByte int, controlBitsQuantity int) []byte {\n\tencoded := make([]byte, int(size/8))\n\t//Data bits accommodate process\n\tfor i := controlBitsQuantity - 1; i > 0; i-- {\n\t\tsl := expInt(i) - 1\n\t\til := expInt(i-1) - 1\n\t\tfor j := sl - 1; j > il; j-- {\n\t\t\tdataBit := takeBit(input[numberOfByte], position, 7-int(j%8))\n\t\t\tx := int(j / 8)\n\t\t\tencoded[x] = encoded[x] | dataBit\n\t\t\tposition++\n\t\t\tif position > 7 {\n\t\t\t\tnumberOfByte--\n\t\t\t\tposition = 0\n\t\t\t}\n\t\t}\n\t}\n\t//Control bits calculus process\n\tfor i := 0; i < controlBitsQuantity-1; i++ {\n\t\tparity := byte(0)\n\t\tfor j := expInt(i) - 1; j < size; j += expInt(i + 1) {\n\t\t\tfor k := 0; k < expInt(i); k++ {\n\t\t\t\tparity ^= takeBit(encoded[int((j+k)/8)], 7-((j+k)%8), 0)\n\t\t\t}\n\t\t}\n\t\tx := int(int(expInt(i)-1) / 8)\n\t\tencoded[x] = encoded[x] | takeBit(parity, 0, 7-(expInt(i)-1)%8)\n\t}\n\treturn encoded\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\n\tret := make([]byte, 1+byteLen)\n\tret[0] = 2 // compressed point\n\n\txBytes := x.Bytes()\n\tcopy(ret[1+byteLen-len(xBytes):], xBytes)\n\tret[0] += byte(y.Bit(0))\n\treturn ret\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func compress(input []int) []int {\n\tout := make([]int, len(input)/16)\n\tfor i := 0; i < len(out); i++ {\n\t\tx := 0\n\t\tfor j := 0; j < 16; j++ {\n\t\t\tx = x ^ (input[i*16+j])\n\t\t}\n\t\tout[i] = x\n\t}\n\treturn out\n}", "func PACKUSDWm128byte(X1 []byte, X2 []byte)", "func (d *digest) compress() {\n\tvar m, v [16]uint32\n\tfor i := 0; i < 16; i++ {\n\t\tm[i] = binary.LittleEndian.Uint32(d.buf[i*4:])\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\tv[i] = d.h[i]\n\t}\n\tv[8] = iv[0]\n\tv[9] = iv[1]\n\tv[10] = iv[2]\n\tv[11] = iv[3]\n\tv[12] = d.t[0] ^ iv[4]\n\tv[13] = d.t[1] ^ iv[5]\n\tv[14] = d.f[0] ^ iv[6]\n\tv[15] = d.f[1] ^ iv[7]\n\n\trotr32 := func (w uint32, c uint32) uint32 {\n\t\treturn (w>>c) | (w<<(32-c))\n\t}\n\tG := func(r, i, a, b, c, d int) {\n\t\tv[a] = v[a] + v[b] + m[sigma[r][2*i+0]]\n\t\tv[d] = rotr32(v[d] ^ v[a], 16)\n\t\tv[c] = v[c] + v[d]\n\t\tv[b] = rotr32(v[b] ^ v[c], 12)\n\t\tv[a] = v[a] + v[b] + m[sigma[r][2*i+1]]\n\t\tv[d] = rotr32(v[d] ^ v[a], 8)\n\t\tv[c] = v[c] + v[d]\n\t\tv[b] = rotr32(v[b] ^ v[c], 7)\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\tG(i, 0, 0, 4, 8, 12);\n\t\tG(i, 1, 1, 5, 9, 13);\n\t\tG(i, 2, 2, 6, 10, 14);\n\t\tG(i, 3, 3, 7, 11, 15);\n\t\tG(i, 4, 0, 5, 10, 15);\n\t\tG(i, 5, 1, 6, 11, 12);\n\t\tG(i, 6, 2, 7, 8, 13);\n\t\tG(i, 7, 3, 4, 9, 14);\n\t}\n\tfor i := 0; i < 8; i++ {\n\t\td.h[i] = d.h[i] ^ v[i] ^ v[i+8]\n\t}\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func Pack(values []int64) ([]byte, error) {\n\tif len(values) == 0 {\n\t\treturn nil, nil\n\t}\n\tif values[0] < 0 {\n\t\treturn nil, errors.Reason(\"values must be between 0 and 2**63\").Err()\n\t}\n\tif values[len(values)-1] < 0 {\n\t\treturn nil, errors.Reason(\"values must be between 0 and 2**63\").Err()\n\t}\n\n\tvar b bytes.Buffer\n\tw := zlib.NewWriter(&b)\n\tvar last int64\n\tfor _, value := range values {\n\t\tv := value\n\t\tvalue -= last\n\t\tif value < 0 {\n\t\t\treturn nil, errors.Reason(\"list must be sorted ascending\").Err()\n\t\t}\n\t\tlast = v\n\t\tfor value > 127 {\n\t\t\tif _, err := w.Write([]byte{byte(1<<7 | value&0x7f)}); err != nil {\n\t\t\t\treturn nil, errors.Annotate(err, \"failed to write\").Err()\n\t\t\t}\n\t\t\tvalue >>= 7\n\t\t}\n\t\tif _, err := w.Write([]byte{byte(value)}); err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"failed to write\").Err()\n\t\t}\n\n\t}\n\tif err := w.Close(); err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to close zlib writer\").Err()\n\t}\n\n\treturn b.Bytes(), nil\n}", "func compress(publicKey []byte) ([]byte, error) {\n\tif len(publicKey) == pubKeyBytesLenUncompressed-1 && publicKey[0] != compressedKeyPrefix {\n\t\tpublicKey = append([]byte{compressedKeyPrefix}, publicKey...)\n\t}\n\tif len(publicKey) != pubKeyBytesLenUncompressed {\n\t\treturn nil, errors.Errorf(\"length of uncompressed public key is invalid\")\n\t}\n\tx, y := elliptic.Unmarshal(ecies.DefaultCurve, publicKey)\n\n\treturn secp256k1.CompressPubkey(x, y), nil\n}", "func generate(degree byte, x byte, rand io.Reader) ([]byte, error) {\n\tresult := make([]byte, degree+1)\n\tresult[0] = x\n\n\tbuf := make([]byte, degree-1)\n\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := byte(1); i < degree; i++ {\n\t\tresult[i] = buf[i-1]\n\t}\n\n\t// the Nth term can't be zero, or else it's a (N-1) degree polynomial\n\tfor {\n\t\tbuf = make([]byte, 1)\n\t\tif _, err := io.ReadFull(rand, buf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif buf[0] != 0 {\n\t\t\tresult[degree] = buf[0]\n\t\t\treturn result, nil\n\t\t}\n\t}\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func compress(chars []byte) int {\n \n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func Ctoz_byte(input []byte, inputStride int, output DSPSplitComplex, outputStride int) {\n\tvar splitComplex C.DSPSplitComplex\n\tsplitComplex.realp = (*C.float)(&output.Real[0])\n\tsplitComplex.imagp = (*C.float)(&output.Imag[0])\n\tn := 2 * len(output.Real) / outputStride\n\tif n2 := len(input) / (4 * inputStride); n2 < n {\n\t\tn = n2\n\t}\n\tC.vDSP_ctoz((*C.DSPComplex)(unsafe.Pointer(&input[0])), C.vDSP_Stride(inputStride), &splitComplex, C.vDSP_Stride(outputStride), C.vDSP_Length(n))\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func (pk *PublicKey) Compress() *CompressedPublicKey {\n\n\t// Serialize X Coordinate\n\tcpk := new(CompressedPublicKey)\n\tcopy(cpk[1:], pk[:CoordinateSize])\n\n\t// Set header byte depending on parity of Y coordinate\n\tyIsEven := pk[PublicSize-1]%2 == 0\n\tif yIsEven {\n\t\tcpk[0] = HeaderCompressedEven\n\t} else {\n\t\tcpk[0] = HeaderCompressedOdd\n\t}\n\n\treturn cpk\n}", "func decompress(publicKey []byte) []byte {\n\tx, y := secp256k1.DecompressPubkey(publicKey)\n\treturn elliptic.Marshal(ecies.DefaultCurve, x, y)\n}", "func (pk *PublicKey) Pack(buf *[PublicKeySize]byte) {\n\tvar tmp [mode2.PublicKeySize]byte\n\tpk.d.Pack(&tmp)\n\tcopy(buf[:mode2.PublicKeySize], tmp[:])\n\tcopy(buf[mode2.PublicKeySize:], pk.e)\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func compress(n uint64) ([]byte, error) {\n\t/* Output buffer */\n\tbuf := &bytes.Buffer{}\n\t/* Compressor, which stores to buf */\n\tzw, err := gzip.NewWriterLevel(buf, gzip.BestCompression)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\t/* Write zeros to the compressor */\n\tvar (\n\t\tzeros = make([]byte, COMPRESSCHUNK) /* Zeros to compress */\n\t\ttot = uint64(0) /* Number written */\n\t)\n\tfor tot < n {\n\t\t/* For the last chunk, only write as many zeros as we need */\n\t\tif uint64(len(zeros)) > n-tot {\n\t\t\tzeros = zeros[:n-tot]\n\t\t}\n\t\t/* Write zeros to the compressor */\n\t\tnw, err := zw.Write(zeros)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\ttot += uint64(nw)\n\t}\n\tif err := zw.Close(); nil != err {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func p256FromMont(res, in []uint64)", "func p256FromMont(res, in []uint64)", "func encode(src []byte) ([]byte, int) {\n\n\tvar dst []byte\n\tx := new(big.Int).SetBytes(src)\n\tr := new(big.Int)\n\tm := big.NewInt(58)\n\tzero := big.NewInt(0)\n\ts := \"\"\n\n\t/* While x > 0 */\n\tfor x.Cmp(zero) > 0 {\n\t\t/* x, r = (x / 58, x % 58) */\n\t\tx.QuoRem(x, m, r)\n\t\t/* Prepend ASCII character */\n\t\ts = string(base58table[r.Int64()]) + s\n\t\tdst = append(dst, base58table[r.Int64()])\n\t}\n\n\t/* For number of leading 0's in bytes, prepend 1 */\n\tfor _, v := range src {\n\t\tif v != 0 {\n\t\t\tbreak\n\t\t}\n\t\tdst = append(dst, base58table[0])\n\t}\n\n\tfor i := 0; i < len(dst)/2; i++ {\n\t\tdst[i], dst[len(dst)-1-i] =\n\t\t\tdst[len(dst)-1-i], dst[i]\n\t}\n\treturn dst, len(dst)\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func castagnoliSSE42(crc uint32, p []byte) uint32", "func Sum128(data []byte) (h1 uint64, h2 uint64)", "func PACKSSLW(mx, x operand.Op) { ctx.PACKSSLW(mx, x) }", "func compressHuffmanCodes(codes *vector.Vector) (compressedCodes *vector.Vector, lastByteInBits int) {\n\tcurrentCode := vector.New(0, 8)\n\tencodedCode := byte(0)\n\ttotalBits := 0\n\n\tcompressedCodes = vector.New()\n\n\tfor i := 0; i < codes.Size(); i++ {\n\t\tcurrentCode.Append(codes.MustGet(i))\n\n\t\tif currentCode.Size() != 8 && i != codes.Size()-1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor j := 0; j < currentCode.Size(); j++ {\n\t\t\ttotalBits++\n\n\t\t\tencodedCode <<= 1\n\n\t\t\tif currentCode.MustGet(j) != byte(0) {\n\t\t\t\tencodedCode |= 1\n\t\t\t}\n\t\t}\n\n\t\tcompressedCodes.Append(encodedCode)\n\t\tcurrentCode = vector.New(0, 8)\n\t\tencodedCode = byte(0)\n\t}\n\n\tlastByteInBits = totalBits % 8\n\n\tif lastByteInBits == 0 {\n\t\tlastByteInBits = 8\n\t}\n\n\treturn compressedCodes, lastByteInBits\n}", "func Compress(uncompressed *vector.Vector) *vector.Vector {\n\tbyteFrequencies := createFrequencyTable(uncompressed)\n\tprefixTree := buildPrefixTree(byteFrequencies)\n\n\tcodes := dictionary.New()\n\tbuildCodes(prefixTree, vector.New(), codes)\n\n\tcompressedPrefixTree := vector.New()\n\tcompressPrefixTree(prefixTree, compressedPrefixTree)\n\n\tencodedBytes := encodeToHuffmanCodes(uncompressed, codes)\n\n\tcompressedCodes, lastByteInBits := compressHuffmanCodes(encodedBytes)\n\n\t// Reserve space for the last byte size, prefix tree and huffman codes\n\tcompressed := vector.New(0, 1+uint(compressedPrefixTree.Size()+compressedCodes.Size()))\n\tcompressed.Append(byte(lastByteInBits))\n\n\tfor i := 0; i < compressedPrefixTree.Size(); i++ {\n\t\tcompressed.Append(compressedPrefixTree.MustGet(i))\n\t}\n\n\tfor i := 0; i < compressedCodes.Size(); i++ {\n\t\tcompressed.Append(compressedCodes.MustGet(i))\n\t}\n\n\treturn compressed\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func HexadecAxpy(c, b []float64, s float64, ci, bi int)", "func Compress(src []int32) []byte {\n\tbestBitSize := -1\n\tbestTotalSize := -1\n\n\tfor _, bitSize := range possibleBitSize {\n\t\tif totalSize := estimateCompressedSize(src, bitSize); bestTotalSize < 0 || totalSize < bestTotalSize {\n\t\t\tbestBitSize = bitSize\n\t\t\tbestTotalSize = totalSize\n\t\t}\n\t}\n\n\treturn CompressWithBitSize(src, bestBitSize)\n}", "func PMULDQm128byte(X1 []byte, X2 []byte)", "func (n *Uint256) toBin() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits.\n\tmaxOutDigits := n.BitLen()\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 2 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that no partial digit handling is needed in this case because the shift\n\t// amount evenly divides the bits per internal word.\n\tconst shift = 1\n\tconst mask = 1<<shift - 1\n\tconst digitsPerInternalWord = bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\tfor i := 0; i < digitsPerInternalWord; i++ {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\t\tinputWord = n.n[inputIdx]\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func (b bit128) toByteSlice() []byte {\n\tdst := make([]byte, 16)\n\t_ = dst[15]\n\tbinary.BigEndian.PutUint64(dst[0:8], b[0])\n\tbinary.BigEndian.PutUint64(dst[8:16], b[1])\n\treturn dst\n}", "func (curve *Curve) CompressPoint(X, Y *big.Int) (cp []byte) {\n\tby := new(big.Int).And(Y, big.NewInt(1)).Int64()\n\tbx := X.Bytes()\n\tcp = make([]byte, len(bx)+1)\n\tif by == 1 {\n\t\tcp[0] = byte(3)\n\t} else {\n\t\tcp[0] = byte(2)\n\t}\n\tcopy(cp[1:], bx)\n\n\treturn\n}", "func Sum(out *[16]byte, m []byte, key *[32]byte) {\n\tr := key\n\ts := key[16:]\n\tvar (\n\t\ty7 float64\n\t\ty6 float64\n\t\ty1 float64\n\t\ty0 float64\n\t\ty5 float64\n\t\ty4 float64\n\t\tx7 float64\n\t\tx6 float64\n\t\tx1 float64\n\t\tx0 float64\n\t\ty3 float64\n\t\ty2 float64\n\t\tx5 float64\n\t\tr3lowx0 float64\n\t\tx4 float64\n\t\tr0lowx6 float64\n\t\tx3 float64\n\t\tr3highx0 float64\n\t\tx2 float64\n\t\tr0highx6 float64\n\t\tr0lowx0 float64\n\t\tsr1lowx6 float64\n\t\tr0highx0 float64\n\t\tsr1highx6 float64\n\t\tsr3low float64\n\t\tr1lowx0 float64\n\t\tsr2lowx6 float64\n\t\tr1highx0 float64\n\t\tsr2highx6 float64\n\t\tr2lowx0 float64\n\t\tsr3lowx6 float64\n\t\tr2highx0 float64\n\t\tsr3highx6 float64\n\t\tr1highx4 float64\n\t\tr1lowx4 float64\n\t\tr0highx4 float64\n\t\tr0lowx4 float64\n\t\tsr3highx4 float64\n\t\tsr3lowx4 float64\n\t\tsr2highx4 float64\n\t\tsr2lowx4 float64\n\t\tr0lowx2 float64\n\t\tr0highx2 float64\n\t\tr1lowx2 float64\n\t\tr1highx2 float64\n\t\tr2lowx2 float64\n\t\tr2highx2 float64\n\t\tsr3lowx2 float64\n\t\tsr3highx2 float64\n\t\tz0 float64\n\t\tz1 float64\n\t\tz2 float64\n\t\tz3 float64\n\t\tm0 int64\n\t\tm1 int64\n\t\tm2 int64\n\t\tm3 int64\n\t\tm00 uint32\n\t\tm01 uint32\n\t\tm02 uint32\n\t\tm03 uint32\n\t\tm10 uint32\n\t\tm11 uint32\n\t\tm12 uint32\n\t\tm13 uint32\n\t\tm20 uint32\n\t\tm21 uint32\n\t\tm22 uint32\n\t\tm23 uint32\n\t\tm30 uint32\n\t\tm31 uint32\n\t\tm32 uint32\n\t\tm33 uint64\n\t\tlbelow2 int32\n\t\tlbelow3 int32\n\t\tlbelow4 int32\n\t\tlbelow5 int32\n\t\tlbelow6 int32\n\t\tlbelow7 int32\n\t\tlbelow8 int32\n\t\tlbelow9 int32\n\t\tlbelow10 int32\n\t\tlbelow11 int32\n\t\tlbelow12 int32\n\t\tlbelow13 int32\n\t\tlbelow14 int32\n\t\tlbelow15 int32\n\t\ts00 uint32\n\t\ts01 uint32\n\t\ts02 uint32\n\t\ts03 uint32\n\t\ts10 uint32\n\t\ts11 uint32\n\t\ts12 uint32\n\t\ts13 uint32\n\t\ts20 uint32\n\t\ts21 uint32\n\t\ts22 uint32\n\t\ts23 uint32\n\t\ts30 uint32\n\t\ts31 uint32\n\t\ts32 uint32\n\t\ts33 uint32\n\t\tbits32 uint64\n\t\tf uint64\n\t\tf0 uint64\n\t\tf1 uint64\n\t\tf2 uint64\n\t\tf3 uint64\n\t\tf4 uint64\n\t\tg uint64\n\t\tg0 uint64\n\t\tg1 uint64\n\t\tg2 uint64\n\t\tg3 uint64\n\t\tg4 uint64\n\t)\n\n\tvar p int32\n\n\tl := int32(len(m))\n\n\tr00 := uint32(r[0])\n\n\tr01 := uint32(r[1])\n\n\tr02 := uint32(r[2])\n\tr0 := int64(2151)\n\n\tr03 := uint32(r[3])\n\tr03 &= 15\n\tr0 <<= 51\n\n\tr10 := uint32(r[4])\n\tr10 &= 252\n\tr01 <<= 8\n\tr0 += int64(r00)\n\n\tr11 := uint32(r[5])\n\tr02 <<= 16\n\tr0 += int64(r01)\n\n\tr12 := uint32(r[6])\n\tr03 <<= 24\n\tr0 += int64(r02)\n\n\tr13 := uint32(r[7])\n\tr13 &= 15\n\tr1 := int64(2215)\n\tr0 += int64(r03)\n\n\td0 := r0\n\tr1 <<= 51\n\tr2 := int64(2279)\n\n\tr20 := uint32(r[8])\n\tr20 &= 252\n\tr11 <<= 8\n\tr1 += int64(r10)\n\n\tr21 := uint32(r[9])\n\tr12 <<= 16\n\tr1 += int64(r11)\n\n\tr22 := uint32(r[10])\n\tr13 <<= 24\n\tr1 += int64(r12)\n\n\tr23 := uint32(r[11])\n\tr23 &= 15\n\tr2 <<= 51\n\tr1 += int64(r13)\n\n\td1 := r1\n\tr21 <<= 8\n\tr2 += int64(r20)\n\n\tr30 := uint32(r[12])\n\tr30 &= 252\n\tr22 <<= 16\n\tr2 += int64(r21)\n\n\tr31 := uint32(r[13])\n\tr23 <<= 24\n\tr2 += int64(r22)\n\n\tr32 := uint32(r[14])\n\tr2 += int64(r23)\n\tr3 := int64(2343)\n\n\td2 := r2\n\tr3 <<= 51\n\n\tr33 := uint32(r[15])\n\tr33 &= 15\n\tr31 <<= 8\n\tr3 += int64(r30)\n\n\tr32 <<= 16\n\tr3 += int64(r31)\n\n\tr33 <<= 24\n\tr3 += int64(r32)\n\n\tr3 += int64(r33)\n\th0 := alpha32 - alpha32\n\n\td3 := r3\n\th1 := alpha32 - alpha32\n\n\th2 := alpha32 - alpha32\n\n\th3 := alpha32 - alpha32\n\n\th4 := alpha32 - alpha32\n\n\tr0low := math.Float64frombits(uint64(d0))\n\th5 := alpha32 - alpha32\n\n\tr1low := math.Float64frombits(uint64(d1))\n\th6 := alpha32 - alpha32\n\n\tr2low := math.Float64frombits(uint64(d2))\n\th7 := alpha32 - alpha32\n\n\tr0low -= alpha0\n\n\tr1low -= alpha32\n\n\tr2low -= alpha64\n\n\tr0high := r0low + alpha18\n\n\tr3low := math.Float64frombits(uint64(d3))\n\n\tr1high := r1low + alpha50\n\tsr1low := scale * r1low\n\n\tr2high := r2low + alpha82\n\tsr2low := scale * r2low\n\n\tr0high -= alpha18\n\tr0high_stack := r0high\n\n\tr3low -= alpha96\n\n\tr1high -= alpha50\n\tr1high_stack := r1high\n\n\tsr1high := sr1low + alpham80\n\n\tr0low -= r0high\n\n\tr2high -= alpha82\n\tsr3low = scale * r3low\n\n\tsr2high := sr2low + alpham48\n\n\tr1low -= r1high\n\tr1low_stack := r1low\n\n\tsr1high -= alpham80\n\tsr1high_stack := sr1high\n\n\tr2low -= r2high\n\tr2low_stack := r2low\n\n\tsr2high -= alpham48\n\tsr2high_stack := sr2high\n\n\tr3high := r3low + alpha112\n\tr0low_stack := r0low\n\n\tsr1low -= sr1high\n\tsr1low_stack := sr1low\n\n\tsr3high := sr3low + alpham16\n\tr2high_stack := r2high\n\n\tsr2low -= sr2high\n\tsr2low_stack := sr2low\n\n\tr3high -= alpha112\n\tr3high_stack := r3high\n\n\tsr3high -= alpham16\n\tsr3high_stack := sr3high\n\n\tr3low -= r3high\n\tr3low_stack := r3low\n\n\tsr3low -= sr3high\n\tsr3low_stack := sr3low\n\n\tif l < 16 {\n\t\tgoto addatmost15bytes\n\t}\n\n\tm00 = uint32(m[p+0])\n\tm0 = 2151\n\n\tm0 <<= 51\n\tm1 = 2215\n\tm01 = uint32(m[p+1])\n\n\tm1 <<= 51\n\tm2 = 2279\n\tm02 = uint32(m[p+2])\n\n\tm2 <<= 51\n\tm3 = 2343\n\tm03 = uint32(m[p+3])\n\n\tm10 = uint32(m[p+4])\n\tm01 <<= 8\n\tm0 += int64(m00)\n\n\tm11 = uint32(m[p+5])\n\tm02 <<= 16\n\tm0 += int64(m01)\n\n\tm12 = uint32(m[p+6])\n\tm03 <<= 24\n\tm0 += int64(m02)\n\n\tm13 = uint32(m[p+7])\n\tm3 <<= 51\n\tm0 += int64(m03)\n\n\tm20 = uint32(m[p+8])\n\tm11 <<= 8\n\tm1 += int64(m10)\n\n\tm21 = uint32(m[p+9])\n\tm12 <<= 16\n\tm1 += int64(m11)\n\n\tm22 = uint32(m[p+10])\n\tm13 <<= 24\n\tm1 += int64(m12)\n\n\tm23 = uint32(m[p+11])\n\tm1 += int64(m13)\n\n\tm30 = uint32(m[p+12])\n\tm21 <<= 8\n\tm2 += int64(m20)\n\n\tm31 = uint32(m[p+13])\n\tm22 <<= 16\n\tm2 += int64(m21)\n\n\tm32 = uint32(m[p+14])\n\tm23 <<= 24\n\tm2 += int64(m22)\n\n\tm33 = uint64(m[p+15])\n\tm2 += int64(m23)\n\n\td0 = m0\n\tm31 <<= 8\n\tm3 += int64(m30)\n\n\td1 = m1\n\tm32 <<= 16\n\tm3 += int64(m31)\n\n\td2 = m2\n\tm33 += 256\n\n\tm33 <<= 24\n\tm3 += int64(m32)\n\n\tm3 += int64(m33)\n\td3 = m3\n\n\tp += 16\n\tl -= 16\n\n\tz0 = math.Float64frombits(uint64(d0))\n\n\tz1 = math.Float64frombits(uint64(d1))\n\n\tz2 = math.Float64frombits(uint64(d2))\n\n\tz3 = math.Float64frombits(uint64(d3))\n\n\tz0 -= alpha0\n\n\tz1 -= alpha32\n\n\tz2 -= alpha64\n\n\tz3 -= alpha96\n\n\th0 += z0\n\n\th1 += z1\n\n\th3 += z2\n\n\th5 += z3\n\n\tif l < 16 {\n\t\tgoto multiplyaddatmost15bytes\n\t}\n\nmultiplyaddatleast16bytes:\n\n\tm2 = 2279\n\tm20 = uint32(m[p+8])\n\ty7 = h7 + alpha130\n\n\tm2 <<= 51\n\tm3 = 2343\n\tm21 = uint32(m[p+9])\n\ty6 = h6 + alpha130\n\n\tm3 <<= 51\n\tm0 = 2151\n\tm22 = uint32(m[p+10])\n\ty1 = h1 + alpha32\n\n\tm0 <<= 51\n\tm1 = 2215\n\tm23 = uint32(m[p+11])\n\ty0 = h0 + alpha32\n\n\tm1 <<= 51\n\tm30 = uint32(m[p+12])\n\ty7 -= alpha130\n\n\tm21 <<= 8\n\tm2 += int64(m20)\n\tm31 = uint32(m[p+13])\n\ty6 -= alpha130\n\n\tm22 <<= 16\n\tm2 += int64(m21)\n\tm32 = uint32(m[p+14])\n\ty1 -= alpha32\n\n\tm23 <<= 24\n\tm2 += int64(m22)\n\tm33 = uint64(m[p+15])\n\ty0 -= alpha32\n\n\tm2 += int64(m23)\n\tm00 = uint32(m[p+0])\n\ty5 = h5 + alpha96\n\n\tm31 <<= 8\n\tm3 += int64(m30)\n\tm01 = uint32(m[p+1])\n\ty4 = h4 + alpha96\n\n\tm32 <<= 16\n\tm02 = uint32(m[p+2])\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tm33 += 256\n\tm03 = uint32(m[p+3])\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tm33 <<= 24\n\tm3 += int64(m31)\n\tm10 = uint32(m[p+4])\n\tx1 = h1 - y1\n\n\tm01 <<= 8\n\tm3 += int64(m32)\n\tm11 = uint32(m[p+5])\n\tx0 = h0 - y0\n\n\tm3 += int64(m33)\n\tm0 += int64(m00)\n\tm12 = uint32(m[p+6])\n\ty5 -= alpha96\n\n\tm02 <<= 16\n\tm0 += int64(m01)\n\tm13 = uint32(m[p+7])\n\ty4 -= alpha96\n\n\tm03 <<= 24\n\tm0 += int64(m02)\n\td2 = m2\n\tx1 += y7\n\n\tm0 += int64(m03)\n\td3 = m3\n\tx0 += y6\n\n\tm11 <<= 8\n\tm1 += int64(m10)\n\td0 = m0\n\tx7 += y5\n\n\tm12 <<= 16\n\tm1 += int64(m11)\n\tx6 += y4\n\n\tm13 <<= 24\n\tm1 += int64(m12)\n\ty3 = h3 + alpha64\n\n\tm1 += int64(m13)\n\td1 = m1\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\tz2 = math.Float64frombits(uint64(d2))\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\tz3 = math.Float64frombits(uint64(d3))\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\tz2 -= alpha64\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\tz3 -= alpha96\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\tp += 16\n\tl -= 16\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\tz1 = math.Float64frombits(uint64(d1))\n\th0 += sr3lowx2\n\n\tz0 = math.Float64frombits(uint64(d0))\n\th1 += sr3highx2\n\n\tz1 -= alpha32\n\n\tz0 -= alpha0\n\n\th5 += z3\n\n\th3 += z2\n\n\th1 += z1\n\n\th0 += z0\n\n\tif l >= 16 {\n\t\tgoto multiplyaddatleast16bytes\n\t}\n\nmultiplyaddatmost15bytes:\n\n\ty7 = h7 + alpha130\n\n\ty6 = h6 + alpha130\n\n\ty1 = h1 + alpha32\n\n\ty0 = h0 + alpha32\n\n\ty7 -= alpha130\n\n\ty6 -= alpha130\n\n\ty1 -= alpha32\n\n\ty0 -= alpha32\n\n\ty5 = h5 + alpha96\n\n\ty4 = h4 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tx1 = h1 - y1\n\n\tx0 = h0 - y0\n\n\ty5 -= alpha96\n\n\ty4 -= alpha96\n\n\tx1 += y7\n\n\tx0 += y6\n\n\tx7 += y5\n\n\tx6 += y4\n\n\ty3 = h3 + alpha64\n\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\th0 += sr3lowx2\n\n\th1 += sr3highx2\n\naddatmost15bytes:\n\n\tif l == 0 {\n\t\tgoto nomorebytes\n\t}\n\n\tlbelow2 = l - 2\n\n\tlbelow3 = l - 3\n\n\tlbelow2 >>= 31\n\tlbelow4 = l - 4\n\n\tm00 = uint32(m[p+0])\n\tlbelow3 >>= 31\n\tp += lbelow2\n\n\tm01 = uint32(m[p+1])\n\tlbelow4 >>= 31\n\tp += lbelow3\n\n\tm02 = uint32(m[p+2])\n\tp += lbelow4\n\tm0 = 2151\n\n\tm03 = uint32(m[p+3])\n\tm0 <<= 51\n\tm1 = 2215\n\n\tm0 += int64(m00)\n\tm01 &^= uint32(lbelow2)\n\n\tm02 &^= uint32(lbelow3)\n\tm01 -= uint32(lbelow2)\n\n\tm01 <<= 8\n\tm03 &^= uint32(lbelow4)\n\n\tm0 += int64(m01)\n\tlbelow2 -= lbelow3\n\n\tm02 += uint32(lbelow2)\n\tlbelow3 -= lbelow4\n\n\tm02 <<= 16\n\tm03 += uint32(lbelow3)\n\n\tm03 <<= 24\n\tm0 += int64(m02)\n\n\tm0 += int64(m03)\n\tlbelow5 = l - 5\n\n\tlbelow6 = l - 6\n\tlbelow7 = l - 7\n\n\tlbelow5 >>= 31\n\tlbelow8 = l - 8\n\n\tlbelow6 >>= 31\n\tp += lbelow5\n\n\tm10 = uint32(m[p+4])\n\tlbelow7 >>= 31\n\tp += lbelow6\n\n\tm11 = uint32(m[p+5])\n\tlbelow8 >>= 31\n\tp += lbelow7\n\n\tm12 = uint32(m[p+6])\n\tm1 <<= 51\n\tp += lbelow8\n\n\tm13 = uint32(m[p+7])\n\tm10 &^= uint32(lbelow5)\n\tlbelow4 -= lbelow5\n\n\tm10 += uint32(lbelow4)\n\tlbelow5 -= lbelow6\n\n\tm11 &^= uint32(lbelow6)\n\tm11 += uint32(lbelow5)\n\n\tm11 <<= 8\n\tm1 += int64(m10)\n\n\tm1 += int64(m11)\n\tm12 &^= uint32(lbelow7)\n\n\tlbelow6 -= lbelow7\n\tm13 &^= uint32(lbelow8)\n\n\tm12 += uint32(lbelow6)\n\tlbelow7 -= lbelow8\n\n\tm12 <<= 16\n\tm13 += uint32(lbelow7)\n\n\tm13 <<= 24\n\tm1 += int64(m12)\n\n\tm1 += int64(m13)\n\tm2 = 2279\n\n\tlbelow9 = l - 9\n\tm3 = 2343\n\n\tlbelow10 = l - 10\n\tlbelow11 = l - 11\n\n\tlbelow9 >>= 31\n\tlbelow12 = l - 12\n\n\tlbelow10 >>= 31\n\tp += lbelow9\n\n\tm20 = uint32(m[p+8])\n\tlbelow11 >>= 31\n\tp += lbelow10\n\n\tm21 = uint32(m[p+9])\n\tlbelow12 >>= 31\n\tp += lbelow11\n\n\tm22 = uint32(m[p+10])\n\tm2 <<= 51\n\tp += lbelow12\n\n\tm23 = uint32(m[p+11])\n\tm20 &^= uint32(lbelow9)\n\tlbelow8 -= lbelow9\n\n\tm20 += uint32(lbelow8)\n\tlbelow9 -= lbelow10\n\n\tm21 &^= uint32(lbelow10)\n\tm21 += uint32(lbelow9)\n\n\tm21 <<= 8\n\tm2 += int64(m20)\n\n\tm2 += int64(m21)\n\tm22 &^= uint32(lbelow11)\n\n\tlbelow10 -= lbelow11\n\tm23 &^= uint32(lbelow12)\n\n\tm22 += uint32(lbelow10)\n\tlbelow11 -= lbelow12\n\n\tm22 <<= 16\n\tm23 += uint32(lbelow11)\n\n\tm23 <<= 24\n\tm2 += int64(m22)\n\n\tm3 <<= 51\n\tlbelow13 = l - 13\n\n\tlbelow13 >>= 31\n\tlbelow14 = l - 14\n\n\tlbelow14 >>= 31\n\tp += lbelow13\n\tlbelow15 = l - 15\n\n\tm30 = uint32(m[p+12])\n\tlbelow15 >>= 31\n\tp += lbelow14\n\n\tm31 = uint32(m[p+13])\n\tp += lbelow15\n\tm2 += int64(m23)\n\n\tm32 = uint32(m[p+14])\n\tm30 &^= uint32(lbelow13)\n\tlbelow12 -= lbelow13\n\n\tm30 += uint32(lbelow12)\n\tlbelow13 -= lbelow14\n\n\tm3 += int64(m30)\n\tm31 &^= uint32(lbelow14)\n\n\tm31 += uint32(lbelow13)\n\tm32 &^= uint32(lbelow15)\n\n\tm31 <<= 8\n\tlbelow14 -= lbelow15\n\n\tm3 += int64(m31)\n\tm32 += uint32(lbelow14)\n\td0 = m0\n\n\tm32 <<= 16\n\tm33 = uint64(lbelow15 + 1)\n\td1 = m1\n\n\tm33 <<= 24\n\tm3 += int64(m32)\n\td2 = m2\n\n\tm3 += int64(m33)\n\td3 = m3\n\n\tz3 = math.Float64frombits(uint64(d3))\n\n\tz2 = math.Float64frombits(uint64(d2))\n\n\tz1 = math.Float64frombits(uint64(d1))\n\n\tz0 = math.Float64frombits(uint64(d0))\n\n\tz3 -= alpha96\n\n\tz2 -= alpha64\n\n\tz1 -= alpha32\n\n\tz0 -= alpha0\n\n\th5 += z3\n\n\th3 += z2\n\n\th1 += z1\n\n\th0 += z0\n\n\ty7 = h7 + alpha130\n\n\ty6 = h6 + alpha130\n\n\ty1 = h1 + alpha32\n\n\ty0 = h0 + alpha32\n\n\ty7 -= alpha130\n\n\ty6 -= alpha130\n\n\ty1 -= alpha32\n\n\ty0 -= alpha32\n\n\ty5 = h5 + alpha96\n\n\ty4 = h4 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tx1 = h1 - y1\n\n\tx0 = h0 - y0\n\n\ty5 -= alpha96\n\n\ty4 -= alpha96\n\n\tx1 += y7\n\n\tx0 += y6\n\n\tx7 += y5\n\n\tx6 += y4\n\n\ty3 = h3 + alpha64\n\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\th0 += sr3lowx2\n\n\th1 += sr3highx2\n\nnomorebytes:\n\n\ty7 = h7 + alpha130\n\n\ty0 = h0 + alpha32\n\n\ty1 = h1 + alpha32\n\n\ty2 = h2 + alpha64\n\n\ty7 -= alpha130\n\n\ty3 = h3 + alpha64\n\n\ty4 = h4 + alpha96\n\n\ty5 = h5 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\ty0 -= alpha32\n\n\ty1 -= alpha32\n\n\ty2 -= alpha64\n\n\th6 += x7\n\n\ty3 -= alpha64\n\n\ty4 -= alpha96\n\n\ty5 -= alpha96\n\n\ty6 = h6 + alpha130\n\n\tx0 = h0 - y0\n\n\tx1 = h1 - y1\n\n\tx2 = h2 - y2\n\n\ty6 -= alpha130\n\n\tx0 += y7\n\n\tx3 = h3 - y3\n\n\tx4 = h4 - y4\n\n\tx5 = h5 - y5\n\n\tx6 = h6 - y6\n\n\ty6 *= scale\n\n\tx2 += y0\n\n\tx3 += y1\n\n\tx4 += y2\n\n\tx0 += y6\n\n\tx5 += y3\n\n\tx6 += y4\n\n\tx2 += x3\n\n\tx0 += x1\n\n\tx4 += x5\n\n\tx6 += y5\n\n\tx2 += offset1\n\td1 = int64(math.Float64bits(x2))\n\n\tx0 += offset0\n\td0 = int64(math.Float64bits(x0))\n\n\tx4 += offset2\n\td2 = int64(math.Float64bits(x4))\n\n\tx6 += offset3\n\td3 = int64(math.Float64bits(x6))\n\n\tf0 = uint64(d0)\n\n\tf1 = uint64(d1)\n\tbits32 = math.MaxUint64\n\n\tf2 = uint64(d2)\n\tbits32 >>= 32\n\n\tf3 = uint64(d3)\n\tf = f0 >> 32\n\n\tf0 &= bits32\n\tf &= 255\n\n\tf1 += f\n\tg0 = f0 + 5\n\n\tg = g0 >> 32\n\tg0 &= bits32\n\n\tf = f1 >> 32\n\tf1 &= bits32\n\n\tf &= 255\n\tg1 = f1 + g\n\n\tg = g1 >> 32\n\tf2 += f\n\n\tf = f2 >> 32\n\tg1 &= bits32\n\n\tf2 &= bits32\n\tf &= 255\n\n\tf3 += f\n\tg2 = f2 + g\n\n\tg = g2 >> 32\n\tg2 &= bits32\n\n\tf4 = f3 >> 32\n\tf3 &= bits32\n\n\tf4 &= 255\n\tg3 = f3 + g\n\n\tg = g3 >> 32\n\tg3 &= bits32\n\n\tg4 = f4 + g\n\n\tg4 = g4 - 4\n\ts00 = uint32(s[0])\n\n\tf = uint64(int64(g4) >> 63)\n\ts01 = uint32(s[1])\n\n\tf0 &= f\n\tg0 &^= f\n\ts02 = uint32(s[2])\n\n\tf1 &= f\n\tf0 |= g0\n\ts03 = uint32(s[3])\n\n\tg1 &^= f\n\tf2 &= f\n\ts10 = uint32(s[4])\n\n\tf3 &= f\n\tg2 &^= f\n\ts11 = uint32(s[5])\n\n\tg3 &^= f\n\tf1 |= g1\n\ts12 = uint32(s[6])\n\n\tf2 |= g2\n\tf3 |= g3\n\ts13 = uint32(s[7])\n\n\ts01 <<= 8\n\tf0 += uint64(s00)\n\ts20 = uint32(s[8])\n\n\ts02 <<= 16\n\tf0 += uint64(s01)\n\ts21 = uint32(s[9])\n\n\ts03 <<= 24\n\tf0 += uint64(s02)\n\ts22 = uint32(s[10])\n\n\ts11 <<= 8\n\tf1 += uint64(s10)\n\ts23 = uint32(s[11])\n\n\ts12 <<= 16\n\tf1 += uint64(s11)\n\ts30 = uint32(s[12])\n\n\ts13 <<= 24\n\tf1 += uint64(s12)\n\ts31 = uint32(s[13])\n\n\tf0 += uint64(s03)\n\tf1 += uint64(s13)\n\ts32 = uint32(s[14])\n\n\ts21 <<= 8\n\tf2 += uint64(s20)\n\ts33 = uint32(s[15])\n\n\ts22 <<= 16\n\tf2 += uint64(s21)\n\n\ts23 <<= 24\n\tf2 += uint64(s22)\n\n\ts31 <<= 8\n\tf3 += uint64(s30)\n\n\ts32 <<= 16\n\tf3 += uint64(s31)\n\n\ts33 <<= 24\n\tf3 += uint64(s32)\n\n\tf2 += uint64(s23)\n\tf3 += uint64(s33)\n\n\tout[0] = byte(f0)\n\tf0 >>= 8\n\tout[1] = byte(f0)\n\tf0 >>= 8\n\tout[2] = byte(f0)\n\tf0 >>= 8\n\tout[3] = byte(f0)\n\tf0 >>= 8\n\tf1 += f0\n\n\tout[4] = byte(f1)\n\tf1 >>= 8\n\tout[5] = byte(f1)\n\tf1 >>= 8\n\tout[6] = byte(f1)\n\tf1 >>= 8\n\tout[7] = byte(f1)\n\tf1 >>= 8\n\tf2 += f1\n\n\tout[8] = byte(f2)\n\tf2 >>= 8\n\tout[9] = byte(f2)\n\tf2 >>= 8\n\tout[10] = byte(f2)\n\tf2 >>= 8\n\tout[11] = byte(f2)\n\tf2 >>= 8\n\tf3 += f2\n\n\tout[12] = byte(f3)\n\tf3 >>= 8\n\tout[13] = byte(f3)\n\tf3 >>= 8\n\tout[14] = byte(f3)\n\tf3 >>= 8\n\tout[15] = byte(f3)\n}", "func encode(k Key) ([]byte, error) {\n\tver := k.version()\n\tpsize := ver.PayloadSize()\n\ttsize := 1 + psize + 4\n\traw := k.raw()\n\tif len(raw) > psize {\n\t\treturn nil, errors.New(\"tbd\")\n\t}\n\ttmp := make([]byte, tsize)\n\ttmp[0] = byte(ver)\n\tcopy(tmp[len(tmp)-4-len(raw):], raw)\n\tsum := doublehash.SumDoubleSha256(tmp[:1+psize])\n\tcopy(tmp[1+psize:], sum[:4])\n\treturn rippleEncoding.Encode(tmp)\n}", "func compressBlock(data []byte) []byte {\n\t// Preallocate the output slice on the optimistic assumption that\n\t// the output won't be bigger than the input.\n\tret := make([]byte, 0, len(data))\n\tfor i := 0; i < len(data); i++ {\n\t\t// Last byte in the input? Encode it and be done.\n\t\tif i == len(data)-1 {\n\t\t\tret = append(ret, byteLiteral(data[i])...)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Have we seen a run already? If so then encode it.\n\t\tl, offset := findRun(data[i:], data[0:i])\n\t\tif l >= 3 {\n\t\t\t// 10 bytes is our maximum run length.\n\t\t\tif l > 10 {\n\t\t\t\tl = 10\n\t\t\t}\n\t\t\tword := uint16(offset<<3+(l-3)) | 0x8000\n\t\t\tret = append(ret, byte(word>>8), byte(word&0xff))\n\n\t\t\ti += (l - 1)\n\t\t\tcontinue\n\t\t}\n\n\t\t// space + printable? Add in the special byte and be done.\n\t\tif data[i] == ' ' && (data[i+1] >= 0x40 && data[i+1] <= 0x7f) {\n\t\t\tret = append(ret, 0x80^data[i+1])\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\n\t\t// A literal character? Then just pass it on to the output stream.\n\t\tif (data[i] >= 0x09 && data[i] <= 0x7f) || data[i] == 0 {\n\t\t\tret = append(ret, data[i])\n\t\t\tcontinue\n\t\t}\n\n\t\t// Not a literal. In that case we need to blob a range of bytes --\n\t\t// send out a chunk as big as we can.\n\t\tmax := len(data) - i\n\t\tif max > 8 {\n\t\t\tmax = 8\n\t\t}\n\t\tret = append(ret, byte(max))\n\t\tret = append(ret, data[i:i+max]...)\n\t\ti += (max - 1)\n\t\tcontinue\n\t}\n\n\treturn ret\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func (k *PublicKey) Bytes(compressed bool) []byte {\n\tx := k.X.Bytes()\n\tif len(x) < 32 {\n\t\tfor i := 0; i < 32-len(x); i++ {\n\t\t\tx = append([]byte{0}, x...)\n\t\t}\n\t}\n\n\tif compressed {\n\t\t// If odd\n\t\tif k.Y.Bit(0) != 0 {\n\t\t\treturn bytes.Join([][]byte{{0x03}, x}, nil)\n\t\t}\n\n\t\t// If even\n\t\treturn bytes.Join([][]byte{{0x02}, x}, nil)\n\t}\n\n\ty := k.Y.Bytes()\n\tif len(y) < 32 {\n\t\tfor i := 0; i < 32-len(y); i++ {\n\t\t\ty = append([]byte{0}, y...)\n\t\t}\n\t}\n\n\treturn bytes.Join([][]byte{{0x04}, x, y}, nil)\n}", "func PACKUSDW(mx, x operand.Op) { ctx.PACKUSDW(mx, x) }", "func compress_helper(chars []byte) [] byte {\n if len(chars) <= 1 {\n //base case\n return chars \n }\n \n w := chars[0]\n var count int = 1 \n var i int \n //get repetitions for the character\n for i=1; i<len(chars);i++ {\n if chars[i] == w {\n count++\n } else {\n break\n } \n } \n var res []byte = make([]byte, 0) \n if count == 1 {\n //a\n res = append(res, w)\n } else {\n //a3\n res = append([]byte{w}, []byte(strconv.Itoa(count))...)\n }\n //make recursive call to compress rest of the string\n res = append(res, compress_helper(chars[i:])...)\n for k, v := range res {\n chars[k] = v\n }\n \n chars = chars[:len(res)] \n return chars \n}", "func Compress(input []byte) []byte {\n\tout := make([]byte, 0, len(input)/2) // estimate output size\n\tvar verb []byte\n\n\tfor len(input) > 0 {\n\t\tprefixLen := 0\n\t\tvar code byte\n\t\tn := &codeTrie\n\t\tfor i, c := range input {\n\t\t\tnext := n.branches[int(c)]\n\t\t\tif next == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tn = next\n\t\t\tif n.terminal {\n\t\t\t\tprefixLen = i + 1\n\t\t\t\tcode = n.val\n\t\t\t}\n\t\t}\n\n\t\tif prefixLen > 0 {\n\t\t\tinput = input[prefixLen:]\n\t\t\tout = flushVerb(out, verb)\n\t\t\tverb = verb[:0]\n\t\t\tout = append(out, code)\n\t\t} else {\n\t\t\tverb = append(verb, input[0])\n\t\t\tinput = input[1:]\n\t\t}\n\t}\n\treturn flushVerb(out, verb)\n}", "func encodeBytes(r uint16, decoded []byte) (uint16, []byte) {\n\tvar c1, c2, cipher uint16\n\tc1 = 52845\n\tc2 = 22719\n\tencoded := make([]byte, len(decoded))\n\tfor i, plain := range decoded {\n\t\tcipher = uint16(plain) ^ (r >> 8)\n\t\tr = (uint16(cipher)+r)*c1 + c2\n\t\tencoded[i] = byte(cipher)\n\t}\n\treturn r, encoded\n}", "func HexAxpy(c, b []float64, s float64, ci, bi int)", "func SignCompact(key *PrivateKey, hash []byte, isCompressedKey bool) ([]byte, error) {\n\tsig := key.Sign(hash)\n\n\tcurve := S256()\n\t// bitcoind checks the bit length of R and S here. The ecdsa signature\n\t// algorithm returns R and S mod N therefore they will be the bitsize of\n\t// the curve, and thus correctly sized.\n\tfor i := 0; i < (curve.H+1)*2; i++ {\n\t\tpk, err := recoverKeyFromSignature(sig, hash, i, true)\n\t\tif err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {\n\t\t\tresult := make([]byte, 1, 2*curve.byteSize+1)\n\t\t\tresult[0] = 27 + byte(i)\n\t\t\tif isCompressedKey {\n\t\t\t\tresult[0] += 4\n\t\t\t}\n\t\t\t// Not sure this needs rounding but safer to do so.\n\t\t\tcurvelen := (curve.BitSize + 7) / 8\n\n\t\t\t// Pad R and S to curvelen if needed.\n\t\t\tbytelen := (sig.R.BitLen() + 7) / 8\n\t\t\tif bytelen < curvelen {\n\t\t\t\tresult = append(result,\n\t\t\t\t\tmake([]byte, curvelen-bytelen)...)\n\t\t\t}\n\t\t\tresult = append(result, sig.R.Bytes()...)\n\n\t\t\tbytelen = (sig.S.BitLen() + 7) / 8\n\t\t\tif bytelen < curvelen {\n\t\t\t\tresult = append(result,\n\t\t\t\t\tmake([]byte, curvelen-bytelen)...)\n\t\t\t}\n\t\t\tresult = append(result, sig.S.Bytes()...)\n\n\t\t\treturn result, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"no valid solution for pubkey found\")\n}", "func PCMPEQQm128byte(X1 []byte, X2 []byte)", "func uleb128enc(bout []byte, value int) int {\n\t/* To encode:\n\tGrab the lowest 7 bits of your value and store them in a byte,\n\tthis is what you're going to output.\n\tShift the value 7 bits to the right, getting rid of those 7 bits you just grabbed.\n\tIf the value is non-zero (ie. after you shifted away 7 bits from it),\n\tset the high bit of the byte you're going to output before you output it.\n\tOutput the byte\n\tIf the value is non-zero (ie. same check that resulted in setting the high bit),\n\tgo back and repeat the steps from the start*/\n\tif len(bout) < 10 {\n\t\tpanic(\"Need to give a buffer of at least 10\")\n\t}\n\tcount := 0\n\tfor first, i := true, 0; first || value > 0; i++ {\n\t\tfirst = false\n\t\tlower7bits := byte(value & 0x7f)\n\t\tvalue >>= 7\n\t\tif value > 0 {\n\t\t\tlower7bits |= 128\n\t\t}\n\t\tbout[i] = lower7bits\n\t\tcount++\n\n\t}\n\treturn count\n}", "func p256ReduceDegree(out *[p256Limbs]uint32, tmp [17]uint64) {\n\t// The following table may be helpful when reading this code:\n\t//\n\t// Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...\n\t// Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29\n\t// Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285\n\t// (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285\n\tvar tmp2 [18]uint32\n\tvar carry, x, xMask uint32\n\n\t// tmp contains 64-bit words with the same 29,28,29-bit positions as a\n\t// field element. So the top of an element of tmp might overlap with\n\t// another element two positions down. The following loop eliminates\n\t// this overlap.\n\ttmp2[0] = uint32(tmp[0]) & bottom29Bits\n\n\ttmp2[1] = uint32(tmp[0]) >> 29\n\ttmp2[1] |= (uint32(tmp[0]>>32) << 3) & bottom28Bits\n\ttmp2[1] += uint32(tmp[1]) & bottom28Bits\n\tcarry = tmp2[1] >> 28\n\ttmp2[1] &= bottom28Bits\n\n\tfor i := 2; i < 17; i++ {\n\t\ttmp2[i] = (uint32(tmp[i-2] >> 32)) >> 25\n\t\ttmp2[i] += (uint32(tmp[i-1])) >> 28\n\t\ttmp2[i] += (uint32(tmp[i-1]>>32) << 4) & bottom29Bits\n\t\ttmp2[i] += uint32(tmp[i]) & bottom29Bits\n\t\ttmp2[i] += carry\n\t\tcarry = tmp2[i] >> 29\n\t\ttmp2[i] &= bottom29Bits\n\n\t\ti++\n\t\tif i == 17 {\n\t\t\tbreak\n\t\t}\n\t\ttmp2[i] = uint32(tmp[i-2]>>32) >> 25\n\t\ttmp2[i] += uint32(tmp[i-1]) >> 29\n\t\ttmp2[i] += ((uint32(tmp[i-1] >> 32)) << 3) & bottom28Bits\n\t\ttmp2[i] += uint32(tmp[i]) & bottom28Bits\n\t\ttmp2[i] += carry\n\t\tcarry = tmp2[i] >> 28\n\t\ttmp2[i] &= bottom28Bits\n\t}\n\n\ttmp2[17] = uint32(tmp[15]>>32) >> 25\n\ttmp2[17] += uint32(tmp[16]) >> 29\n\ttmp2[17] += uint32(tmp[16]>>32) << 3\n\ttmp2[17] += carry\n\n\t// Montgomery elimination of terms:\n\t//\n\t// Since R is 2**257, we can divide by R with a bitwise shift if we can\n\t// ensure that the right-most 257 bits are all zero. We can make that true\n\t// by adding multiplies of p without affecting the value.\n\t//\n\t// So we eliminate limbs from right to left. Since the bottom 29 bits of p\n\t// are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.\n\t// We can do that for 8 further limbs and then right shift to eliminate the\n\t// extra factor of R.\n\tfor i := 0; ; i += 2 {\n\t\ttmp2[i+1] += tmp2[i] >> 29\n\t\tx = tmp2[i] & bottom29Bits\n\t\txMask = nonZeroToAllOnes(x)\n\t\ttmp2[i] = 0\n\n\t\t// The bounds calculations for this loop are tricky. Each iteration of\n\t\t// the loop eliminates two words by adding values to words to their\n\t\t// right.\n\t\t//\n\t\t// The following table contains the amounts added to each word (as an\n\t\t// offset from the value of i at the top of the loop). The amounts are\n\t\t// accounted for from the first and second half of the loop separately\n\t\t// and are written as, for example, 28 to mean a value <2**28.\n\t\t//\n\t\t// Word: 3 4 5 6 7 8 9 10\n\t\t// Added in top half: 28 11 29 21 29 28\n\t\t// 28 29\n\t\t// 29\n\t\t// Added in bottom half: 29 10 28 21 28 28\n\t\t// 29\n\t\t//\n\t\t// The value that is currently offset 7 will be offset 5 for the next\n\t\t// iteration and then offset 3 for the iteration after that. Therefore\n\t\t// the total value added will be the values added at 7, 5 and 3.\n\t\t//\n\t\t// The following table accumulates these values. The sums at the bottom\n\t\t// are written as, for example, 29+28, to mean a value < 2**29+2**28.\n\t\t//\n\t\t// Word: 3 4 5 6 7 8 9 10 11 12 13\n\t\t// 28 11 10 29 21 29 28 28 28 28 28\n\t\t// 29 28 11 28 29 28 29 28 29 28\n\t\t// 29 28 21 21 29 21 29 21\n\t\t// 10 29 28 21 28 21 28\n\t\t// 28 29 28 29 28 29 28\n\t\t// 11 10 29 10 29 10\n\t\t// 29 28 11 28 11\n\t\t// 29 29\n\t\t// --------------------------------------------\n\t\t// 30+ 31+ 30+ 31+ 30+\n\t\t// 28+ 29+ 28+ 29+ 21+\n\t\t// 21+ 28+ 21+ 28+ 10\n\t\t// 10 21+ 10 21+\n\t\t// 11 11\n\t\t//\n\t\t// So the greatest amount is added to tmp2[10] and tmp2[12]. If\n\t\t// tmp2[10/12] has an initial value of <2**29, then the maximum value\n\t\t// will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,\n\t\t// as required.\n\t\ttmp2[i+3] += (x << 10) & bottom28Bits\n\t\ttmp2[i+4] += (x >> 18)\n\n\t\ttmp2[i+6] += (x << 21) & bottom29Bits\n\t\ttmp2[i+7] += x >> 8\n\n\t\t// At position 200, which is the starting bit position for word 7, we\n\t\t// have a factor of 0xf000000 = 2**28 - 2**24.\n\t\ttmp2[i+7] += 0x10000000 & xMask\n\t\ttmp2[i+8] += (x - 1) & xMask\n\t\ttmp2[i+7] -= (x << 24) & bottom28Bits\n\t\ttmp2[i+8] -= x >> 4\n\n\t\ttmp2[i+8] += 0x20000000 & xMask\n\t\ttmp2[i+8] -= x\n\t\ttmp2[i+8] += (x << 28) & bottom29Bits\n\t\ttmp2[i+9] += ((x >> 1) - 1) & xMask\n\n\t\tif i+1 == p256Limbs {\n\t\t\tbreak\n\t\t}\n\t\ttmp2[i+2] += tmp2[i+1] >> 28\n\t\tx = tmp2[i+1] & bottom28Bits\n\t\txMask = nonZeroToAllOnes(x)\n\t\ttmp2[i+1] = 0\n\n\t\ttmp2[i+4] += (x << 11) & bottom29Bits\n\t\ttmp2[i+5] += (x >> 18)\n\n\t\ttmp2[i+7] += (x << 21) & bottom28Bits\n\t\ttmp2[i+8] += x >> 7\n\n\t\t// At position 199, which is the starting bit of the 8th word when\n\t\t// dealing with a context starting on an odd word, we have a factor of\n\t\t// 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th\n\t\t// word from i+1 is i+8.\n\t\ttmp2[i+8] += 0x20000000 & xMask\n\t\ttmp2[i+9] += (x - 1) & xMask\n\t\ttmp2[i+8] -= (x << 25) & bottom29Bits\n\t\ttmp2[i+9] -= x >> 4\n\n\t\ttmp2[i+9] += 0x10000000 & xMask\n\t\ttmp2[i+9] -= x\n\t\ttmp2[i+10] += (x - 1) & xMask\n\t}\n\n\t// We merge the right shift with a carry chain. The words above 2**257 have\n\t// widths of 28,29,... which we need to correct when copying them down.\n\tcarry = 0\n\tfor i := 0; i < 8; i++ {\n\t\t// The maximum value of tmp2[i + 9] occurs on the first iteration and\n\t\t// is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is\n\t\t// therefore safe.\n\t\tout[i] = tmp2[i+9]\n\t\tout[i] += carry\n\t\tout[i] += (tmp2[i+10] << 28) & bottom29Bits\n\t\tcarry = out[i] >> 29\n\t\tout[i] &= bottom29Bits\n\n\t\ti++\n\t\tout[i] = tmp2[i+9] >> 1\n\t\tout[i] += carry\n\t\tcarry = out[i] >> 28\n\t\tout[i] &= bottom28Bits\n\t}\n\n\tout[8] = tmp2[17]\n\tout[8] += carry\n\tcarry = out[8] >> 29\n\tout[8] &= bottom29Bits\n\n\tp256ReduceCarry(out, carry)\n}", "func VPCOMPRESSD(ops ...operand.Op) { ctx.VPCOMPRESSD(ops...) }", "func encodeBytes(data []byte) []byte {\n\t// Allocate more space to avoid unnecessary slice growing.\n\t// Assume that the byte slice size is about `(len(data) / encGroupSize + 1) * (encGroupSize + 1)` bytes,\n\t// that is `(len(data) / 8 + 1) * 9` in our implement.\n\tdLen := len(data)\n\tresult := make([]byte, 0, (dLen/encGroupSize+1)*(encGroupSize+1))\n\tfor idx := 0; idx <= dLen; idx += encGroupSize {\n\t\tremain := dLen - idx\n\t\tpadCount := 0\n\t\tif remain >= encGroupSize {\n\t\t\tresult = append(result, data[idx:idx+encGroupSize]...)\n\t\t} else {\n\t\t\tpadCount = encGroupSize - remain\n\t\t\tresult = append(result, data[idx:]...)\n\t\t\tresult = append(result, pads[:padCount]...)\n\t\t}\n\n\t\tmarker := encMarker - byte(padCount)\n\t\tresult = append(result, marker)\n\t}\n\treturn result\n}", "func (n *Uint256) toOctal() []byte {\n\tif n.IsZero() {\n\t\treturn []byte(\"0\")\n\t}\n\n\t// Create space for the max possible number of output digits using the fact\n\t// that 3 bits converts directly to a single octal digit.\n\tmaxOutDigits := (n.BitLen() + 2) / 3\n\tresult := make([]byte, maxOutDigits)\n\n\t// Convert each internal base 2^64 word to base 8 from least to most\n\t// significant. Since the value is guaranteed to be non-zero per a previous\n\t// check, there will always be a nonzero most-significant word. Also, note\n\t// that partial digit handling is needed in this case because the shift\n\t// amount does not evenly divide the bits per internal word.\n\tconst shift = 3\n\tconst mask = 1<<shift - 1\n\tunconvertedBits := bitsPerInternalWord\n\toutputIdx := maxOutDigits - 1\n\tnumInputWords := n.numDigits()\n\tinputWord := n.n[0]\n\tfor inputIdx := 1; inputIdx < numInputWords; inputIdx++ {\n\t\t// Convert full digits.\n\t\tfor ; unconvertedBits >= shift; unconvertedBits -= shift {\n\t\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\t\tinputWord >>= shift\n\t\t\toutputIdx--\n\t\t}\n\n\t\t// Move to the next input word when there are not any remaining\n\t\t// unconverted bits that need to be handled.\n\t\tif unconvertedBits == 0 {\n\t\t\tinputWord = n.n[inputIdx]\n\t\t\tunconvertedBits = bitsPerInternalWord\n\t\t\tcontinue\n\t\t}\n\n\t\t// Account for the remaining unconverted bits from the current word and\n\t\t// the bits needed from the next word to form a full digit for the next\n\t\t// digit.\n\t\tinputWord |= n.n[inputIdx] << unconvertedBits\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\toutputIdx--\n\n\t\t// Move to the next input word while accounting for the bits already\n\t\t// consumed above by shifting it and updating the unconverted bits\n\t\t// accordingly.\n\t\tinputWord = n.n[inputIdx] >> (shift - unconvertedBits)\n\t\tunconvertedBits = bitsPerInternalWord - (shift - unconvertedBits)\n\t}\n\tfor inputWord != 0 {\n\t\tresult[outputIdx] = '0' + byte(inputWord&mask)\n\t\tinputWord >>= shift\n\t\toutputIdx--\n\t}\n\n\treturn result[outputIdx+1:]\n}", "func packSFzVertex(v []FzVertex, ptr0 *C.fz_vertex) {\n\tconst m = 0x7fffffff\n\tfor i0 := range v {\n\t\tptr1 := (*(*[m / sizeOfFzVertexValue]C.fz_vertex)(unsafe.Pointer(ptr0)))[i0]\n\t\tv[i0] = *NewFzVertexRef(unsafe.Pointer(&ptr1))\n\t}\n}", "func PMAXSDm128byte(X1 []byte, X2 []byte)", "func (p *Proof) ProofBytes() []byte {\n\tbuff := new(bytes.Buffer)\n\n\t// The solution we serialise depends on the size of the cuckoo graph. The\n\t// cycle is always of length 42, but each vertex takes up more bits on\n\t// larger graphs, nonceLengthBits is this number of bits.\n\tnonceLengthBits := uint(p.EdgeBits)\n\n\t// Make a slice just large enough to fit all of the POW bits.\n\tbitvecLengthBits := nonceLengthBits * uint(ProofSize)\n\tbitvec := make([]uint8, (bitvecLengthBits+7)/8)\n\n\tfor n, nonce := range p.Nonces {\n\t\t// Pack this nonce into the bit stream.\n\t\tfor bit := uint(0); bit < nonceLengthBits; bit++ {\n\t\t\t// If this bit is set, then write it to the correct position in the\n\t\t\t// stream.\n\t\t\tif nonce&(1<<bit) != 0 {\n\t\t\t\toffsetBits := uint(n)*nonceLengthBits + bit\n\t\t\t\tbitvec[offsetBits/8] |= 1 << (offsetBits % 8)\n\t\t\t}\n\t\t}\n\t}\n\n\tif _, err := buff.Write(bitvec); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\treturn buff.Bytes()\n}", "func pack10(src []uint64) uint64 {\n\t_ = src[9] // eliminate multiple bounds checks\n\treturn 7<<60 |\n\t\tsrc[0] |\n\t\tsrc[1]<<6 |\n\t\tsrc[2]<<12 |\n\t\tsrc[3]<<18 |\n\t\tsrc[4]<<24 |\n\t\tsrc[5]<<30 |\n\t\tsrc[6]<<36 |\n\t\tsrc[7]<<42 |\n\t\tsrc[8]<<48 |\n\t\tsrc[9]<<54\n}", "func EncodeAll(src []uint64) ([]uint64, error) {\n\ti := 0\n\n\t// Re-use the input slice and write encoded values back in place\n\tdst := src\n\tj := 0\n\nNEXTVALUE:\n\tfor i < len(src) {\n\t\tremaining := src[i:]\n\n\t\t// try to pack run of 240 or 120 1s\n\t\tif len(remaining) >= 120 {\n\t\t\t// Invariant: len(a) is fixed to 120 or 240 values\n\t\t\tvar a []uint64\n\t\t\tif len(remaining) >= 240 {\n\t\t\t\ta = remaining[:240]\n\t\t\t} else {\n\t\t\t\ta = remaining[:120]\n\t\t\t}\n\n\t\t\t// search for the longest sequence of 1s in a\n\t\t\t// Postcondition: k equals the index of the last 1 or -1\n\t\t\tk := 0\n\t\t\tfor k = range a {\n\t\t\t\tif a[k] != 1 {\n\t\t\t\t\tk--\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tv := uint64(0)\n\t\t\tswitch {\n\t\t\tcase k == 239:\n\t\t\t\t// 240 1s\n\t\t\t\ti += 240\n\n\t\t\tcase k >= 119:\n\t\t\t\t// at least 120 1s\n\t\t\t\tv = 1 << 60\n\t\t\t\ti += 120\n\n\t\t\tdefault:\n\t\t\t\tgoto CODES\n\t\t\t}\n\n\t\t\tdst[j] = v\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\tCODES:\n\t\tfor code := range numBits {\n\t\t\tintN := int(numBits[code][0])\n\t\t\tbitN := numBits[code][1]\n\t\t\tif intN > len(remaining) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmaxVal := uint64(1 << (bitN & 0x3f))\n\t\t\tval := uint64(code+2) << S8B_BIT_SIZE\n\n\t\t\tfor k, inV := range remaining {\n\t\t\t\tif k < intN {\n\t\t\t\t\tif inV >= maxVal {\n\t\t\t\t\t\tcontinue CODES\n\t\t\t\t\t}\n\t\t\t\t\tval |= inV << ((byte(k) * bitN) & 0x3f)\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tdst[j] = val\n\t\t\tj += 1\n\t\t\ti += intN\n\t\t\tcontinue NEXTVALUE\n\t\t}\n\t\treturn nil, ErrValueOutOfBounds\n\t}\n\treturn dst[:j], nil\n}", "func (d *DecompressionBuffer) Decompress() []float64 {\n\tfirst := d.readFloat()\n\tresult := []float64{first}\n\n\tnumber := first\n\tfor d.hasMore() && len(result) < d.expectedSize {\n\t\tif d.ReadBit() {\n\t\t\t// Hit a 1, so we need another bit to know what to do.\n\t\t\t// Otherwise it's a repeat of the previous value.\n\t\t\tif d.ReadBit() {\n\t\t\t\t// With have full XOR + lengths\n\t\t\t\tnumber = d.readFullXOR(number)\n\t\t\t} else {\n\t\t\t\t// We have partial XOR (it has the same number of leading zeroes and length)\n\t\t\t\tnumber = d.readPartialXOR(number)\n\t\t\t}\n\t\t}\n\t\tresult = append(result, number)\n\t}\n\treturn result\n}", "func (t Tuple) Pack() []byte {\n\tbuf := new(bytes.Buffer)\n\n\tfor i, e := range t {\n\t\tswitch e := e.(type) {\n\t\tcase nil:\n\t\t\tbuf.WriteByte(0x00)\n\t\tcase int64:\n\t\t\tencodeInt(buf, e)\n\t\tcase uint32:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase uint64:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase int:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase byte:\n\t\t\tencodeInt(buf, int64(e))\n\t\tcase []byte:\n\t\t\tencodeBytes(buf, 0x01, e)\n\t\tcase lex.KeyConvertible:\n\t\t\tencodeBytes(buf, 0x01, []byte(e.LexKey()))\n\t\tcase string:\n\t\t\tencodeBytes(buf, 0x02, []byte(e))\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unencodable element at index %d (%v, type %T)\", i, t[i], t[i]))\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func pack4(src []uint64) uint64 {\n\t_ = src[3] // eliminate multiple bounds checks\n\treturn 12<<60 |\n\t\tsrc[0] |\n\t\tsrc[1]<<15 |\n\t\tsrc[2]<<30 |\n\t\tsrc[3]<<45\n}", "func Sum128x32(key []byte, seed uint32) [4]uint32 {\n\tconst c1 = 0x239b961b\n\tconst c2 = 0xab0e9789\n\tconst c3 = 0x38b34ae5\n\tconst c4 = 0xa1e38b93\n\n\th1, h2, h3, h4 := seed, seed, seed, seed\n\n\tsize := len(key)\n\tblocks := size / 16\n\n\thead := *(*[]uint32)(unsafe.Pointer(&key))\n\ttail := key[blocks*16:]\n\n\t// Head\n\tfor i := 0; i < blocks; i++ {\n\t\tk1 := head[i*4+0]\n\t\tk2 := head[i*4+1]\n\t\tk3 := head[i*4+2]\n\t\tk4 := head[i*4+3]\n\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\n\t\th1 = (h1 << 19) | (h1 >> 13) // rotl32(h1, 19)\n\t\th1 += h2\n\t\th1 = h1*5 + 0x561ccd1b\n\n\t\tk2 *= c2\n\t\tk2 = (k2 << 16) | (k2 >> 16) // rotl32(k2, 16)\n\t\tk2 *= c3\n\t\th2 ^= k2\n\n\t\th2 = (h2 << 17) | (h2 >> 15) // rotl32(h2, 17)\n\t\th2 += h3\n\t\th2 = h2*5 + 0x0bcaa747\n\n\t\tk3 *= c3\n\t\tk3 = (k3 << 17) | (k3 >> 15) // rotl32(k3, 17)\n\t\tk3 *= c4\n\t\th3 ^= k3\n\n\t\th3 = (h3 << 15) | (h3 >> 17) // rotl32(h3, 15)\n\t\th3 += h4\n\t\th3 = h3*5 + 0x96cd1c35\n\n\t\tk4 *= c4\n\t\tk4 = (k4 << 18) | (k4 >> 14) // rotl32(k4, 18)\n\t\tk4 *= c1\n\t\th4 ^= k4\n\n\t\th4 = (h4 << 13) | (h4 >> 19) // rotl32(h4, 13)\n\t\th4 += h1\n\t\th4 = h4*5 + 0x32ac3b17\n\t}\n\n\tvar k1, k2, k3, k4 uint32\n\n\t// Tail\n\tswitch size & 0xf {\n\tcase 0xf:\n\t\tk4 ^= uint32(tail[14]) << 16\n\t\tfallthrough\n\tcase 0xe:\n\t\tk4 ^= uint32(tail[13]) << 8\n\t\tfallthrough\n\tcase 0xd:\n\t\tk4 ^= uint32(tail[12])\n\t\tk4 *= c4\n\t\tk4 = (k4 << 18) | (k4 >> 14) // rotl32(k4, 18)\n\t\tk4 *= c1\n\t\th4 ^= k4\n\t\tfallthrough\n\n\tcase 0xc:\n\t\tk3 ^= uint32(tail[11]) << 24\n\t\tfallthrough\n\tcase 0xb:\n\t\tk3 ^= uint32(tail[10]) << 16\n\t\tfallthrough\n\tcase 0xa:\n\t\tk3 ^= uint32(tail[9]) << 8\n\t\tfallthrough\n\tcase 0x9:\n\t\tk3 ^= uint32(tail[8])\n\t\tk3 *= c3\n\t\tk3 = (k3 << 17) | (k3 >> 15) // rotl32(k3, 17)\n\t\tk3 *= c4\n\t\th3 ^= k3\n\t\tfallthrough\n\n\tcase 0x8:\n\t\tk2 ^= uint32(tail[7]) << 24\n\t\tfallthrough\n\tcase 0x7:\n\t\tk2 ^= uint32(tail[6]) << 16\n\t\tfallthrough\n\tcase 0x6:\n\t\tk2 ^= uint32(tail[5]) << 8\n\t\tfallthrough\n\tcase 0x5:\n\t\tk2 ^= uint32(tail[4]) << 0\n\t\tk2 *= c2\n\t\tk2 = (k2 << 16) | (k2 >> 16) // rotl32(k2, 16)\n\t\tk2 *= c3\n\t\th2 ^= k2\n\t\tfallthrough\n\n\tcase 0x4:\n\t\tk1 ^= uint32(tail[3]) << 24\n\t\tfallthrough\n\tcase 0x3:\n\t\tk1 ^= uint32(tail[2]) << 16\n\t\tfallthrough\n\tcase 0x2:\n\t\tk1 ^= uint32(tail[1]) << 8\n\t\tfallthrough\n\tcase 0x1:\n\t\tk1 ^= uint32(tail[0]) << 0\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17) // rotl32(k1, 15)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\t}\n\n\th1 ^= uint32(size)\n\th2 ^= uint32(size)\n\th3 ^= uint32(size)\n\th4 ^= uint32(size)\n\n\th1 = h1 + h2 + h3 + h4\n\th2 += h1\n\th3 += h1\n\th4 += h1\n\n\th1 = fmix32(h1)\n\th2 = fmix32(h2)\n\th3 = fmix32(h3)\n\th4 = fmix32(h4)\n\n\th1 = h1 + h2 + h3 + h4\n\th2 += h1\n\th3 += h1\n\th4 += h1\n\n\treturn [4]uint32{h1, h2, h3, h4}\n}", "func init() {\n\tval := make([]byte, 4)\n\tfor i := 0; i < 256; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\t// First base is the most significant digit.\n\t\t\tval[3-j] = Iton((i >> (2 * j)) & 3)\n\t\t}\n\t\tcopy(dnaFrom2bit[i][:], val)\n\t}\n}", "func CompressPubkey(x, y *big.Int) []byte {\n\treturn secp256k1.CompressPubkey(x, y)\n}", "func bzipCompress(d []byte) ([]byte, error) {\n\tvar out bytes.Buffer\n\tcmd := exec.Command(\"bzip2\", \"-c\", \"-9\")\n\tcmd.Stdin = bytes.NewBuffer(d)\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out.Bytes(), nil\n}", "func (key *PublicKey) SerializeCompressed() []byte {\n\tb := make([]byte, 0, PubKeyBytesLenCompressed)\n\tformat := pubKeyCompressed\n\tif isOdd(key.Y) {\n\t\tformat |= 0x1\n\t}\n\tb = append(b, format)\n\treturn bytes.PaddedAppend(b, 32, key.X.Bytes())\n}", "func (curve *KoblitzCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {\n\t// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl\n\tz1z1 := new(big.Int).Mul(z1, z1)\n\tz1z1.Mod(z1z1, curve.P)\n\tz2z2 := new(big.Int).Mul(z2, z2)\n\tz2z2.Mod(z2z2, curve.P)\n\n\tu1 := new(big.Int).Mul(x1, z2z2)\n\tu1.Mod(u1, curve.P)\n\tu2 := new(big.Int).Mul(x2, z1z1)\n\tu2.Mod(u2, curve.P)\n\th := new(big.Int).Sub(u2, u1)\n\tif h.Sign() == -1 {\n\t\th.Add(h, curve.P)\n\t}\n\ti := new(big.Int).Lsh(h, 1)\n\ti.Mul(i, i)\n\tj := new(big.Int).Mul(h, i)\n\n\ts1 := new(big.Int).Mul(y1, z2)\n\ts1.Mul(s1, z2z2)\n\ts1.Mod(s1, curve.P)\n\ts2 := new(big.Int).Mul(y2, z1)\n\ts2.Mul(s2, z1z1)\n\ts2.Mod(s2, curve.P)\n\tr := new(big.Int).Sub(s2, s1)\n\tif r.Sign() == -1 {\n\t\tr.Add(r, curve.P)\n\t}\n\tr.Lsh(r, 1)\n\tv := new(big.Int).Mul(u1, i)\n\n\tx3 := new(big.Int).Set(r)\n\tx3.Mul(x3, x3)\n\tx3.Sub(x3, j)\n\tx3.Sub(x3, v)\n\tx3.Sub(x3, v)\n\tx3.Mod(x3, curve.P)\n\n\ty3 := new(big.Int).Set(r)\n\tv.Sub(v, x3)\n\ty3.Mul(y3, v)\n\ts1.Mul(s1, j)\n\ts1.Lsh(s1, 1)\n\ty3.Sub(y3, s1)\n\ty3.Mod(y3, curve.P)\n\n\tz3 := new(big.Int).Add(z1, z2)\n\tz3.Mul(z3, z3)\n\tz3.Sub(z3, z1z1)\n\tif z3.Sign() == -1 {\n\t\tz3.Add(z3, curve.P)\n\t}\n\tz3.Sub(z3, z2z2)\n\tif z3.Sign() == -1 {\n\t\tz3.Add(z3, curve.P)\n\t}\n\tz3.Mul(z3, h)\n\tz3.Mod(z3, curve.P)\n\n\treturn x3, y3, z3\n}", "func (c *curve) encodePoint(x, y *mod.Int) []byte {\n\n\t// Encode the y-coordinate\n\tb, _ := y.MarshalBinary()\n\n\t// Encode the sign of the x-coordinate.\n\tif y.M.BitLen()&7 == 0 {\n\t\t// No unused bits at the top of y-coordinate encoding,\n\t\t// so we must prepend a whole byte.\n\t\tb = append(make([]byte, 1), b...)\n\t}\n\tif c.coordSign(x) != 0 {\n\t\tb[0] |= 0x80\n\t}\n\n\t// Convert to little-endian\n\treverse(b, b)\n\treturn b\n}", "func Ztoc_byte(input DSPSplitComplex, inputStride int, output []byte, outputStride int) {\n\tvar splitComplex C.DSPSplitComplex\n\tsplitComplex.realp = (*C.float)(&input.Real[0])\n\tsplitComplex.imagp = (*C.float)(&input.Imag[0])\n\tC.vDSP_ztoc(&splitComplex, C.vDSP_Stride(inputStride), (*C.DSPComplex)(unsafe.Pointer(&output[0])), C.vDSP_Stride(outputStride), C.vDSP_Length(len(output)/4/outputStride))\n}", "func PACKUSWB(mx, x operand.Op) { ctx.PACKUSWB(mx, x) }", "func compress(src []byte, dest io.Writer, level int) {\n\tcompressor, _ := flate.NewWriter(dest, level)\n\tcompressor.Write(src)\n\tcompressor.Close()\n}", "func __b64encode(out *[]byte, src *[]byte, mode int)", "func core(out *[64]byte, in *[16]byte, k *[32]byte) {\n\tj0 := uint32(0x61707865)\n\tj1 := uint32(0x3320646e)\n\tj2 := uint32(0x79622d32)\n\tj3 := uint32(0x6b206574)\n\tj4 := binary.LittleEndian.Uint32(k[0:4])\n\tj5 := binary.LittleEndian.Uint32(k[4:8])\n\tj6 := binary.LittleEndian.Uint32(k[8:12])\n\tj7 := binary.LittleEndian.Uint32(k[12:16])\n\tj8 := binary.LittleEndian.Uint32(k[16:20])\n\tj9 := binary.LittleEndian.Uint32(k[20:24])\n\tj10 := binary.LittleEndian.Uint32(k[24:28])\n\tj11 := binary.LittleEndian.Uint32(k[28:32])\n\tj12 := binary.LittleEndian.Uint32(in[0:4])\n\tj13 := binary.LittleEndian.Uint32(in[4:8])\n\tj14 := binary.LittleEndian.Uint32(in[8:12])\n\tj15 := binary.LittleEndian.Uint32(in[12:16])\n\n\tx0, x1, x2, x3, x4, x5, x6, x7 := j0, j1, j2, j3, j4, j5, j6, j7\n\tx8, x9, x10, x11, x12, x13, x14, x15 := j8, j9, j10, j11, j12, j13, j14, j15\n\n\tfor i := 0; i < rounds; i += 2 {\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 16) | (x12 >> (16))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 12) | (x4 >> (20))\n\t\tx0 += x4\n\t\tx12 ^= x0\n\t\tx12 = (x12 << 8) | (x12 >> (24))\n\t\tx8 += x12\n\t\tx4 ^= x8\n\t\tx4 = (x4 << 7) | (x4 >> (25))\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx1 += x5\n\t\tx13 ^= x1\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx9 += x13\n\t\tx5 ^= x9\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx2 += x6\n\t\tx14 ^= x2\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx10 += x14\n\t\tx6 ^= x10\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx3 += x7\n\t\tx15 ^= x3\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx11 += x15\n\t\tx7 ^= x11\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 16) | (x15 >> 16)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 12) | (x5 >> 20)\n\t\tx0 += x5\n\t\tx15 ^= x0\n\t\tx15 = (x15 << 8) | (x15 >> 24)\n\t\tx10 += x15\n\t\tx5 ^= x10\n\t\tx5 = (x5 << 7) | (x5 >> 25)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 16) | (x12 >> 16)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 12) | (x6 >> 20)\n\t\tx1 += x6\n\t\tx12 ^= x1\n\t\tx12 = (x12 << 8) | (x12 >> 24)\n\t\tx11 += x12\n\t\tx6 ^= x11\n\t\tx6 = (x6 << 7) | (x6 >> 25)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 16) | (x13 >> 16)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 12) | (x7 >> 20)\n\t\tx2 += x7\n\t\tx13 ^= x2\n\t\tx13 = (x13 << 8) | (x13 >> 24)\n\t\tx8 += x13\n\t\tx7 ^= x8\n\t\tx7 = (x7 << 7) | (x7 >> 25)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 16) | (x14 >> 16)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 12) | (x4 >> 20)\n\t\tx3 += x4\n\t\tx14 ^= x3\n\t\tx14 = (x14 << 8) | (x14 >> 24)\n\t\tx9 += x14\n\t\tx4 ^= x9\n\t\tx4 = (x4 << 7) | (x4 >> 25)\n\t}\n\n\tx0 += j0\n\tx1 += j1\n\tx2 += j2\n\tx3 += j3\n\tx4 += j4\n\tx5 += j5\n\tx6 += j6\n\tx7 += j7\n\tx8 += j8\n\tx9 += j9\n\tx10 += j10\n\tx11 += j11\n\tx12 += j12\n\tx13 += j13\n\tx14 += j14\n\tx15 += j15\n\n\tbinary.LittleEndian.PutUint32(out[0:4], x0)\n\tbinary.LittleEndian.PutUint32(out[4:8], x1)\n\tbinary.LittleEndian.PutUint32(out[8:12], x2)\n\tbinary.LittleEndian.PutUint32(out[12:16], x3)\n\tbinary.LittleEndian.PutUint32(out[16:20], x4)\n\tbinary.LittleEndian.PutUint32(out[20:24], x5)\n\tbinary.LittleEndian.PutUint32(out[24:28], x6)\n\tbinary.LittleEndian.PutUint32(out[28:32], x7)\n\tbinary.LittleEndian.PutUint32(out[32:36], x8)\n\tbinary.LittleEndian.PutUint32(out[36:40], x9)\n\tbinary.LittleEndian.PutUint32(out[40:44], x10)\n\tbinary.LittleEndian.PutUint32(out[44:48], x11)\n\tbinary.LittleEndian.PutUint32(out[48:52], x12)\n\tbinary.LittleEndian.PutUint32(out[52:56], x13)\n\tbinary.LittleEndian.PutUint32(out[56:60], x14)\n\tbinary.LittleEndian.PutUint32(out[60:64], x15)\n}", "func PMINSDm128byte(X1 []byte, X2 []byte)", "func bitsToBytes(bits []byte) []byte {\n\tn := len(bits)\n\tif n == 0 {\n\t\treturn []byte{}\n\t}\n\tfor i := (n-1)%8 + 1; i < 8; i++ {\n\t\tbits = append(bits, 0)\n\t}\n\tbytes := make([]byte, n/8)\n\tfor i, b := range bits {\n\t\tp := i / 8\n\t\tif b == 1 {\n\t\t\tbytes[p] |= byte(0x80) >> (i % 8)\n\t\t} else if b != 0 {\n\t\t\tpanic(fmt.Errorf(\"invalid bit (%d)\", i))\n\t\t}\n\t}\n\treturn bytes\n}", "func PMAXUDm128byte(X1 []byte, X2 []byte)", "func pack8(src []uint64) uint64 {\n\t_ = src[7] // eliminate multiple bounds checks\n\treturn 8<<60 |\n\t\tsrc[0] |\n\t\tsrc[1]<<7 |\n\t\tsrc[2]<<14 |\n\t\tsrc[3]<<21 |\n\t\tsrc[4]<<28 |\n\t\tsrc[5]<<35 |\n\t\tsrc[6]<<42 |\n\t\tsrc[7]<<49\n}", "func Pack(data []interface{}) []byte {\n\tbuf := new(bytes.Buffer)\n\tfor _, v := range data {\n\t\terr := binary.Write(buf, binary.BigEndian, v)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"failed packing bytes:\", err)\n\t\t}\n\t}\n\treturn buf.Bytes()\n}", "func eval(p []byte, x byte) (result byte) {\n\t// Horner's scheme\n\tfor i := 1; i <= len(p); i++ {\n\t\tresult = mul(result, x) ^ p[len(p)-i]\n\t}\n\treturn\n}", "func (s *Scratch) decompress() error {\n\tbr := &s.bits\n\tif err := br.init(s.br.unread()); err != nil {\n\t\treturn err\n\t}\n\n\tvar s1, s2 decoder\n\t// Initialize and decode first state and symbol.\n\ts1.init(br, s.decTable, s.actualTableLog)\n\ts2.init(br, s.decTable, s.actualTableLog)\n\n\t// Use temp table to avoid bound checks/append penalty.\n\tvar tmp = s.ct.tableSymbol[:256]\n\tvar off uint8\n\n\t// Main part\n\tif !s.zeroBits {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.nextFast()\n\t\t\ttmp[off+1] = s2.nextFast()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.nextFast()\n\t\t\ttmp[off+3] = s2.nextFast()\n\t\t\toff += 4\n\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.next()\n\t\t\ttmp[off+1] = s2.next()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.next()\n\t\t\ttmp[off+3] = s2.next()\n\t\t\toff += 4\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ts.Out = append(s.Out, tmp[:off]...)\n\n\t// Final bits, a bit more expensive check\n\tfor {\n\t\tif s1.finished() {\n\t\t\ts.Out = append(s.Out, s1.final(), s2.final())\n\t\t\tbreak\n\t\t}\n\t\tbr.fill()\n\t\ts.Out = append(s.Out, s1.next())\n\t\tif s2.finished() {\n\t\t\ts.Out = append(s.Out, s2.final(), s1.final())\n\t\t\tbreak\n\t\t}\n\t\ts.Out = append(s.Out, s2.next())\n\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t}\n\t}\n\treturn br.close()\n}", "func (d *Digest128) bmix128(p []byte) []byte {\n\tvar h1, h2 = d.h1, d.h2\n\n\tfor len(p) >= 16 {\n\t\tk1 := uint64(p[0]) | uint64(p[1])<<8 | uint64(p[2])<<16 | uint64(p[3])<<24 | uint64(p[4])<<32 | uint64(p[5])<<40 | uint64(p[6])<<48 | uint64(p[7])<<56\n\t\tk2 := uint64(p[8]) | uint64(p[9])<<8 | uint64(p[10])<<16 | uint64(p[11])<<24 | uint64(p[12])<<32 | uint64(p[13])<<40 | uint64(p[14])<<48 | uint64(p[15])<<56\n\t\tp = p[16:]\n\n\t\tk1 *= c1_128\n\t\tk1 = bits.RotateLeft64(k1, 31)\n\t\tk1 *= c2_128\n\t\th1 ^= k1\n\n\t\th1 = bits.RotateLeft64(h1, 27)\n\t\th1 += h2\n\t\th1 = h1*5 + 0x52dce729\n\n\t\tk2 *= c2_128\n\t\tk2 = bits.RotateLeft64(k2, 33)\n\t\tk2 *= c1_128\n\t\th2 ^= k2\n\n\t\th2 = bits.RotateLeft64(h2, 31)\n\t\th2 += h1\n\t\th2 = h2*5 + 0x38495ab5\n\t}\n\n\td.h1, d.h2 = h1, h2\n\treturn p\n}", "func convertPublicKey(pk []uint8) []uint8 {\n\tvar z = make([]uint8, 32)\n\tvar x = gf()\n\tvar a = gf()\n\tvar b = gf()\n\n\tunpack25519(x, pk)\n\n\tA(a, x, gf1)\n\tZ(b, x, gf1)\n\tinv25519(a, a)\n\tM(a, a, b)\n\n\tpack25519(z, a)\n\treturn z\n}", "func compressGZ(d []byte) ([]byte, error) {\n\tbuf := bytes.Buffer{}\n\tzw := gzip.NewWriter(&buf)\n\tif _, err := zw.Write(d); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := zw.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func compressByte(src []byte) []byte {\n\tcompressedData := new(bytes.Buffer)\n\tcompress(src, compressedData, 9)\n\treturn compressedData.Bytes()\n}", "func PMAXUWm128byte(X1 []byte, X2 []byte)", "func PMINUDm128byte(X1 []byte, X2 []byte)", "func bytesEncode(data *encryptedData) ([]byte, error) {\n\tif err := data.verify(); err != nil {\n\t\treturn nil, errors.WithMessage(err, \"encrypted data is invalid\")\n\t}\n\tcompressedKey, err := compress(data.EphemeralPublicKey)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"could not compress EphemeralPublicKey\")\n\t}\n\tencodedData := make([]byte, 1+len(data.InitializationVector)+len(compressedKey)+len(data.MessageAuthenticationCode)+len(data.Ciphertext))\n\tencodedData[0] = cipher.AES256CBC\n\tcopy(encodedData[1:], data.InitializationVector)\n\tcopy(encodedData[1+len(data.InitializationVector):], compressedKey)\n\tcopy(encodedData[1+len(data.InitializationVector)+len(compressedKey):], data.MessageAuthenticationCode)\n\tcopy(encodedData[1+len(data.InitializationVector)+len(compressedKey)+len(data.MessageAuthenticationCode):], data.Ciphertext)\n\treturn encodedData, nil\n}", "func PMINUWm128byte(X1 []byte, X2 []byte)", "func (pk *PublicKey) Unpack(buf *[PublicKeySize]byte) {\n\tvar tmp [mode2.PublicKeySize]byte\n\tcopy(tmp[:], buf[:mode2.PublicKeySize])\n\tpk.d.Unpack(&tmp)\n\tpk.e = make([]byte, ed25519.PublicKeySize)\n\tcopy(pk.e, buf[mode2.PublicKeySize:])\n}", "func encodeByteSlice(w io.Writer, bz []byte) (err error) {\n\terr = encodeVarint(w, int64(len(bz)))\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = w.Write(bz)\n\treturn\n}", "func serializeBigInt(x *big.Int) []byte {\n\txb := x.Bytes()\n\treverse(xb)\n\tfor len(xb) < EC_COORD_SIZE {\n\t\txb = append(xb, 0)\n\t}\n\treturn xb\n}", "func buildPackfileWithoutHeader(t testing.TB, blobSizes []int, key *crypto.Key, compress bool) (blobs []restic.Blob, packfile []byte) {\n\topts := []zstd.EOption{\n\t\t// Set the compression level configured.\n\t\tzstd.WithEncoderLevel(zstd.SpeedDefault),\n\t\t// Disable CRC, we have enough checks in place, makes the\n\t\t// compressed data four bytes shorter.\n\t\tzstd.WithEncoderCRC(false),\n\t\t// Set a window of 512kbyte, so we have good lookbehind for usual\n\t\t// blob sizes.\n\t\tzstd.WithWindowSize(512 * 1024),\n\t}\n\tenc, err := zstd.NewWriter(nil, opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar offset uint\n\tfor i, size := range blobSizes {\n\t\tplaintext := test.Random(800+i, size)\n\t\tid := restic.Hash(plaintext)\n\t\tuncompressedLength := uint(0)\n\t\tif compress {\n\t\t\tuncompressedLength = uint(len(plaintext))\n\t\t\tplaintext = enc.EncodeAll(plaintext, nil)\n\t\t}\n\n\t\t// we use a deterministic nonce here so the whole process is\n\t\t// deterministic, last byte is the blob index\n\t\tvar nonce = []byte{\n\t\t\t0x15, 0x98, 0xc0, 0xf7, 0xb9, 0x65, 0x97, 0x74,\n\t\t\t0x12, 0xdc, 0xd3, 0x62, 0xa9, 0x6e, 0x20, byte(i),\n\t\t}\n\n\t\tbefore := len(packfile)\n\t\tpackfile = append(packfile, nonce...)\n\t\tpackfile = key.Seal(packfile, nonce, plaintext, nil)\n\t\tafter := len(packfile)\n\n\t\tciphertextLength := after - before\n\n\t\tblobs = append(blobs, restic.Blob{\n\t\t\tBlobHandle: restic.BlobHandle{\n\t\t\t\tType: restic.DataBlob,\n\t\t\t\tID: id,\n\t\t\t},\n\t\t\tLength: uint(ciphertextLength),\n\t\t\tUncompressedLength: uncompressedLength,\n\t\t\tOffset: offset,\n\t\t})\n\n\t\toffset = uint(len(packfile))\n\t}\n\n\treturn blobs, packfile\n}", "func newCompressedPublicKey(spk types.SiaPublicKey) (cpk compressedPublicKey, _ error) {\n\tif len(spk.Key) != len(cpk.Key) {\n\t\treturn cpk, errors.New(\"newCompressedPublicKey: unsupported key length\")\n\t}\n\tif spk.Algorithm != types.SignatureEd25519 {\n\t\treturn cpk, errors.New(\"newCompressedPublicKey: unsupported signature algo\")\n\t}\n\tcopy(cpk.Key[:], spk.Key)\n\tcpk.Algorithm = signatureEd25519\n\treturn\n}" ]
[ "0.66965336", "0.6246139", "0.62374", "0.61326283", "0.6047263", "0.6035819", "0.600565", "0.5947837", "0.581165", "0.5790596", "0.56698364", "0.5654003", "0.56118", "0.53809667", "0.53785837", "0.5317318", "0.53047943", "0.5289326", "0.5251364", "0.5191273", "0.5177538", "0.51671344", "0.51470476", "0.51421565", "0.51378375", "0.5137575", "0.5137575", "0.5088681", "0.5074905", "0.5071217", "0.50551814", "0.50427866", "0.5036662", "0.50290835", "0.5019734", "0.50173885", "0.50152355", "0.5009755", "0.50062937", "0.49433365", "0.49139887", "0.49011695", "0.48997986", "0.4898822", "0.48963094", "0.4894703", "0.48727325", "0.48706964", "0.48688662", "0.48601148", "0.48545176", "0.485357", "0.48459312", "0.48441598", "0.48328733", "0.48286048", "0.48132876", "0.4812481", "0.48109624", "0.48061264", "0.47919622", "0.47870982", "0.4782766", "0.47762263", "0.4760907", "0.4759005", "0.47524372", "0.47462922", "0.47451082", "0.47440937", "0.4743307", "0.4742737", "0.4731368", "0.47251377", "0.47234184", "0.4723213", "0.47104955", "0.47052357", "0.46899265", "0.4683776", "0.4672089", "0.46714577", "0.46656564", "0.4658948", "0.46559757", "0.46285462", "0.46246868", "0.46201947", "0.46165153", "0.46139163", "0.46086764", "0.46082133", "0.46027306", "0.45998615", "0.45959717", "0.45940086", "0.458736", "0.45846152", "0.4582182", "0.45812878" ]
0.7749233
0
decompressPoly creates a polynomial based on a compressed array, using d bits per coefficients
func decompressPoly(c []byte, d int) Poly { var p Poly switch d { case 3: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { t[0] = uint16(c[id]) t[1] = uint16(c[id]) >> 3 t[2] = (uint16(c[id]) >> 6) | (uint16(c[id+1]) << 2) t[3] = uint16(c[id+1]) >> 1 t[4] = uint16(c[id+1]) >> 4 t[5] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2]) << 1) t[6] = uint16(c[id+2]) >> 2 t[7] = uint16(c[id+2]) >> 5 for j := 0; j < 8; j++ { p[8*i+j] = int16(((1 << 2) + uint32(t[j]&((1<<3)-1))*uint32(q)) >> 3) } id += 3 } case 4: for i := 0; i < n/2; i++ { p[2*i] = int16(((1 << 3) + uint32(c[i]&15)*uint32(q)) >> 4) p[2*i+1] = int16(((1 << 3) + uint32(c[i]>>4)*uint32(q)) >> 4) } case 5: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { t[0] = uint16(c[id]) t[1] = (uint16(c[id]) >> 5) | (uint16(c[id+1] << 3)) t[2] = uint16(c[id+1]) >> 2 t[3] = (uint16(c[id+1]) >> 7) | (uint16(c[id+2] << 1)) t[4] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3] << 4)) t[5] = uint16(c[id+3]) >> 1 t[6] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4] << 2)) t[7] = uint16(c[id+4]) >> 3 for j := 0; j < 8; j++ { p[8*i+j] = int16(((1 << 4) + uint32(t[j]&((1<<5)-1))*uint32(q)) >> 5) } id += 5 } case 6: var t [4]uint16 id := 0 for i := 0; i < n/4; i++ { t[0] = uint16(c[id]) t[1] = (uint16(c[id]) >> 6) | (uint16(c[id+1] << 2)) t[2] = (uint16(c[id+1]) >> 4) | (uint16(c[id+2]) << 4) t[3] = uint16(c[id+2]) >> 2 for j := 0; j < 4; j++ { p[4*i+j] = int16(((1 << 5) + uint32(t[j]&((1<<6)-1))*uint32(q)) >> 6) } id += 3 } case 10: var t [4]uint16 id := 0 for i := 0; i < n/4; i++ { t[0] = uint16(c[id]) | (uint16(c[id+1]) << 8) t[1] = (uint16(c[id+1]) >> 2) | (uint16(c[id+2]) << 6) t[2] = (uint16(c[id+2]) >> 4) | (uint16(c[id+3]) << 4) t[3] = (uint16(c[id+3]) >> 6) | (uint16(c[id+4]) << 2) for j := 0; j < 4; j++ { p[4*i+j] = int16(((1 << 9) + uint32(t[j]&((1<<10)-1))*uint32(q)) >> 10) } id += 5 } case 11: var t [8]uint16 id := 0 for i := 0; i < n/8; i++ { t[0] = uint16(c[id]) | (uint16(c[id+1]) << 8) t[1] = (uint16(c[id+1]) >> 3) | (uint16(c[id+2]) << 5) t[2] = (uint16(c[id+2]) >> 6) | (uint16(c[id+3]) << 2) | (uint16(c[id+4]) << 10) t[3] = (uint16(c[id+4]) >> 1) | (uint16(c[id+5]) << 7) t[4] = (uint16(c[id+5]) >> 4) | (uint16(c[id+6]) << 4) t[5] = (uint16(c[id+6]) >> 7) | (uint16(c[id+7]) << 1) | (uint16(c[id+8]) << 9) t[6] = (uint16(c[id+8]) >> 2) | (uint16(c[id+9]) << 6) t[7] = (uint16(c[id+9]) >> 5) | (uint16(c[id+10]) << 3) for j := 0; j < 8; j++ { p[8*i+j] = int16(((1 << 10) + uint32(t[j]&((1<<11)-1))*uint32(q)) >> 11) } id += 11 } default: panic("bad d value") } return p }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func polyCBD2(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/8; i++ {\n\t\tt = load32LE(outbuf[4*i:])\n\t\td = t & 0x55555555\n\t\td += (t >> 1) & 0x55555555\n\n\t\tfor j := 0; j < 8; j++ {\n\t\t\ta = int16((d >> (4*j + 0)) & 0x3)\n\t\t\tb = int16((d >> (4*j + 2)) & 0x3)\n\t\t\tp[8*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func polyCBD3(outbuf []byte) Poly {\n\tvar t, d uint32\n\tvar a, b int16\n\tvar p Poly\n\n\tfor i := 0; i < n/4; i++ {\n\t\tt = load24LE(outbuf[3*i:])\n\t\td = t & 0x00249249\n\t\td += (t >> 1) & 0x00249249\n\t\td += (t >> 2) & 0x00249249\n\n\t\tfor j := 0; j < 4; j++ {\n\t\t\ta = int16((d >> (6*j + 0)) & 0x7)\n\t\t\tb = int16((d >> (6*j + 3)) & 0x7)\n\t\t\tp[4*i+j] = a - b\n\t\t}\n\t}\n\treturn p\n}", "func decompress(publicKey []byte) []byte {\n\tx, y := secp256k1.DecompressPubkey(publicKey)\n\treturn elliptic.Marshal(ecies.DefaultCurve, x, y)\n}", "func (s *Scratch) decompress() error {\n\tbr := &s.bits\n\tif err := br.init(s.br.unread()); err != nil {\n\t\treturn err\n\t}\n\n\tvar s1, s2 decoder\n\t// Initialize and decode first state and symbol.\n\ts1.init(br, s.decTable, s.actualTableLog)\n\ts2.init(br, s.decTable, s.actualTableLog)\n\n\t// Use temp table to avoid bound checks/append penalty.\n\tvar tmp = s.ct.tableSymbol[:256]\n\tvar off uint8\n\n\t// Main part\n\tif !s.zeroBits {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.nextFast()\n\t\t\ttmp[off+1] = s2.nextFast()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.nextFast()\n\t\t\ttmp[off+3] = s2.nextFast()\n\t\t\toff += 4\n\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor br.off >= 8 {\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+0] = s1.next()\n\t\t\ttmp[off+1] = s2.next()\n\t\t\tbr.fillFast()\n\t\t\ttmp[off+2] = s1.next()\n\t\t\ttmp[off+3] = s2.next()\n\t\t\toff += 4\n\t\t\tif off == 0 {\n\t\t\t\ts.Out = append(s.Out, tmp...)\n\t\t\t\t// When off is 0, we have overflowed and should write.\n\t\t\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ts.Out = append(s.Out, tmp[:off]...)\n\n\t// Final bits, a bit more expensive check\n\tfor {\n\t\tif s1.finished() {\n\t\t\ts.Out = append(s.Out, s1.final(), s2.final())\n\t\t\tbreak\n\t\t}\n\t\tbr.fill()\n\t\ts.Out = append(s.Out, s1.next())\n\t\tif s2.finished() {\n\t\t\ts.Out = append(s.Out, s2.final(), s1.final())\n\t\t\tbreak\n\t\t}\n\t\ts.Out = append(s.Out, s2.next())\n\t\tif len(s.Out) >= s.DecompressLimit {\n\t\t\treturn fmt.Errorf(\"output size (%d) > DecompressLimit (%d)\", len(s.Out), s.DecompressLimit)\n\t\t}\n\t}\n\treturn br.close()\n}", "func (d *DecompressionBuffer) Decompress() []float64 {\n\tfirst := d.readFloat()\n\tresult := []float64{first}\n\n\tnumber := first\n\tfor d.hasMore() && len(result) < d.expectedSize {\n\t\tif d.ReadBit() {\n\t\t\t// Hit a 1, so we need another bit to know what to do.\n\t\t\t// Otherwise it's a repeat of the previous value.\n\t\t\tif d.ReadBit() {\n\t\t\t\t// With have full XOR + lengths\n\t\t\t\tnumber = d.readFullXOR(number)\n\t\t\t} else {\n\t\t\t\t// We have partial XOR (it has the same number of leading zeroes and length)\n\t\t\t\tnumber = d.readPartialXOR(number)\n\t\t\t}\n\t\t}\n\t\tresult = append(result, number)\n\t}\n\treturn result\n}", "func decompress(in []byte) ([]byte, error) {\n\tr, err := zlib.NewReader(bytes.NewBuffer(in))\n\tif err != nil {\n\t\treturn nil, errors.New(\"decompression failed\")\n\t}\n\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(r)\n\t//log.Printf(\"Decompressed %d bytes from %d bytes\\n\", unzippedLen, len(in))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func decompressBytes(input []byte) (output []byte, err error) {\n\tb := bytes.NewReader(input)\n\tvar r io.ReadCloser\n\n\tr, err = zlib.NewReader(b)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Close()\n\n\tbuffer := new(bytes.Buffer)\n\t_, err = buffer.ReadFrom(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput = buffer.Bytes()\n\treturn\n}", "func decompressBytes(input []byte) (output []byte, err error) {\n\tb := bytes.NewReader(input)\n\tvar r io.ReadCloser\n\n\tr, err = zlib.NewReader(b)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Close()\n\n\tbuffer := new(bytes.Buffer)\n\t_, err = buffer.ReadFrom(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toutput = buffer.Bytes()\n\treturn\n}", "func polyFromMsg(msg []byte) Poly {\n\tvar p Poly\n\tfor i := 0; i < n/8; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tmask := -int16((msg[i] >> j) & 1)\n\t\t\tp[8*i+j] = mask & int16((q+1)/2)\n\t\t}\n\t}\n\treturn p\n}", "func decompressLZ4(src io.Reader) io.Reader {\n\tpr, pw := io.Pipe()\n\tzr := lz4.NewReader(src)\n\tgo func() {\n\t\t_, err := zr.WriteTo(pw)\n\t\tpw.CloseWithError(err) // make sure the other side can see EOF or other errors\n\t}()\n\treturn pr\n\n}", "func (p *Poly) Unmarshal(buf []byte, rem int) ([]byte, int, error) {\n\tvar l, c uint32\n\tbuf, rem, err := surge.UnmarshalLen(&l, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tbuf, rem, err = surge.UnmarshalLen(&c, secp256k1.FnSize, buf, rem)\n\tif err != nil {\n\t\treturn buf, rem, err\n\t}\n\tif l == 0 {\n\t\t*p = make([]secp256k1.Fn, 0, c)\n\t\treturn buf, rem, nil\n\t}\n\tif len(*p) < int(l) || cap(*p) < int(c) {\n\t\t*p = make(Poly, l, c)\n\t} else {\n\t\t*p = (*p)[:l]\n\t}\n\tfor i := range *p {\n\t\tbuf, rem, err = (*p)[i].Unmarshal(buf, rem)\n\t\tif err != nil {\n\t\t\treturn buf, rem, err\n\t\t}\n\t}\n\treturn buf, rem, nil\n}", "func decompress(cd []byte, tracklen int) (dat []byte, err error) {\n\tfor {\n\t\tif len(cd) == 0 {\n\t\t\tbreak\n\t\t}\n\t\trunLength := int(cd[0])\n\t\tcd = cd[1:]\n\t\tdat = append(dat, cd[:runLength]...)\n\t\tcd = cd[runLength:]\n\n\t\tif len(cd) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\trunLength = int(cd[0])\n\t\trepeated := cd[1]\n\t\tcd = cd[2:]\n\t\tfor i := runLength; i > 0; i-- {\n\t\t\tdat = append(dat, repeated)\n\t\t}\n\t}\n\n\tif tracklen != len(dat) {\n\t\treturn nil, fmt.Errorf(\"qrst: decompressed data isn't a track length (%d != %d)\", tracklen, len(dat))\n\t}\n\n\treturn\n}", "func TestDecompressY(t *testing.T) {\n\ttests := []struct {\n\t\tname string // test description\n\t\tx string // hex encoded x coordinate\n\t\tvalid bool // expected decompress result\n\t\twantOddY string // hex encoded expected odd y coordinate\n\t\twantEvenY string // hex encoded expected even y coordinate\n\t}{{\n\t\tname: \"x = 0 -- not a point on the curve\",\n\t\tx: \"0\",\n\t\tvalid: false,\n\t\twantOddY: \"\",\n\t\twantEvenY: \"\",\n\t}, {\n\t\tname: \"x = 1\",\n\t\tx: \"1\",\n\t\tvalid: true,\n\t\twantOddY: \"bde70df51939b94c9c24979fa7dd04ebd9b3572da7802290438af2a681895441\",\n\t\twantEvenY: \"4218f20ae6c646b363db68605822fb14264ca8d2587fdd6fbc750d587e76a7ee\",\n\t}, {\n\t\tname: \"x = secp256k1 prime (aka 0) -- not a point on the curve\",\n\t\tx: \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\",\n\t\tvalid: false,\n\t\twantOddY: \"\",\n\t\twantEvenY: \"\",\n\t}, {\n\t\tname: \"x = secp256k1 prime - 1 -- not a point on the curve\",\n\t\tx: \"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\",\n\t\tvalid: false,\n\t\twantOddY: \"\",\n\t\twantEvenY: \"\",\n\t}, {\n\t\tname: \"x = secp256k1 group order\",\n\t\tx: \"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\",\n\t\tvalid: true,\n\t\twantOddY: \"670999be34f51e8894b9c14211c28801d9a70fde24b71d3753854b35d07c9a11\",\n\t\twantEvenY: \"98f66641cb0ae1776b463ebdee3d77fe2658f021db48e2c8ac7ab4c92f83621e\",\n\t}, {\n\t\tname: \"x = secp256k1 group order - 1 -- not a point on the curve\",\n\t\tx: \"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140\",\n\t\tvalid: false,\n\t\twantOddY: \"\",\n\t\twantEvenY: \"\",\n\t}}\n\n\tfor _, test := range tests {\n\t\t// Decompress the test odd y coordinate for the given test x coordinate\n\t\t// and ensure the returned validity flag matches the expected result.\n\t\tvar oddY fieldVal\n\t\tfx := new(fieldVal).SetHex(test.x)\n\t\tvalid := decompressY(fx, true, &oddY)\n\t\tif valid != test.valid {\n\t\t\tt.Errorf(\"%s: unexpected valid flag -- got: %v, want: %v\",\n\t\t\t\ttest.name, valid, test.valid)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Decompress the test even y coordinate for the given test x coordinate\n\t\t// and ensure the returned validity flag matches the expected result.\n\t\tvar evenY fieldVal\n\t\tvalid = decompressY(fx, false, &evenY)\n\t\tif valid != test.valid {\n\t\t\tt.Errorf(\"%s: unexpected valid flag -- got: %v, want: %v\",\n\t\t\t\ttest.name, valid, test.valid)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Skip checks related to the y coordinate when there isn't one.\n\t\tif !valid {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the decompressed odd Y coordinate is the expected value.\n\t\toddY.Normalize()\n\t\twantOddY := new(fieldVal).SetHex(test.wantOddY)\n\t\tif !wantOddY.Equals(&oddY) {\n\t\t\tt.Errorf(\"%s: mismatched odd y\\ngot: %v, want: %v\", test.name,\n\t\t\t\toddY, wantOddY)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the decompressed even Y coordinate is the expected value.\n\t\tevenY.Normalize()\n\t\twantEvenY := new(fieldVal).SetHex(test.wantEvenY)\n\t\tif !wantEvenY.Equals(&evenY) {\n\t\t\tt.Errorf(\"%s: mismatched even y\\ngot: %v, want: %v\", test.name,\n\t\t\t\tevenY, wantEvenY)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the decompressed odd y coordinate is actually odd.\n\t\tif !oddY.IsOdd() {\n\t\t\tt.Errorf(\"%s: odd y coordinate is even\", test.name)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the decompressed even y coordinate is actually even.\n\t\tif evenY.IsOdd() {\n\t\t\tt.Errorf(\"%s: even y coordinate is odd\", test.name)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func poly(i int, u []byte) byte {\n\tvar r byte = 1\n\tfor j, m := 0, len(u); j < m; j++ {\n\t\tif j != i {\n\t\t\tr = mul(r, div(u[j], add(u[j], u[i])))\n\t\t}\n\t}\n\treturn r\n}", "func Decompress(b []byte, s *Scratch) ([]byte, error) {\n\ts, err := s.prepare(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Out = s.Out[:0]\n\terr = s.readNCount()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.buildDtable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = s.decompress()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.Out, nil\n}", "func Poly(xvalues, yvalues []float64, degree int) ([]float64, error) {\n\tif len(xvalues) != len(yvalues) {\n\t\treturn nil, ErrPolyRegArraysSameLength\n\t}\n\n\tm := len(yvalues)\n\tn := degree + 1\n\ty := New(m, 1, yvalues...)\n\tx := Zero(m, n)\n\n\tfor i := 0; i < m; i++ {\n\t\tip := float64(1)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tx.Set(i, j, ip)\n\t\t\tip *= xvalues[i]\n\t\t}\n\t}\n\n\tq, r := x.QR()\n\tqty, err := q.Transpose().Times(y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := make([]float64, n)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tc[i] = qty.Get(i, 0)\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tc[i] -= c[j] * r.Get(i, j)\n\t\t}\n\t\tc[i] /= r.Get(i, i)\n\t}\n\n\treturn c, nil\n}", "func (this *DtNavMesh) DecodePolyIdPoly(ref DtPolyRef) uint32 {\n\tpolyMask := (uint32(1) << this.m_polyBits) - 1\n\treturn (uint32(ref) & polyMask)\n}", "func polyUniform(rho []byte, nonce []byte) Poly {\n\tvar outbuf [shake128Rate]byte\n\n\tstate := sha3.NewShake128()\n\tstate.Write(rho[:])\n\tstate.Write(nonce)\n\tstate.Read(outbuf[:])\n\n\tvar a Poly\n\tctr := rej(a[:], outbuf[:])\n\tfor ctr < n {\n\t\tstate.Read(outbuf[:shake128Rate])\n\t\tctr += rej(a[ctr:], outbuf[:shake128Rate])\n\t}\n\treturn a\n}", "func decompress(src io.Reader, dest io.Writer) {\n\tdecompressor := flate.NewReader(src)\n\tio.Copy(dest, decompressor)\n\tdecompressor.Close()\n}", "func NewPoly(prefix, name string, fields map[string]interface{}, tags map[string]string) *Poly {\n\tp := &Poly{\n\t\tPrefix: prefix,\n\t\tName: name,\n\t\tFields: make(map[string]interface{}),\n\t\tTags: make(map[string]string),\n\t}\n\tp.AddTags(tags)\n\tp.AddFields(fields)\n\treturn p\n}", "func (this *DtNavMesh) DecodePolyId(ref DtPolyRef, salt, it, ip *uint32) {\n\tsaltMask := (uint32(1) << this.m_saltBits) - 1\n\ttileMask := (uint32(1) << this.m_tileBits) - 1\n\tpolyMask := (uint32(1) << this.m_polyBits) - 1\n\t*salt = ((uint32(ref) >> (this.m_polyBits + this.m_tileBits)) & saltMask)\n\t*it = ((uint32(ref) >> this.m_polyBits) & tileMask)\n\t*ip = (uint32(ref) & polyMask)\n}", "func polyToMsg(p Poly) []byte {\n\tmsg := make([]byte, 32)\n\tvar t uint16\n\tvar tmp byte\n\tp.reduce()\n\tfor i := 0; i < n/8; i++ {\n\t\ttmp = 0\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tt = (((uint16(p[8*i+j]) << 1) + uint16(q/2)) / uint16(q)) & 1\n\t\t\ttmp |= byte(t << j)\n\t\t}\n\t\tmsg[i] = tmp\n\t}\n\treturn msg\n}", "func Decompress(compressed *vector.Vector) (*vector.Vector, error) {\n\tif compressed.Size() == 0 {\n\t\treturn compressed, nil\n\t}\n\n\tsize := compressed.MustGet(0).(uint16)\n\tif !isValidDictionarySize(DictionarySize(size)) {\n\t\treturn nil, fmt.Errorf(\"the data is compressed with an invalid dictionary size %d\", size)\n\t}\n\n\tdict := createInitialDecompressDictionary()\n\n\tresult := vector.New()\n\tword := vector.New()\n\n\tfor i := 1; i < compressed.Size(); i++ {\n\t\tif dict.Size() == int(size) {\n\t\t\tdict = createInitialDecompressDictionary()\n\t\t}\n\n\t\tcode := compressed.MustGet(i)\n\n\t\tentry := vector.New()\n\n\t\tif c, ok := dict.Get(code); ok {\n\t\t\tbyteVector := c.(*vector.Vector)\n\n\t\t\tentry = vector.New(uint(byteVector.Size()))\n\t\t\tfor i := 0; i < byteVector.Size(); i++ {\n\t\t\t\tentry.MustSet(i, byteVector.MustGet(i))\n\t\t\t}\n\t\t} else if int(code.(uint16)) == dict.Size() && word.Size() > 0 {\n\t\t\tentry = word.AppendToCopy(word.MustGet(0))\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%w: %d\", ErrBadCompressedCode, code)\n\t\t}\n\n\t\tfor i := 0; i < entry.Size(); i++ {\n\t\t\tresult.Append(entry.MustGet(i))\n\t\t}\n\n\t\tif word.Size() > 0 {\n\t\t\tword = word.AppendToCopy(entry.MustGet(0))\n\t\t\tdict.Set(uint16(dict.Size()), word)\n\t\t}\n\n\t\tword = entry\n\t}\n\n\treturn result, nil\n}", "func polymod(v []byte) uint64 {\n\tc := uint64(1)\n\tfor _, d := range v {\n\t\tc0 := byte(c >> 35)\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\treturn c ^ 1\n}", "func NewPolynomial(coefficients []*big.Int) (*Polynomial, error) {\n\tif len(coefficients) == 0 {\n\t\treturn nil, errors.Errorf(\"no coefficients given\")\n\t}\n\tfor i, v := range coefficients {\n\t\tif v.Sign() < 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is negative (%d)\", i, v)\n\t\t}\n\t\tif v.Cmp(bn256.Order) >= 0 {\n\t\t\treturn nil, errors.Errorf(\"coefficient %d is too big (%d)\", i, v)\n\t\t}\n\t}\n\tp := Polynomial(coefficients)\n\treturn &p, nil\n}", "func polyMod(v []uint8) uint64 {\n\tvar c uint64 = 1\n\tfor _, d := range v {\n\t\tvar c0 uint64 = c >> 35\n\t\tc = ((c & 0x07ffffffff) << 5) ^ uint64(d)\n\n\t\tif c0&0x01 != 0 {\n\t\t\tc ^= 0x98f2bc8e61\n\t\t}\n\t\tif c0&0x02 != 0 {\n\t\t\tc ^= 0x79b76d99e2\n\t\t}\n\t\tif c0&0x04 != 0 {\n\t\t\tc ^= 0xf33e5fb3c4\n\t\t}\n\t\tif c0&0x08 != 0 {\n\t\t\tc ^= 0xae2eabe2a8\n\t\t}\n\t\tif c0&0x10 != 0 {\n\t\t\tc ^= 0x1e4f43e470\n\t\t}\n\t}\n\n\treturn c ^ 1\n}", "func Decompress(b []byte) ([]byte, error) {\n\tdec := make([]byte, 0, len(b)) // estimate initial size\n\n\tfor len(b) > 0 {\n\t\tswitch b[0] {\n\t\tcase 254: // verbatim byte\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[1])\n\t\t\tb = b[2:]\n\t\tcase 255: // verbatim string\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tn := int(b[1])\n\t\t\tif len(b) < n+2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[2:n+2]...)\n\t\t\tb = b[n+2:]\n\t\tdefault: // look up encoded value\n\t\t\tdec = append(dec, codes[int(b[0])]...)\n\t\t\tb = b[1:]\n\t\t}\n\t}\n\n\treturn dec, nil\n}", "func (cpk *CompressedPublicKey) Uncompress() (*PublicKey, error) {\n\t// Should only execute the decompression branch of ParsePublicKey\n\tpk_s, err := btcec.ParsePubKey(cpk[:], S256)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newPublicKeyCoords(pk_s.X, pk_s.Y), nil\n}", "func CompressWithBitSize(src []int32, bitSize int) []byte {\n}", "func polyBaseMul(a, b Poly) Poly {\n\tvar r Poly\n\tfor i := 0; i < n/4; i++ {\n\t\tcopy(r[4*i:4*i+2], basemul(a[4*i:4*i+2], b[4*i:4*i+2], zetas[64+i]))\n\t\tcopy(r[4*i+2:4*i+4], basemul(a[4*i+2:4*i+4], b[4*i+2:4*i+4], -zetas[64+i]))\n\t}\n\treturn r\n}", "func Decompress(file *os.File, outputName string) {\n\t// Ler Árvore (Reconstruir)\n\treader := bit.NewReader(file)\n\troot := readTree(reader)\n\tif root == nil {\n\t\tpanic(\"Árvore nula!\")\n\t}\n\t// Decodificar percorrendo a arvore\n\tif root.IsLeaf() {\n\t\tnodeHelper := tree.New(\"\", nil, nil)\n\t\tnodeHelper.Left = root\n\t\troot = nodeHelper\n\t}\n\tdecodeFile(reader, outputName, root)\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte", "func (x *Xz) Decompress(in io.Reader, out io.Writer) error {\n\tr, err := fastxz.NewReader(in, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(out, r)\n\treturn err\n}", "func Decompress(input, output []byte) (outSize int, err error) {\r\n\tvar errCode C.int\r\n\toutSize = int(C.lzf_decompress(p(input), clen(input), p(output), clen(output), &errCode))\r\n\tif outSize > 0 {\r\n\t\treturn\r\n\t}\r\n\tswitch errCode {\r\n\tcase C.E2BIG:\r\n\t\terr = ErrInsufficientBuffer\r\n\tcase C.EINVAL:\r\n\t\terr = ErrDataCorruption\r\n\tdefault:\r\n\t\terr = ErrUnknown\r\n\t}\r\n\treturn\r\n}", "func Decompress(inPath string, outPath string) error {\n\t// open the input, compressed file\n\tinFile, err := os.Open(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// we open this for read only, and this process exists after a finite (short)\n\t// period of time; there's no need to throw an error if closing it fails\n\tdefer inFile.Close()\n\n\t// open output file\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// lz4 read buffer\n\tr := lz4.NewReader(inFile)\n\t// write buffer\n\tw := bufio.NewWriter(outFile)\n\n\t// 4kb chunks\n\tbuf := make([]byte, 4096)\n\tfor {\n\t\t// read a chunk\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn err\n\t\t}\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// write a chunk\n\t\tif _, err := w.Write(buf[:n]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// flush and pending data\n\tif err = w.Flush(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// make sure we successfully close the compressed file\n\tif err := outFile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func polynomialFunction(a ...float64) Y {\n\treturn func(x ...float64) float64 {\n\t\tvar y float64\n\t\tfor i, aa := range a {\n\t\t\ty += aa * math.Pow(x[0], float64(i))\n\t\t}\n\t\treturn y\n\t}\n}", "func decompressPoint(x *big.Int, ybit bool) (*big.Int, error) {\n\t// TODO: This will probably only work for secp256k1 due to\n\t// optimizations.\n\n\t// Y = +-sqrt(x^3 + B)\n\tx3 := new(big.Int).Mul(x, x)\n\tx3.Mul(x3, x)\n\tx3.Add(x3, secp256k1.Params().B)\n\tx3.Mod(x3, secp256k1.Params().P)\n\n\t// Now calculate sqrt mod p of x^3 + B\n\t// This code used to do a full sqrt based on tonelli/shanks,\n\t// but this was replaced by the algorithms referenced in\n\t// https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294\n\ty := new(big.Int).Exp(x3, secp256k1.QPlus1Div4(), secp256k1.Params().P)\n\n\tif ybit != isOdd(y) {\n\t\ty.Sub(secp256k1.Params().P, y)\n\t}\n\n\t// Check that y is a square root of x^3 + B.\n\ty2 := new(big.Int).Mul(y, y)\n\ty2.Mod(y2, secp256k1.Params().P)\n\tif y2.Cmp(x3) != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid square root\")\n\t}\n\n\t// Verify that y-coord has expected parity.\n\tif ybit != isOdd(y) {\n\t\treturn nil, fmt.Errorf(\"ybit doesn't match oddness\")\n\t}\n\n\treturn y, nil\n}", "func Decompress(proof *CommitmentProof) *CommitmentProof {\n\tcomp := proof.GetCompressed()\n\tif comp != nil {\n\t\treturn &CommitmentProof{\n\t\t\tProof: &CommitmentProof_Batch{\n\t\t\t\tBatch: decompress(comp),\n\t\t\t},\n\t\t}\n\t}\n\treturn proof\n}", "func Uncompress(data []byte) []byte {\n\tb := bytes.NewBuffer(data)\n\tr, err := zlib.NewReader(b)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tr.Close()\n\n\treturn buf\n}", "func Decompress(src []byte) []byte {\n\n\tvar i, j, r, c int\n\tvar flags uint\n\n\tsrcBuf := bytes.NewBuffer(src)\n\tdst := bytes.Buffer{}\n\n\t// ring buffer of size n, with extra f-1 bytes to aid string comparison\n\ttextBuf := make([]byte, n+f-1)\n\n\tr = n - f\n\tflags = 0\n\n\tfor {\n\t\tflags = flags >> 1\n\t\tif ((flags) & 0x100) == 0 {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc = int(bite)\n\t\t\tflags = uint(c | 0xFF00) /* uses higher byte cleverly to count eight*/\n\t\t}\n\t\tif flags&1 == 1 {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc = int(bite)\n\t\t\tdst.WriteByte(byte(c))\n\t\t\ttextBuf[r] = byte(c)\n\t\t\tr++\n\t\t\tr &= (n - 1)\n\t\t} else {\n\t\t\tbite, err := srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti = int(bite)\n\n\t\t\tbite, err = srcBuf.ReadByte()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tj = int(bite)\n\n\t\t\ti |= ((j & 0xF0) << 4)\n\t\t\tj = (j & 0x0F) + threshold\n\t\t\tfor k := 0; k <= j; k++ {\n\t\t\t\tc = int(textBuf[(i+k)&(n-1)])\n\t\t\t\tdst.WriteByte(byte(c))\n\t\t\t\ttextBuf[r] = byte(c)\n\t\t\t\tr++\n\t\t\t\tr &= (n - 1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dst.Bytes()\n}", "func Unpack(data []byte) ([]int64, error) {\n\tif len(data) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar ret []int64\n\tvar value int64\n\tvar base int64 = 1\n\tvar last int64\n\n\tr, err := zlib.NewReader(bytes.NewReader(data))\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get zlib reader\").Err()\n\t}\n\tdefer r.Close()\n\n\tdata, err = ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to read all\").Err()\n\t}\n\n\tfor _, valByte := range data {\n\t\tvalue += int64(valByte&0x7f) * base\n\t\tif valByte&0x80 > 0 {\n\t\t\tbase <<= 7\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, value+last)\n\t\tlast += value\n\t\tvalue = 0\n\t\tbase = 1\n\t}\n\n\treturn ret, nil\n}", "func (r *Registry) Decompress(alg string, data []byte) ([]byte, error) {\n\t// resolve compression algorithm\n\talgorithm, err := r.resolveAlgorithm(alg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decompress data using specified algorithm\n\tresult, err := algorithm.Decompress(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"decompression failed for alg[%s]: %s\", alg, err.Error())\n\t}\n\n\treturn result, nil\n}", "func decompress(str string, recursionLevel int) (length int) {\n\tvar index int\n\ttheMultiplierPattern := regexp.MustCompile(\"\\\\(([0-9x]*)\\\\)\")\n\n\tfor index < len(str) {\n\t\t// Search for start Character\n\t\tif str[index] == '(' {\n\t\t\t//\tlog.Printf(\"Recursion Level %v\\n\", recursionLevel)\n\n\t\t\t// extract Header info\n\t\t\ttheMultiplier := theMultiplierPattern.FindStringSubmatch(str[index:])[1]\n\t\t\tnums := strings.Split(theMultiplier, \"x\")\n\n\t\t\tcount, _ := strconv.Atoi(nums[0])\n\t\t\trepetitions, _ := strconv.Atoi(nums[1])\n\t\t\t//log.Printf(\"Multiply %v chars exactly %v times\\n\", count, repetitions)\n\n\t\t\t// find substring to process\n\t\t\trecursionStart := index + len(theMultiplier) + 2\n\t\t\trecursionString := str[recursionStart : recursionStart+count]\n\t\t\t//log.Printf(\"Now recurse substring %v\\n\", recursionString)\n\t\t\tlength += decompress(recursionString, recursionLevel+1) * repetitions\n\t\t\tindex += count + len(theMultiplier) + 2\n\t\t} else {\n\t\t\tlength++\n\t\t\tindex++\n\t\t}\n\t}\n\tcountd09Version2 = length\n\n\treturn length\n}", "func Decode_Polygon(geom []uint32) [][][][]int {\n\tpos := 0\n\tcurrentpt := []int{0, 0}\n\tnewline := [][]int{}\n\tpolygons := [][][][]int{}\n\tfor pos < len(geom) {\n\t\tgeomval := geom[pos]\n\n\t\tcmd, length := Get_Command_Length(geomval)\n\n\t\t// conde for a move to cmd\n\t\tif cmd == 1 {\n\t\t\txdelta := DecodeDelta(geom[pos+1])\n\t\t\tydelta := DecodeDelta(geom[pos+2])\n\t\t\tcurrentpt = []int{currentpt[0] + xdelta, currentpt[1] + ydelta}\n\t\t\t//fmt.Println(firstpt)\n\t\t\tpos += 2\n\n\t\t} else if cmd == 2 {\n\t\t\tnewline = [][]int{currentpt}\n\t\t\tcurrentpos := pos + 1\n\t\t\tendpos := currentpos + int(length*2)\n\t\t\tfor currentpos < endpos {\n\t\t\t\txdelta := DecodeDelta(geom[currentpos])\n\t\t\t\tydelta := DecodeDelta(geom[currentpos+1])\n\t\t\t\tcurrentpt = []int{currentpt[0] + xdelta, currentpt[1] + ydelta}\n\t\t\t\tnewline = append(newline, currentpt)\n\t\t\t\tcurrentpos += 2\n\t\t\t}\n\n\t\t\tpos = currentpos - 1\n\n\t\t} else if cmd == 7 {\n\t\t\t//newline = append(newline,newline[0])\n\t\t\tif Exterior_Ring(newline) == false {\n\t\t\t\tpolygons = append(polygons, [][][]int{newline})\n\t\t\t\tnewline = [][]int{}\n\t\t\t} else {\n\t\t\t\tif len(polygons) == 0 {\n\t\t\t\t\tpolygons = append(polygons, [][][]int{newline})\n\n\t\t\t\t} else {\n\t\t\t\t\tpolygons[len(polygons)-1] = append(polygons[len(polygons)-1], newline)\n\n\t\t\t\t}\n\t\t\t\tnewline = [][]int{}\n\t\t\t}\n\n\t\t}\n\n\t\t//fmt.Println(cmd,length)\n\t\tpos += 1\n\t}\n\n\treturn polygons\n}", "func (p thinPoly) Karatsuba4(f, g thinPoly) thinPoly {\n\tvar t = make(thinPoly, 16)\n\tvar z = make(thinPoly, 32)\n\tf0, f1 := f[:8], f[8:]\n\tg0, g1 := g[:8], g[8:]\n\n\tt.Karatsuba5(f0, g0)\n\tz.Set(t)\n\tt.Karatsuba5(f1, g1)\n\tz[8:].Inc(t.Mul(-1, t))\n\n\tp.Set(z)\n\tp[8:].Inc(z.Mul(-1, z)[:24])\n\tt.Karatsuba5(z.Add(f0, f1), z[8:].Add(g0, g1))\n\tp[8:].Inc(t)\n\n\treturn p\n}", "func compressLZ4(src io.Reader) io.Reader {\n\tpr, pw := io.Pipe()\n\tzw := lz4.NewWriter(pw)\n\tgo func() {\n\t\t_, err := zw.ReadFrom(src)\n\t\tpw.CloseWithError(err) // make sure the other side can see EOF or other errors\n\t}()\n\treturn pr\n}", "func Poly(p *sdf.Polygon, path string) error {\n\n\tvlist := p.Vertices()\n\tif vlist == nil {\n\t\treturn errors.New(\"no vertices\")\n\t}\n\n\tfmt.Printf(\"rendering %s\\n\", path)\n\td := NewDXF(path)\n\n\tfor i := 0; i < len(vlist)-1; i++ {\n\t\tp0 := vlist[i]\n\t\tp1 := vlist[i+1]\n\t\td.Line(p0, p1)\n\t}\n\n\tif p.Closed() {\n\t\tp0 := vlist[len(vlist)-1]\n\t\tp1 := vlist[0]\n\t\tif !p0.Equals(p1, tolerance) {\n\t\t\td.Line(p0, p1)\n\t\t}\n\t}\n\n\treturn d.Save()\n}", "func compress(input []int) []int {\n\tout := make([]int, len(input)/16)\n\tfor i := 0; i < len(out); i++ {\n\t\tx := 0\n\t\tfor j := 0; j < 16; j++ {\n\t\t\tx = x ^ (input[i*16+j])\n\t\t}\n\t\tout[i] = x\n\t}\n\treturn out\n}", "func (comp *Compressor) Decompress() (string, error) {\n\tdictSize := 256\n\tdictionary := make(map[byte][]byte, dictSize)\n\tfor i := 0; i < dictSize; i++ {\n\t\tdictionary[byte(i)] = []byte{byte(i)}\n\t}\n\n\tvar result strings.Builder\n\tvar word []byte\n\tfor _, k := range comp.Yield {\n\t\tvar entry []byte\n\t\tif x, ok := dictionary[k]; ok {\n\t\t\tentry = x[:len(x):len(x)]\n\t\t} else if int(k) == dictSize && len(word) > 0 {\n\t\t\tentry = append(word, word[0])\n\t\t} else {\n\t\t\treturn result.String(), UnknownSymbolError(k)\n\t\t}\n\t\tresult.Write(entry)\n\n\t\tif len(word) > 0 {\n\t\t\tword = append(word, entry[0])\n\t\t\tdictionary[byte(dictSize)] = word\n\t\t\tdictSize++\n\t\t}\n\t\tword = entry\n\t}\n\treturn result.String(), nil\n}", "func Unmarshal(curve elliptic.Curve, data []byte) (*big.Int, *big.Int)", "func Decompress(data []byte) ([]byte, error) {\n\t// Start off assuming that decompressing a buffer makes the result\n\t// larger. This is mostly but not always true.\n\tret := make([]byte, 0, len(data)*2)\n\tfor o := 0; o < len(data); o++ {\n\t\tb := data[o]\n\t\tswitch {\n\t\tcase b == 0:\n\t\t\tret = append(ret, b)\n\t\tcase (b >= 1 && b <= 8):\n\t\t\tif o+int(b)+1 > len(data) {\n\t\t\t\treturn nil, fmt.Errorf(\"copy from past end of block: %v/%v\", len(data), o+int(b)+1)\n\t\t\t}\n\t\t\td := data[o+1 : o+int(b)+1]\n\t\t\tret = append(ret, d...)\n\t\t\to += int(b)\n\t\tcase (b >= 0x09 && b <= 0x7f):\n\t\t\tret = append(ret, b)\n\t\tcase b >= 0x80 && b <= 0xbf:\n\t\t\to++\n\t\t\tm := int(b)<<8 + int(data[o])\n\t\t\tdist := (m & 0x3fff) >> 3\n\t\t\tl := m&0x07 + 3\n\t\t\tif dist > len(ret) {\n\t\t\t\tlog.Fatalf(\"dist %v, len %v but len(ret) only %v (%x)\", dist, l, len(ret), m)\n\t\t\t}\n\t\t\tif dist < 1 {\n\t\t\t\tlog.Printf(\"dist %v is less than 1\", dist)\n\t\t\t\tdist = 1\n\t\t\t}\n\t\t\tsl := len(ret)\n\t\t\tfor i := 0; i < l; i++ {\n\t\t\t\tidx := (len(ret) - dist)\n\t\t\t\tif idx < 0 || idx >= len(ret) {\n\t\t\t\t\tlog.Printf(\"Out of range; started %v, off %v, len %v, curidx %v, curlen %v\", sl, dist, l, idx, len(ret))\n\t\t\t\t}\n\t\t\t\tsb := ret[idx]\n\t\t\t\tret = append(ret, sb)\n\t\t\t}\n\t\tcase b >= 0xc0:\n\t\t\tret = append(ret, ' ')\n\t\t\tret = append(ret, b^0x80)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"unknown byte %v\", b)\n\t\t}\n\n\t}\n\n\treturn ret, nil\n}", "func Decompress(compressed *vector.Vector) (*vector.Vector, error) {\n\tif compressed.Size() == 0 {\n\t\treturn compressed, nil\n\t}\n\n\tlastByteInBits := int(compressed.MustGet(0).(byte))\n\n\tprefixTree, nextIndex := decompressPrefixTree(compressed, 1)\n\tdecompressed := vector.New()\n\n\tcodes := decompressHuffmanCodes(compressed, nextIndex, lastByteInBits)\n\n\tvar err error\n\tnextIndex = 0\n\n\tfor nextIndex < codes.Size() {\n\t\tnextIndex, err = decodeHuffmanCode(codes, nextIndex, prefixTree, decompressed)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn decompressed, nil\n}", "func compress(publicKey []byte) ([]byte, error) {\n\tif len(publicKey) == pubKeyBytesLenUncompressed-1 && publicKey[0] != compressedKeyPrefix {\n\t\tpublicKey = append([]byte{compressedKeyPrefix}, publicKey...)\n\t}\n\tif len(publicKey) != pubKeyBytesLenUncompressed {\n\t\treturn nil, errors.Errorf(\"length of uncompressed public key is invalid\")\n\t}\n\tx, y := elliptic.Unmarshal(ecies.DefaultCurve, publicKey)\n\n\treturn secp256k1.CompressPubkey(x, y), nil\n}", "func NewPolyDataMapper(nOriFeatures, iFeature, jFeature, order int) (o *PolyDataMapper) {\n\n\t// check\n\tif order < 2 {\n\t\tchk.Panic(\"PolyDataMapper is useful for order >= 2. order = %d is invalid\\n\", order)\n\t}\n\tif iFeature > nOriFeatures-1 {\n\t\tchk.Panic(\"iFeature must be within [0, %d]. iFeature = %d is invalid\\n\", nOriFeatures-1, iFeature)\n\t}\n\tif jFeature > nOriFeatures {\n\t\tchk.Panic(\"jFeature must be within [0, %d]. jFeature = %d is invalid\\n\", nOriFeatures-1, jFeature)\n\t}\n\n\t// input data\n\to = new(PolyDataMapper)\n\to.nOriFeatures = nOriFeatures\n\to.iFeature = iFeature\n\to.jFeature = jFeature\n\to.order = order\n\n\t// derived\n\tp := o.order + 1 // auxiliary\n\tnPascal := p*(p+1)/2 - 1 // -1 because first row in Pascal triangle is neglected\n\to.nExtraFeatures = nPascal - 2 // -2 because iFeature and jFeatureare were considered in nPascal already\n\treturn\n}", "func Marshal(curve elliptic.Curve, x, y *big.Int) []byte {\n\tbyteLen := (curve.Params().BitSize + 7) >> 3\n\n\tret := make([]byte, 1+byteLen)\n\tret[0] = 2 // compressed point\n\n\txBytes := x.Bytes()\n\tcopy(ret[1+byteLen-len(xBytes):], xBytes)\n\tret[0] += byte(y.Bit(0))\n\treturn ret\n}", "func Decompress(dst, src []byte) (n int, err error) {\n\tif len(src) == 0 {\n\t\treturn 0, nil\n\t}\n\tvar result C.int\n\tif len(dst) > 0 {\n\t\tresult = C.LZ4_decompress_safe(\n\t\t\t(*C.char)(unsafe.Pointer(&src[0])),\n\t\t\t(*C.char)(unsafe.Pointer(&dst[0])),\n\t\t\tC.int(len(src)),\n\t\t\tC.int(len(dst)))\n\t}\n\tif result <= 0 {\n\t\treturn 0, ErrDecompress\n\t}\n\treturn int(result), nil\n}", "func polyGetNoise(eta int, seed []byte, nonce byte) Poly {\n\toutbuf := make([]byte, eta*n/4)\n\tstate := sha3.NewShake256()\n\tstate.Write(seed[:])\n\tstate.Write([]byte{nonce})\n\tstate.Read(outbuf[:])\n\tvar p Poly\n\tif eta == 3 {\n\t\tp = polyCBD3(outbuf)\n\t}\n\tif eta == 2 {\n\t\tp = polyCBD2(outbuf)\n\t}\n\treturn p\n}", "func decompressByte(src []byte) []byte {\n\tcompressedData := bytes.NewBuffer(src)\n\tdeCompressedData := new(bytes.Buffer)\n\tdecompress(compressedData, deCompressedData)\n\treturn deCompressedData.Bytes()\n}", "func NewDecompressionBuffer(data []byte, expectedSize int) DecompressionBuffer {\n\tdbuf := DecompressionBuffer{\n\t\tdata: data,\n\t\tposition: uint32(7), // Start reading from the \"left\"\n\t\teof: false,\n\t\texpectedSize: expectedSize,\n\t}\n\n\tif len(data) <= 8 {\n\t\t//Tiny input.\n\t\tdbuf.eof = true\n\t} else {\n\t\tdbuf.current = data[8]\n\t\tdbuf.currentByteIndex = 8\n\t}\n\n\treturn dbuf\n}", "func dividePolynomial(nn []float64 , dd []float64) (q, r []float64, ok bool) {\n \n if degree(dd) < 0 {\n return\n }\n\n nnfloat := append(r, nn...)\n \n if degree(nnfloat) >= degree(dd) {\n\n q = make([]float64, degree(nnfloat)-degree(dd)+1)\n\n for degree(nnfloat) >= degree(dd) {\n d := make([]float64, degree(nnfloat)+1)\n copy(d[degree(nnfloat)-degree(dd):], dd)\n q[degree(nnfloat)-degree(dd)] = nnfloat[degree(nnfloat)] / d[degree(d)]\n for i := range d {\n d[i] *= q[degree(nnfloat)-degree(dd)]\n nnfloat[i] -= d[i]\n }\n }\n }\n\n return q, nnfloat, true\n\n}", "func (p *Pipeline) Decompress() error {\n\t// decompress the database pipeline data\n\tdata, err := decompress(p.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// overwrite compressed pipeline data with decompressed pipeline data\n\tp.Data = data\n\n\treturn nil\n}", "func Uncompress(out, in []byte) (outSize int, err error) {\n\toutSize = int(C.LZ4_decompress_safe(p(in), p(out), clen(in), clen(out)))\n\tif outSize < 0 {\n\t\terr = errors.New(\"Malformed compression stream\")\n\t}\n\treturn\n}", "func decompressHuffmanCodes(compressed *vector.Vector, index int, lastByteInBits int) *vector.Vector {\n\thuffmanCodes := vector.New(0, uint(compressed.Size()-index))\n\n\tfor i := index; i < compressed.Size(); i++ {\n\t\tcodeByte := compressed.MustGet(i).(byte)\n\n\t\ttotalBits := 7\n\t\tif i == compressed.Size()-1 {\n\t\t\ttotalBits = lastByteInBits - 1\n\t\t}\n\n\t\tfor j := totalBits; j >= 0; j-- {\n\t\t\thuffmanCodes.Append((codeByte >> j) & 1)\n\t\t}\n\t}\n\n\treturn huffmanCodes\n}", "func (s *CubicSplineSDF2) PolySpline2D(n int) (SDF2, error) {\n\tp := s.Polygonize(n)\n\treturn Polygon2D(p.Vertices())\n}", "func NewContinueDecompress(dictionarySize, maxMessageSize int) *ContinueDecompress {\n\tif dictionarySize < minDictionarySize {\n\t\tdictionarySize = minDictionarySize\n\t}\n\tif maxMessageSize < minMessageSize {\n\t\tmaxMessageSize = minMessageSize\n\t}\n\tif maxMessageSize > MaxInputSize {\n\t\tmaxMessageSize = MaxInputSize\n\t}\n\tcd := &ContinueDecompress{\n\t\tdictionarySize: dictionarySize,\n\t\tmaxMessageSize: maxMessageSize,\n\t\tlz4Stream: C.LZ4_createStreamDecode(),\n\t\tringBuffer: make([]byte, dictionarySize+maxMessageSize),\n\t}\n\truntime.SetFinalizer(cd, freeContinueDecompress)\n\treturn cd\n}", "func DecompressPubkey(pubkey []byte) (x, y *big.Int) {\n\treturn secp256k1.DecompressPubkey(pubkey)\n}", "func Decompress(header *common.Header, filename string, output string) error {\r\n\r\n\tf, err := os.Open(filename)\r\n\tdefer f.Close()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tinitOpenedZipFiles()\r\n\tdefer closeOpenedZipFiles()\r\n\r\n\tfoldersNum := len(header.Folders)\r\n\treadedFolders := 0\r\n\r\n\tfor _, folder := range header.Folders {\r\n\t\tif (folder.Flags == common.FData || folder.Flags == common.FFolder) && folder.Data == uint32(0xFFFFFFFF) {\r\n\t\t\treadedFolders++\r\n\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\terr = writeFile(output, header, &folder, nil)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tneedToRead := int64(header.Size)\r\n\treaded := int64(0)\r\n\r\n\tvar b bytes.Buffer\r\n\r\n\tr := lzma.NewReader(f)\r\n\r\n\tfor _, dataRecord := range header.Data {\r\n\t\tb.Reset()\r\n\t\tn, err := io.CopyN(&b, r, int64(dataRecord.Size))\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\treaded += n\r\n\r\n\t\tfor _, folder := range header.Folders {\r\n\t\t\tif folder.Flags == common.FData && folder.Data == uint32(dataRecord.Offset) {\r\n\t\t\t\treadedFolders++\r\n\t\t\t\terr = writeFile(output, header, &folder, b.Bytes())\r\n\t\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\t_ = r.Close()\r\n\tb.Reset()\r\n\r\n\truntime.GC()\r\n\tif readed != needToRead {\r\n\t\treturn fmt.Errorf(\"Readed: %d, Expected: %d\", readed, needToRead)\r\n\t}\r\n\r\n\treturn nil\r\n}", "func unpackArgSSFzPixmap(x [][]FzPixmap) (unpacked **C.fz_pixmap, allocs *cgoAllocMap) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\tallocs = new(cgoAllocMap)\n\tdefer runtime.SetFinalizer(&unpacked, func(***C.fz_pixmap) {\n\t\tgo allocs.Free()\n\t})\n\n\tlen0 := len(x)\n\tmem0 := allocPFzPixmapMemory(len0)\n\tallocs.Add(mem0)\n\th0 := &sliceHeader{\n\t\tData: uintptr(mem0),\n\t\tCap: len0,\n\t\tLen: len0,\n\t}\n\tv0 := *(*[]*C.fz_pixmap)(unsafe.Pointer(h0))\n\tfor i0 := range x {\n\t\tlen1 := len(x[i0])\n\t\tmem1 := allocFzPixmapMemory(len1)\n\t\tallocs.Add(mem1)\n\t\th1 := &sliceHeader{\n\t\t\tData: uintptr(mem1),\n\t\t\tCap: len1,\n\t\t\tLen: len1,\n\t\t}\n\t\tv1 := *(*[]C.fz_pixmap)(unsafe.Pointer(h1))\n\t\tfor i1 := range x[i0] {\n\t\t\tallocs1 := new(cgoAllocMap)\n\t\t\tv1[i1], allocs1 = x[i0][i1].PassValue()\n\t\t\tallocs.Borrow(allocs1)\n\t\t}\n\t\th := (*sliceHeader)(unsafe.Pointer(&v1))\n\t\tv0[i0] = (*C.fz_pixmap)(unsafe.Pointer(h.Data))\n\t}\n\th := (*sliceHeader)(unsafe.Pointer(&v0))\n\tunpacked = (**C.fz_pixmap)(unsafe.Pointer(h.Data))\n\treturn\n}", "func (encoder *encoder) DecodeInt(p interface{}, coeffs []int64) {\n\n\tencoder.DecodeRingT(p, encoder.tmpPtRt)\n\n\tencoder.ringT.NTT(encoder.tmpPtRt.value, encoder.tmpPoly)\n\n\tmodulus := int64(encoder.params.t)\n\tmodulusHalf := modulus >> 1\n\tvar value int64\n\tfor i := 0; i < encoder.ringQ.N; i++ {\n\n\t\tvalue = int64(encoder.tmpPoly.Coeffs[0][encoder.indexMatrix[i]])\n\t\tcoeffs[i] = value\n\t\tif value >= modulusHalf {\n\t\t\tcoeffs[i] -= modulus\n\t\t}\n\t}\n}", "func (c *ZLIB) Decode(encodedData []byte) ([]byte, error) {\n\tif len(encodedData) < 256 {\n\t\treturn nil, errors.New(\"Zlib.Decode: missing section header\")\n\t}\n\n\t// Check size in ZLIB section header\n\tsize := binary.LittleEndian.Uint32(\n\t\tencodedData[zlibSizeOffset : zlibSizeOffset+4],\n\t)\n\tif size != uint32(len(encodedData)-zlibSectionHeaderSize) {\n\t\treturn nil, errors.New(\"ZLIB.Decode: size mismatch\")\n\t}\n\n\t// Remove section header\n\tr, err := zlib.NewReader(\n\t\tbytes.NewBuffer(encodedData[zlibSectionHeaderSize:]),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecodedData, err := io.ReadAll(r)\n\tr.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn decodedData, nil\n}", "func unpackArgSSFzBuffer(x [][]FzBuffer) (unpacked **C.fz_buffer, allocs *cgoAllocMap) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\tallocs = new(cgoAllocMap)\n\tdefer runtime.SetFinalizer(&unpacked, func(***C.fz_buffer) {\n\t\tgo allocs.Free()\n\t})\n\n\tlen0 := len(x)\n\tmem0 := allocPFzBufferMemory(len0)\n\tallocs.Add(mem0)\n\th0 := &sliceHeader{\n\t\tData: uintptr(mem0),\n\t\tCap: len0,\n\t\tLen: len0,\n\t}\n\tv0 := *(*[]*C.fz_buffer)(unsafe.Pointer(h0))\n\tfor i0 := range x {\n\t\th := (*sliceHeader)(unsafe.Pointer(&x[i0]))\n\t\tv0[i0] = (*C.fz_buffer)(unsafe.Pointer(h.Data))\n\t}\n\th := (*sliceHeader)(unsafe.Pointer(&v0))\n\tunpacked = (**C.fz_buffer)(unsafe.Pointer(h.Data))\n\treturn\n}", "func NewDecompressor(\n\tuncompressed io.Writer, codec api.CompressionCodec, keys *enc.EEK, uncompressedBufferSize uint32,\n) (Decompressor, error) {\n\tif uncompressedBufferSize < MinBufferSize {\n\t\treturn nil, ErrBufferSizeTooSmall\n\t}\n\treturn &decompressor{\n\t\tuncompressed: uncompressed,\n\t\tinner: nil,\n\t\tcodec: codec,\n\t\tbuf: new(bytes.Buffer),\n\t\tclosed: false,\n\t\tuncompressedMAC: enc.NewHMAC(keys.HMACKey),\n\t\tuncompressedBufferSize: uncompressedBufferSize,\n\t}, nil\n}", "func Uncompress(_ *flag.FlagSet) cmdflag.Handler {\n\treturn func(args ...string) (int, error) {\n\t\tzr := lz4.NewReader(nil)\n\n\t\t// Use stdin/stdout if no file provided.\n\t\tif len(args) == 0 {\n\t\t\tzr.Reset(os.Stdin)\n\t\t\t_, err := io.Copy(os.Stdout, zr)\n\t\t\treturn 0, err\n\t\t}\n\n\t\tfor fidx, zfilename := range args {\n\t\t\t// Input file.\n\t\t\tzfile, err := os.Open(zfilename)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tzinfo, err := zfile.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tmode := zinfo.Mode() // use the same mode for the output file\n\n\t\t\t// Output file.\n\t\t\tfilename := strings.TrimSuffix(zfilename, lz4Extension)\n\t\t\tfile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, mode)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tzr.Reset(zfile)\n\n\t\t\tzfinfo, err := zfile.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tvar (\n\t\t\t\tsize int\n\t\t\t\tout io.Writer = file\n\t\t\t\tzsize = zfinfo.Size()\n\t\t\t\tbar *progressbar.ProgressBar\n\t\t\t)\n\t\t\tif zsize > 0 {\n\t\t\t\tbar = progressbar.NewOptions64(zsize,\n\t\t\t\t\t// File transfers are usually slow, make sure we display the bar at 0%.\n\t\t\t\t\tprogressbar.OptionSetRenderBlankState(true),\n\t\t\t\t\t// Display the filename.\n\t\t\t\t\tprogressbar.OptionSetDescription(filename),\n\t\t\t\t\tprogressbar.OptionClearOnFinish(),\n\t\t\t\t)\n\t\t\t\tout = io.MultiWriter(out, bar)\n\t\t\t\t_ = zr.Apply(\n\t\t\t\t\tlz4.OnBlockDoneOption(func(n int) {\n\t\t\t\t\t\tsize += n\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// Uncompress.\n\t\t\t_, err = io.Copy(out, zr)\n\t\t\tif err != nil {\n\t\t\t\treturn fidx, err\n\t\t\t}\n\t\t\tfor _, c := range []io.Closer{zfile, file} {\n\t\t\t\terr := c.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fidx, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bar != nil {\n\t\t\t\t_ = bar.Clear()\n\t\t\t\tfmt.Printf(\"%s %d\\n\", zfilename, size)\n\t\t\t}\n\t\t}\n\n\t\treturn len(args), nil\n\t}\n}", "func unpackArgSFzPixmap(x []FzPixmap) (unpacked *C.fz_pixmap, allocs *cgoAllocMap) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\tallocs = new(cgoAllocMap)\n\tdefer runtime.SetFinalizer(&unpacked, func(**C.fz_pixmap) {\n\t\tgo allocs.Free()\n\t})\n\n\tlen0 := len(x)\n\tmem0 := allocFzPixmapMemory(len0)\n\tallocs.Add(mem0)\n\th0 := &sliceHeader{\n\t\tData: uintptr(mem0),\n\t\tCap: len0,\n\t\tLen: len0,\n\t}\n\tv0 := *(*[]C.fz_pixmap)(unsafe.Pointer(h0))\n\tfor i0 := range x {\n\t\tallocs0 := new(cgoAllocMap)\n\t\tv0[i0], allocs0 = x[i0].PassValue()\n\t\tallocs.Borrow(allocs0)\n\t}\n\th := (*sliceHeader)(unsafe.Pointer(&v0))\n\tunpacked = (*C.fz_pixmap)(unsafe.Pointer(h.Data))\n\treturn\n}", "func Decompress(dst, src []byte) ([]byte, error) {\n\treturn decoder.DecodeAll(src, dst)\n}", "func Ctoz_byte(input []byte, inputStride int, output DSPSplitComplex, outputStride int) {\n\tvar splitComplex C.DSPSplitComplex\n\tsplitComplex.realp = (*C.float)(&output.Real[0])\n\tsplitComplex.imagp = (*C.float)(&output.Imag[0])\n\tn := 2 * len(output.Real) / outputStride\n\tif n2 := len(input) / (4 * inputStride); n2 < n {\n\t\tn = n2\n\t}\n\tC.vDSP_ctoz((*C.DSPComplex)(unsafe.Pointer(&input[0])), C.vDSP_Stride(inputStride), &splitComplex, C.vDSP_Stride(outputStride), C.vDSP_Length(n))\n}", "func unpackArgSSPDFObj(x [][]PDFObj) (unpacked **C.pdf_obj, allocs *cgoAllocMap) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\tallocs = new(cgoAllocMap)\n\tdefer runtime.SetFinalizer(&unpacked, func(***C.pdf_obj) {\n\t\tgo allocs.Free()\n\t})\n\n\tlen0 := len(x)\n\tmem0 := allocPPDFObjMemory(len0)\n\tallocs.Add(mem0)\n\th0 := &sliceHeader{\n\t\tData: uintptr(mem0),\n\t\tCap: len0,\n\t\tLen: len0,\n\t}\n\tv0 := *(*[]*C.pdf_obj)(unsafe.Pointer(h0))\n\tfor i0 := range x {\n\t\th := (*sliceHeader)(unsafe.Pointer(&x[i0]))\n\t\tv0[i0] = (*C.pdf_obj)(unsafe.Pointer(h.Data))\n\t}\n\th := (*sliceHeader)(unsafe.Pointer(&v0))\n\tunpacked = (**C.pdf_obj)(unsafe.Pointer(h.Data))\n\treturn\n}", "func Ddct(n int, isgn int, a []float64, ip []int, w []float64) {\n\tvar j, nw, nc int\n\tvar xr float64\n\n\tnw = ip[0]\n\tif n > (nw << 2) {\n\t\tnw = n >> 2\n\t\tmakewt(nw, ip, w)\n\t}\n\tnc = ip[1]\n\tif n > nc {\n\t\tnc = n\n\t\tmakect(nc, ip, w[nw:])\n\t}\n\tif isgn < 0 {\n\t\txr = a[n-1]\n\t\tfor j = n - 2; j >= 2; j -= 2 {\n\t\t\ta[j+1] = a[j] - a[j-1]\n\t\t\ta[j] += a[j-1]\n\t\t}\n\t\ta[1] = a[0] - xr\n\t\ta[0] += xr\n\t\tif n > 4 {\n\t\t\trftbsub(n, a, nc, w[nw:])\n\t\t\tcftbsub(n, a, ip, nw, w)\n\t\t} else if n == 4 {\n\t\t\tcftbsub(n, a, ip, nw, w)\n\t\t}\n\t}\n\tdctsub(n, a, nc, w[nw:])\n\tif isgn >= 0 {\n\t\tif n > 4 {\n\t\t\tcftfsub(n, a, ip, nw, w)\n\t\t\trftfsub(n, a, nc, w[nw:])\n\t\t} else if n == 4 {\n\t\t\tcftfsub(n, a, ip, nw, w)\n\t\t}\n\t\txr = a[0] - a[1]\n\t\ta[0] += a[1]\n\t\tfor j = 2; j < n; j += 2 {\n\t\t\ta[j-1] = a[j] - a[j+1]\n\t\t\ta[j] += a[j+1]\n\t\t}\n\t\ta[n-1] = xr\n\t}\n}", "func NewDecompressor(ct CompressionType, r io.ReadCloser) io.ReadCloser {\n\tif ct == NoCompression {\n\t\treturn r\n\t} else if ct == Snappy {\n\t\td := &Decompressor{\n\t\t\tur: r,\n\t\t\trc: snappy.NewReader(r),\n\t\t\tct: ct,\n\t\t}\n\t\treturn d\n\t} else {\n\t\tpanic(\"unknown compression type\")\n\t}\n}", "func Uncompressed() []int {\n\treturn []int{27, 28, 29, 30}\n}", "func decompress(targetDir string, tarFile string, excludeFiles []string) error {\n\treader, err := os.Open(tarFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tgzReader, err := gzip.NewReader(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer gzReader.Close()\n\n\ttarReader := tar.NewReader(gzReader)\n\tfor {\n\t\theader, err := tarReader.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif isExcluded(header.Name, excludeFiles) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttarget := path.Join(targetDir, header.Name)\n\t\tswitch header.Typeflag {\n\t\tcase tar.TypeDir:\n\t\t\terr = os.MkdirAll(target, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase tar.TypeReg:\n\t\t\tw, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = io.Copy(w, tarReader)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tw.Close()\n\t\tdefault:\n\t\t\tlog.Printf(\"Unsupported type: %v\", header.Typeflag)\n\t\t}\n\t}\n\n\treturn nil\n}", "func decodeCoords(data []byte) Coords {\n\theader := binary.LittleEndian.Uint32(data[:4])\n\tdata = data[4:4 * header]\n\tcoords := make(Coords, header)\n\tfor i := 0; i < int(4 * header); i += 4 {\n\t\tx := binary.LittleEndian.Uint16(data[i:i + 2])\n\t\ty := binary.LittleEndian.Uint16(data[i + 2:i + 4])\n\t\tcoords[i / 4][0] = float64(x)\n\t\tcoords[i / 4][1] = float64(y)\n\t}\n\treturn coords\n}", "func lookupPoly(blockSizeLength int) int {\n\tswitch (blockSizeLength * 8) {\n\tcase 64: return 0x1B;\n\tcase 128: return 0x87;\n\tcase 160: return 0x2D;\n\tcase 192: return 0x87;\n\tcase 224: return 0x309;\n\tcase 256: return 0x425;\n\tcase 320: return 0x1B;\n\tcase 384: return 0x100D;\n\tcase 448: return 0x851;\n\tcase 512: return 0x125;\n\tcase 768: return 0xA0011;\n\tcase 1024: return 0x80043;\n\tcase 2048: return 0x86001;\n }\n\treturn -1\n}", "func makeSlice(offset dvid.Point3d, size dvid.Point2d) []byte {\n\tnumBytes := size[0] * size[1] * 8\n\tslice := make([]byte, numBytes, numBytes)\n\ti := 0\n\tmodz := offset[2] % int32(len(zdata))\n\tfor y := int32(0); y < size[1]; y++ {\n\t\tsy := y + offset[1]\n\t\tmody := sy % int32(len(ydata))\n\t\tsx := offset[0]\n\t\tfor x := int32(0); x < size[0]; x++ {\n\t\t\tmodx := sx % int32(len(xdata))\n\t\t\tbinary.BigEndian.PutUint64(slice[i:i+8], xdata[modx]+ydata[mody]+zdata[modz])\n\t\t\ti += 8\n\t\t\tsx++\n\t\t}\n\t}\n\treturn slice\n}", "func CompressedTexSubImage1D(target uint32, level int32, xoffset int32, width int32, format uint32, imageSize int32, data unsafe.Pointer) {\n\tsyscall.Syscall9(gpCompressedTexSubImage1D, 7, uintptr(target), uintptr(level), uintptr(xoffset), uintptr(width), uintptr(format), uintptr(imageSize), uintptr(data), 0, 0)\n}", "func (c *Compressor) Decompress(b []byte) (image.Image, error) {\n\tr := bytes.NewBuffer(b)\n\n\tvar width, height uint32\n\tif err := binary.Read(r, encodingEndian, &width); err != nil {\n\t\treturn nil, errors.New(\"failed to read width field: \" + err.Error())\n\t}\n\tif err := binary.Read(r, encodingEndian, &height); err != nil {\n\t\treturn nil, errors.New(\"failed to read height field: \" + err.Error())\n\t}\n\n\texpander, err := readPCAExpander(r)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to read PCA expander: \" + err.Error())\n\t} else if len(expander.basis[0]) != c.blockSize*c.blockSize {\n\t\treturn nil, errors.New(\"block size mismatch\")\n\t}\n\n\tvar minValue, maxValue float64\n\tif err := binary.Read(r, encodingEndian, &minValue); err != nil {\n\t\treturn nil, errors.New(\"failed to read min value: \" + err.Error())\n\t}\n\tif err := binary.Read(r, encodingEndian, &maxValue); err != nil {\n\t\treturn nil, errors.New(\"failed to read max value: \" + err.Error())\n\t}\n\n\trect := image.Rect(0, 0, int(width), int(height))\n\tblockCount := blocker.Count(rect, c.blockSize)\n\timageBlocks := make([]linalg.Vector, blockCount)\n\tfor i := range imageBlocks {\n\t\treducedBlock := make(linalg.Vector, len(expander.basis))\n\t\tfor j := range reducedBlock {\n\t\t\tif val, err := r.ReadByte(); err != nil {\n\t\t\t\treturn nil, errors.New(\"failed to read data: \" + err.Error())\n\t\t\t} else {\n\t\t\t\tnum := ((float64(val) / 255.0) * (maxValue - minValue)) + minValue\n\t\t\t\treducedBlock[j] = num\n\t\t\t}\n\t\t}\n\t\timageBlocks[i] = expander.Expand(reducedBlock)\n\t}\n\n\treturn blocker.Image(rect.Dx(), rect.Dy(), imageBlocks, c.blockSize), nil\n}", "func (pk *PublicKey) Unpack(buf *[PublicKeySize]byte) {\n\tvar tmp [mode2.PublicKeySize]byte\n\tcopy(tmp[:], buf[:mode2.PublicKeySize])\n\tpk.d.Unpack(&tmp)\n\tpk.e = make([]byte, ed25519.PublicKeySize)\n\tcopy(pk.e, buf[mode2.PublicKeySize:])\n}", "func sm2P256PointSub(x1, y1, z1, x2, y2, z2, x3, y3, z3 *sm2P256FieldElement) {\n\tvar u1, u2, z22, z12, z23, z13, s1, s2, h, h2, r, r2, tm sm2P256FieldElement\n\ty:=sm2P256ToBig(y2)\n\tzero:=new(big.Int).SetInt64(0)\n\ty.Sub(zero,y)\n\tsm2P256FromBig(y2,y)\n\n\tif sm2P256ToBig(z1).Sign() == 0 {\n\t\tsm2P256Dup(x3, x2)\n\t\tsm2P256Dup(y3, y2)\n\t\tsm2P256Dup(z3, z2)\n\t\treturn\n\t}\n\n\tif sm2P256ToBig(z2).Sign() == 0 {\n\t\tsm2P256Dup(x3, x1)\n\t\tsm2P256Dup(y3, y1)\n\t\tsm2P256Dup(z3, z1)\n\t\treturn\n\t}\n\n\tsm2P256Square(&z12, z1) // z12 = z1 ^ 2\n\tsm2P256Square(&z22, z2) // z22 = z2 ^ 2\n\n\tsm2P256Mul(&z13, &z12, z1) // z13 = z1 ^ 3\n\tsm2P256Mul(&z23, &z22, z2) // z23 = z2 ^ 3\n\n\tsm2P256Mul(&u1, x1, &z22) // u1 = x1 * z2 ^ 2\n\tsm2P256Mul(&u2, x2, &z12) // u2 = x2 * z1 ^ 2\n\n\tsm2P256Mul(&s1, y1, &z23) // s1 = y1 * z2 ^ 3\n\tsm2P256Mul(&s2, y2, &z13) // s2 = y2 * z1 ^ 3\n\n\tif sm2P256ToBig(&u1).Cmp(sm2P256ToBig(&u2)) == 0 &&\n\t\tsm2P256ToBig(&s1).Cmp(sm2P256ToBig(&s2)) == 0 {\n\t\tsm2P256PointDouble(x1, y1, z1, x1, y1, z1)\n\t}\n\n\tsm2P256Sub(&h, &u2, &u1) // h = u2 - u1\n\tsm2P256Sub(&r, &s2, &s1) // r = s2 - s1\n\n\tsm2P256Square(&r2, &r) // r2 = r ^ 2\n\tsm2P256Square(&h2, &h) // h2 = h ^ 2\n\n\tsm2P256Mul(&tm, &h2, &h) // tm = h ^ 3\n\tsm2P256Sub(x3, &r2, &tm)\n\tsm2P256Mul(&tm, &u1, &h2)\n\tsm2P256Scalar(&tm, 2) // tm = 2 * (u1 * h ^ 2)\n\tsm2P256Sub(x3, x3, &tm) // x3 = r ^ 2 - h ^ 3 - 2 * u1 * h ^ 2\n\n\tsm2P256Mul(&tm, &u1, &h2) // tm = u1 * h ^ 2\n\tsm2P256Sub(&tm, &tm, x3) // tm = u1 * h ^ 2 - x3\n\tsm2P256Mul(y3, &r, &tm)\n\tsm2P256Mul(&tm, &h2, &h) // tm = h ^ 3\n\tsm2P256Mul(&tm, &tm, &s1) // tm = s1 * h ^ 3\n\tsm2P256Sub(y3, y3, &tm) // y3 = r * (u1 * h ^ 2 - x3) - s1 * h ^ 3\n\n\tsm2P256Mul(z3, z1, z2)\n\tsm2P256Mul(z3, z3, &h) // z3 = z1 * z3 * h\n}", "func (z PolyLineZ) read(r io.ReadSeeker) (retrec ShapeTypeI, err error) {\n\tvar rawrec struct {\n\t\tBox Box\n\t\tNumParts uint32\n\t\tNumPoints uint32\n\t}\n\terr = binary.Read(r, binary.LittleEndian, &rawrec)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`couldn't read raw poly line header: %w`, err)\n\t}\n\n\tz.Box = rawrec.Box\n\tz.NumParts = rawrec.NumParts\n\tz.NumPoints = rawrec.NumPoints\n\n\tz.Parts = make([]uint32, z.NumParts)\n\terr = binary.Read(r, binary.LittleEndian, &z.Parts)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`parts: %w`, err)\n\t}\n\n\tz.Points = make([]Point, z.NumPoints)\n\terr = binary.Read(r, binary.LittleEndian, &z.Points)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`points: %w`, err)\n\t}\n\n\terr = binary.Read(r, binary.LittleEndian, &z.ZRange)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`zrange: %w`, err)\n\t}\n\n\tz.ZArray = make([]float64, z.NumPoints)\n\terr = binary.Read(r, binary.LittleEndian, &z.ZArray)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`Z-Array: %w`, err)\n\t}\n\n\terr = binary.Read(r, binary.LittleEndian, &z.MRange)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`M Range: %w`, err)\n\t}\n\n\tz.MArray = make([]float64, z.NumPoints)\n\terr = binary.Read(r, binary.LittleEndian, &z.MArray)\n\tif err != nil {\n\t\treturn nil, xerrors.Errorf(`M-Array: %w`, err)\n\t}\n\n\treturn z, nil\n}", "func desz(src []byte, dst interface{}) error {\n\tdec := gob.NewDecoder(bytes.NewBuffer(src))\n\tif err := dec.Decode(dst); err != nil {\n\t\treturn errors.New(\"DESZ FAILED!\")\n\t}\n\treturn nil\n}", "func nextDecomposed(i *Iter) (next []byte) {\n\toutp := 0\n\tinCopyStart, outCopyStart := i.p, 0\n\tfor {\n\t\tif sz := int(i.info.size); sz <= 1 {\n\t\t\ti.rb.ss = 0\n\t\t\tp := i.p\n\t\t\ti.p++ // ASCII or illegal byte. Either way, advance by 1.\n\t\t\tif i.p >= i.rb.nsrc {\n\t\t\t\ti.setDone()\n\t\t\t\treturn i.returnSlice(p, i.p)\n\t\t\t} else if i.rb.src._byte(i.p) < utf8.RuneSelf {\n\t\t\t\ti.next = i.asciiF\n\t\t\t\treturn i.returnSlice(p, i.p)\n\t\t\t}\n\t\t\toutp++\n\t\t} else if d := i.info.Decomposition(); d != nil {\n\t\t\t// Note: If leading CCC != 0, then len(d) == 2 and last is also non-zero.\n\t\t\t// Case 1: there is a leftover to copy. In this case the decomposition\n\t\t\t// must begin with a modifier and should always be appended.\n\t\t\t// Case 2: no leftover. Simply return d if followed by a ccc == 0 value.\n\t\t\tp := outp + len(d)\n\t\t\tif outp > 0 {\n\t\t\t\ti.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)\n\t\t\t\t// TODO: this condition should not be possible, but we leave it\n\t\t\t\t// in for defensive purposes.\n\t\t\t\tif p > len(i.buf) {\n\t\t\t\t\treturn i.buf[:outp]\n\t\t\t\t}\n\t\t\t} else if i.info.multiSegment() {\n\t\t\t\t// outp must be 0 as multi-segment decompositions always\n\t\t\t\t// start a new segment.\n\t\t\t\tif i.multiSeg == nil {\n\t\t\t\t\ti.multiSeg = d\n\t\t\t\t\ti.next = nextMulti\n\t\t\t\t\treturn nextMulti(i)\n\t\t\t\t}\n\t\t\t\t// We are in the last segment. Treat as normal decomposition.\n\t\t\t\td = i.multiSeg\n\t\t\t\ti.multiSeg = nil\n\t\t\t\tp = len(d)\n\t\t\t}\n\t\t\tprevCC := i.info.tccc\n\t\t\tif i.p += sz; i.p >= i.rb.nsrc {\n\t\t\t\ti.setDone()\n\t\t\t\ti.info = Properties{} // Force BoundaryBefore to succeed.\n\t\t\t} else {\n\t\t\t\ti.info = i.rb.f.info(i.rb.src, i.p)\n\t\t\t}\n\t\t\tswitch i.rb.ss.next(i.info) {\n\t\t\tcase ssOverflow:\n\t\t\t\ti.next = nextCGJDecompose\n\t\t\t\tfallthrough\n\t\t\tcase ssStarter:\n\t\t\t\tif outp > 0 {\n\t\t\t\t\tcopy(i.buf[outp:], d)\n\t\t\t\t\treturn i.buf[:p]\n\t\t\t\t}\n\t\t\t\treturn d\n\t\t\t}\n\t\t\tcopy(i.buf[outp:], d)\n\t\t\toutp = p\n\t\t\tinCopyStart, outCopyStart = i.p, outp\n\t\t\tif i.info.ccc < prevCC {\n\t\t\t\tgoto doNorm\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if r := i.rb.src.hangul(i.p); r != 0 {\n\t\t\toutp = decomposeHangul(i.buf[:], r)\n\t\t\ti.p += hangulUTF8Size\n\t\t\tinCopyStart, outCopyStart = i.p, outp\n\t\t\tif i.p >= i.rb.nsrc {\n\t\t\t\ti.setDone()\n\t\t\t\tbreak\n\t\t\t} else if i.rb.src.hangul(i.p) != 0 {\n\t\t\t\ti.next = nextHangul\n\t\t\t\treturn i.buf[:outp]\n\t\t\t}\n\t\t} else {\n\t\t\tp := outp + sz\n\t\t\tif p > len(i.buf) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\toutp = p\n\t\t\ti.p += sz\n\t\t}\n\t\tif i.p >= i.rb.nsrc {\n\t\t\ti.setDone()\n\t\t\tbreak\n\t\t}\n\t\tprevCC := i.info.tccc\n\t\ti.info = i.rb.f.info(i.rb.src, i.p)\n\t\tif v := i.rb.ss.next(i.info); v == ssStarter {\n\t\t\tbreak\n\t\t} else if v == ssOverflow {\n\t\t\ti.next = nextCGJDecompose\n\t\t\tbreak\n\t\t}\n\t\tif i.info.ccc < prevCC {\n\t\t\tgoto doNorm\n\t\t}\n\t}\n\tif outCopyStart == 0 {\n\t\treturn i.returnSlice(inCopyStart, i.p)\n\t} else if inCopyStart < i.p {\n\t\ti.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)\n\t}\n\treturn i.buf[:outp]\ndoNorm:\n\t// Insert what we have decomposed so far in the reorderBuffer.\n\t// As we will only reorder, there will always be enough room.\n\ti.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)\n\ti.rb.insertDecomposed(i.buf[0:outp])\n\treturn doNormDecomposed(i)\n}", "func UncompressElement(scope *Scope, compressed tf.Output, output_types []tf.DataType, output_shapes []tf.Shape) (components []tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"output_types\": output_types, \"output_shapes\": output_shapes}\n\topspec := tf.OpSpec{\n\t\tType: \"UncompressElement\",\n\t\tInput: []tf.Input{\n\t\t\tcompressed,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tvar idx int\n\tvar err error\n\tif components, idx, err = makeOutputList(op, idx, \"components\"); err != nil {\n\t\tscope.UpdateErr(\"UncompressElement\", err)\n\t\treturn\n\t}\n\treturn components\n}", "func polyval(p []*big.Int, x *big.Int) *big.Int {\n\t// evaluation using Horner's method\n\tres := new(big.Int).Set(p[0]) // Q.256\n\ttmp := new(big.Int) // big.Int.Mul doesn't like when input is reused as output\n\tfor _, c := range p[1:] {\n\t\ttmp = tmp.Mul(res, x) // Q.256 * Q.256 => Q.512\n\t\tres = res.Rsh(tmp, precision) // Q.512 >> 256 => Q.256\n\t\tres = res.Add(res, c)\n\t}\n\n\treturn res\n}", "func zzUnpackCMap(packed []int) []rune {\n\tm := make([]rune, 0x110000)\n\tj := 0 // index in unpacked array\n\tassert(len(packed) == 4122)\n\n\tfor i := 0; i < 4122; i += 2 {\n\t\tcount, value := packed[i], packed[i+1]\n\t\tm[j] = rune(value)\n\t\tj++\n\t\tcount--\n\t\tfor count > 0 {\n\t\t\tm[j] = rune(value)\n\t\t\tj++\n\t\t\tcount--\n\t\t}\n\t}\n\treturn m\n}", "func PolyMpz(z []MpzT, t []TermT) TermT {\n\tcount := C.uint32_t(len(z))\n\tif count == 0 {\n\t\treturn TermT(C.yices_zero())\n\t}\n\treturn TermT(C.yices_poly_mpzp(count, (*C.mpz_t)(&z[0]), (*C.term_t)(&t[0])))\n}", "func Decompress(b AbstractBlob) AbstractBlob {\n\tif b==nil || !b.IsDirect() { return b }\n\t\n\tlzb,ok := b.(*BlobLz4Compressed)\n\tif !ok { return b }\n\t\n\tl := lzb.UCLen\n\tif l>0x7E000000 { return nil }\n\tbuf := make([]byte,l)\n\ti,e := lz4.UncompressBlock(lzb.Lz4Content,buf,0)\n\tif e!=nil { return nil }\n\tif i<l { buf = buf[:i] }\n\treturn &BlobDirect{buf}\n}", "func packSFzVertex(v []FzVertex, ptr0 *C.fz_vertex) {\n\tconst m = 0x7fffffff\n\tfor i0 := range v {\n\t\tptr1 := (*(*[m / sizeOfFzVertexValue]C.fz_vertex)(unsafe.Pointer(ptr0)))[i0]\n\t\tv[i0] = *NewFzVertexRef(unsafe.Pointer(&ptr1))\n\t}\n}", "func (curve *Curve) CompressPoint(X, Y *big.Int) (cp []byte) {\n\tby := new(big.Int).And(Y, big.NewInt(1)).Int64()\n\tbx := X.Bytes()\n\tcp = make([]byte, len(bx)+1)\n\tif by == 1 {\n\t\tcp[0] = byte(3)\n\t} else {\n\t\tcp[0] = byte(2)\n\t}\n\tcopy(cp[1:], bx)\n\n\treturn\n}", "func CompressedTextureSubImage1D(texture uint32, level int32, xoffset int32, width int32, format uint32, imageSize int32, data unsafe.Pointer) {\n\tsyscall.Syscall9(gpCompressedTextureSubImage1D, 7, uintptr(texture), uintptr(level), uintptr(xoffset), uintptr(width), uintptr(format), uintptr(imageSize), uintptr(data), 0, 0)\n}" ]
[ "0.69328", "0.6616255", "0.6591734", "0.57660264", "0.5645416", "0.5374109", "0.5363688", "0.53158724", "0.53158724", "0.52924484", "0.52727073", "0.5240977", "0.52062666", "0.51923466", "0.5136329", "0.5112102", "0.50809157", "0.506987", "0.5028679", "0.49928594", "0.49914414", "0.4976341", "0.4969049", "0.4937908", "0.4912141", "0.49080384", "0.48710677", "0.48645604", "0.4853708", "0.48249483", "0.48210448", "0.48198712", "0.480331", "0.47904062", "0.47850826", "0.47521326", "0.4745827", "0.47332275", "0.47226724", "0.47023264", "0.47002143", "0.46980596", "0.46974486", "0.46938333", "0.4693394", "0.46833596", "0.4674772", "0.46460494", "0.46400112", "0.4625336", "0.462102", "0.4615506", "0.46069914", "0.45861894", "0.4576724", "0.4566523", "0.45646214", "0.45640844", "0.45610508", "0.4543077", "0.45365527", "0.45249343", "0.4521909", "0.45117402", "0.4507731", "0.4505759", "0.45013952", "0.44912383", "0.4486018", "0.44831404", "0.4482064", "0.44706997", "0.44562882", "0.44455212", "0.44205773", "0.44139186", "0.43803313", "0.43558905", "0.43532956", "0.43511087", "0.43506274", "0.4347463", "0.4347405", "0.43424037", "0.434122", "0.43377602", "0.43339306", "0.43263328", "0.43158364", "0.43158075", "0.4309443", "0.43093556", "0.43039867", "0.430109", "0.43005124", "0.42958772", "0.42956832", "0.42930064", "0.42911634", "0.42881435" ]
0.81790996
0
////////////////////////////////////////////////////////////////////////////// Node Service // //////////////////////////////////////////////////////////////////////////////
func init() { var err error client, err = sdscontroller.GetClient("", "") if client == nil || err != nil { glog.Errorf("client init failed, %s", err.Error()) return } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *NameService) RequestNodeStatus(nodeID fred.NodeID) (kgs []fred.Item) {\n\n}", "func doNode(w http.ResponseWriter, r *http.Request) {\n\ts, err := newServerCGI(w, r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif s.NodeManager.ListLen() > 0 {\n\t\tfmt.Fprintln(w, s.NodeManager.GetNodestrSliceInTable(\"\")[0])\n\t} else {\n\t\tfmt.Fprintln(w, s.InitNode.GetData()[0])\n\t}\n}", "func NodeInitStatus(w http.ResponseWriter, r *http.Request) {\n\n}", "func name_node(message nn_proto.Propuesta){\n\tvar conn *grpc.ClientConn\n\tconn, err := grpc.Dial(\"dist13:9000\", grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"could not connect: %s\", err)\n\t}\n\tdefer conn.Close()\n\n\tc := nn_proto.NewHelloworldServiceClient(conn)\n\n\tresponse, err := c.EnviarPropuesta(context.Background(), &message)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error when calling EnviarPropuesta: %s\", err)\n\t}\n\tmsgenviados = msgenviados + 1\n\tmessagedn := dn_proto.PropRequest{\n\t\tCantidadn1: response.Cantidadn1,\n\t\tCantidadn2: response.Cantidadn2,\n\t\tCantidadn3: response.Cantidadn3,\n\t\tNombrel: response.Nombrel,\n\t\tCantidadtotal: response.Cantidadtotal,\n\t}\n\tif response.Nombrel == \"Propuesta aceptada\" {\n\t\tmessagedn = dn_proto.PropRequest{\n\t\t\tCantidadn1: message.Cantidadn1,\n\t\t\tCantidadn2: message.Cantidadn2,\n\t\t\tCantidadn3: message.Cantidadn3,\n\t\t\tNombrel: message.Nombrel,\n\t\t\tCantidadtotal: message.Cantidadtotal,\n\t\t}\n\t}\n\tvar maquina string = \"\"\n\tif message.Cantidadn1 != \"0\"{\n\t\tmaquina = \"dist14:9001\"\n\t\tconectardn(maquina, messagedn)\n\t}\n\tif message.Cantidadn3 != \"0\"{\n\t\tmaquina = \"dist16:9003\"\n\t\tconectardn(maquina, messagedn)\n\t}\n\tdescargarlocal(messagedn)\n}", "func nodeHandler(w http.ResponseWriter, r *http.Request, gos *Gossiper) {\n\t// If GET send the peers in json format\n\tif r.Method == \"GET\" {\n\t\tgos.mutexs.peersMutex.Lock()\n\t\tpeers := NodesResponse{gos.peers}\n\t\tgos.mutexs.peersMutex.Unlock()\n\n\t\tjs, err := json.Marshal(peers)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(js)\n\n\t\t// If POST get the ID and if it's new add it to the list of peers of the gossiper and send 200\n\t} else if r.Method == \"POST\" {\n\t\treqBody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\taddr := string(reqBody)\n\n\t\t// If peer is new add it to the gossiper's peerster list\n\t\tgos.mutexs.peersMutex.Lock()\n\t\tif !strings.Contains(gos.peers, addr) {\n\t\t\tif gos.peers == \"\" {\n\t\t\t\tgos.peers = addr\n\t\t\t} else {\n\t\t\t\tauxPeers := strings.Split(gos.peers, \",\")\n\t\t\t\tauxPeers = append(auxPeers, addr)\n\t\t\t\tgos.peers = strings.Join(auxPeers, \",\")\n\t\t\t}\n\t\t}\n\t\tgos.mutexs.peersMutex.Unlock()\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"200 OK\"))\n\n\t}\n}", "func listenNodeRPCs() {\n\tkvNode := rpc.NewServer()\n\tkv := new(KVNode)\n\tkvNode.Register(kv)\n\tl, err := net.Listen(\"tcp\", listenKVNodeIpPort)\n\tcheckError(\"Error in listenNodeRPCs(), net.Listen()\", err, true)\n\tfmt.Println(\"Listening for node RPC calls on:\", listenKVNodeIpPort)\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tcheckError(\"Error in listenNodeRPCs(), l.Accept()\", err, true)\n\t\tgo kvNode.ServeConn(conn)\n\t}\n}", "func newServiceNode(port int, httpport int, wsport int, modules ...string) (*node.Node, error) {\n\tcfg := &node.DefaultConfig\n\tcfg.P2P.ListenAddr = fmt.Sprintf(\":%d\", port)\n\tcfg.P2P.EnableMsgEvents = true\n\tcfg.P2P.NoDiscovery = true\n\tcfg.IPCPath = ipcpath\n\tcfg.DataDir = fmt.Sprintf(\"%s%d\", datadirPrefix, port)\n\tif httpport > 0 {\n\t\tcfg.HTTPHost = node.DefaultHTTPHost\n\t\tcfg.HTTPPort = httpport\n\t}\n\tif wsport > 0 {\n\t\tcfg.WSHost = node.DefaultWSHost\n\t\tcfg.WSPort = wsport\n\t\tcfg.WSOrigins = []string{\"*\"}\n\t\tfor i := 0; i < len(modules); i++ {\n\t\t\tcfg.WSModules = append(cfg.WSModules, modules[i])\n\t\t}\n\t}\n\tstack, err := node.New(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ServiceNode create fail: %v\", err)\n\t}\n\treturn stack, nil\n}", "func (a API) Node(cmd *btcjson.NodeCmd) (e error) {\n\tRPCHandlers[\"node\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (r *NodeReconciler) specNodeService(svc *corev1.Service, node *ethereumv1alpha1.Node) {\n\tlabels := node.GetLabels()\n\tclient := node.Spec.Client\n\n\tsvc.ObjectMeta.Labels = labels\n\tsvc.Spec.Ports = []corev1.ServicePort{\n\t\t{\n\t\t\tName: \"discovery\",\n\t\t\tPort: int32(node.Spec.P2PPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.P2PPort)),\n\t\t\tProtocol: corev1.ProtocolUDP,\n\t\t},\n\t\t{\n\t\t\tName: \"p2p\",\n\t\t\tPort: int32(node.Spec.P2PPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.P2PPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t},\n\t}\n\n\tif node.Spec.RPCPort != 0 {\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"json-rpc\",\n\t\t\tPort: int32(node.Spec.RPCPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.RPCPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tif node.Spec.WSPort != 0 {\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"ws\",\n\t\t\tPort: int32(node.Spec.WSPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.WSPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tif node.Spec.GraphQLPort != 0 {\n\t\ttargetPort := node.Spec.GraphQLPort\n\t\tif client == ethereumv1alpha1.GethClient {\n\t\t\ttargetPort = node.Spec.RPCPort\n\t\t}\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"graphql\",\n\t\t\tPort: int32(node.Spec.GraphQLPort),\n\t\t\tTargetPort: intstr.FromInt(int(targetPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tsvc.Spec.Selector = labels\n}", "func (r *NetworkReconciler) specNodeService(svc *corev1.Service, node *ethereumv1alpha1.Node, network *ethereumv1alpha1.Network) {\n\tlabels := node.Labels(network.Name)\n\tclient := node.Client\n\n\tsvc.ObjectMeta.Labels = labels\n\tsvc.Spec.Ports = []corev1.ServicePort{\n\t\t{\n\t\t\tName: \"discovery\",\n\t\t\tPort: int32(node.P2PPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.P2PPort)),\n\t\t\tProtocol: corev1.ProtocolUDP,\n\t\t},\n\t\t{\n\t\t\tName: \"p2p\",\n\t\t\tPort: int32(node.P2PPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.P2PPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t},\n\t}\n\n\tif node.RPCPort != 0 {\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"json-rpc\",\n\t\t\tPort: int32(node.RPCPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.RPCPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tif node.WSPort != 0 {\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"ws\",\n\t\t\tPort: int32(node.WSPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.WSPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tif node.GraphQLPort != 0 {\n\t\ttargetPort := node.GraphQLPort\n\t\tif client == ethereumv1alpha1.GethClient {\n\t\t\ttargetPort = node.RPCPort\n\t\t}\n\t\tsvc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{\n\t\t\tName: \"graphql\",\n\t\t\tPort: int32(node.GraphQLPort),\n\t\t\tTargetPort: intstr.FromInt(int(targetPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t})\n\t}\n\n\tsvc.Spec.Selector = labels\n}", "func GetAllServers(nodeuuid string)(data map[string]map[string]string, err error){\n err = ndb.GetTokenByUuid(nodeuuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return nil,err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(nodeuuid)\n if err != nil {\n logs.Error(\"GetAllServers ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return nil,err\n }\n data, err = nodeclient.GetAllServers(ipuuid,portuuid)\n if err != nil {\n logs.Error(\"node/GetAllServers ERROR http data request: \"+err.Error())\n return nil, err\n }\n return data,nil\n}", "func doStart(server common.Server, cfg *config.Config) (err error) {\n\tdebug.SetMaxThreads(20000)\n\n\ts, ok := server.(*DataNode)\n\tif !ok {\n\t\treturn errors.New(\"Invalid Node Type!\")\n\t}\n\n\ts.stopC = make(chan bool, 0)\n\n\t// parse the config file\n\tif err = s.parseConfig(cfg); err != nil {\n\t\treturn\n\t}\n\n\texporter.Init(ModuleName, cfg)\n\ts.registerMetrics()\n\ts.register(cfg)\n\n\t//parse the smux config\n\tif err = s.parseSmuxConfig(cfg); err != nil {\n\t\treturn\n\t}\n\t//connection pool must be created before initSpaceManager\n\ts.initConnPool()\n\n\t// init limit\n\tinitRepairLimit(s, cfg)\n\n\t// start the raft server\n\tif err = s.startRaftServer(cfg); err != nil {\n\t\treturn\n\t}\n\n\t// create space manager (disk, partition, etc.)\n\tif err = s.startSpaceManager(cfg); err != nil {\n\t\treturn\n\t}\n\n\t// check local partition compare with master ,if lack,then not start\n\tif err = s.checkLocalPartitionMatchWithMaster(); err != nil {\n\t\tlog.LogError(err)\n\t\texporter.Warning(err.Error())\n\t\treturn\n\t}\n\n\t// tcp listening & tcp connection pool\n\tif err = s.startTCPService(); err != nil {\n\t\treturn\n\t}\n\n\t//smux listening & smux connection pool\n\tif err = s.startSmuxService(cfg); err != nil {\n\t\treturn\n\t}\n\n\tgo s.registerHandler()\n\n\tgo s.startUpdateNodeInfo()\n\n\treturn\n}", "func (n *nodeImpl) Node(args ...string) error {\n\treturn n.command(n.getNodePath(), args...)\n}", "func (p *Plain_node) listen() {\n\tl, err := net.Listen(\"tcp\", p.IP+\":\"+p.Port_string)\n\n\tif err != nil {\n\t\teprint(err)\n\t\treturn\n\t}\n\n\tdefer l.Close()\n\n\tfmt.Println(DHT_PREFIX+\"Start Listening on [\"+p.IP+\":\"+p.Port_string+\"]\")\n\n\t// add self information to the map\n\tp.NList[p.IP+\":\"+p.Port_string] = p.ID\n\n\t// server start and ready for receiving msgs.\n\tfor {\n\t\tconn, err := l.Accept()\n\n\t\tfmt.Println(DHT_PREFIX+\"Incoming connection from \"+conn.RemoteAddr().String())\n\n\t\tif err != nil {\n\t\t\teprint(err)\n\t\t\tconn.Close()\n\t\t}\n\t\tgo p.handleRequest(conn)\n\t}\n}", "func SyncNode(endpoint string){\n\tfmt.Println(\"Syncing node : \" + endpoint)\n\tbody, err := json.Marshal(m)\n\tif err == nil {\n\t\trs, err := http.Post(endpoint + \"/syncall\", \"application/json\", bytes.NewBuffer(body))\n\t\tif rs == nil{\n\t\t\tpanic(\"something went wrong\")\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\t\tpanic(err)\n\t\t}\n\t}else{\n\t\tfmt.Println(\"Error\", err)\n\t}\n}", "func NodeList(nodeGet *wwapiv1.GetNodeList) (nodeList wwapiv1.NodeList, err error) {\n\t// nil is okay for nodeNames\n\tnodeDB, err := node.New()\n\tif err != nil {\n\t\treturn\n\t}\n\tnodes, err := nodeDB.FindAllNodes()\n\tif err != nil {\n\t\treturn\n\t}\n\tnodeGet.Nodes = hostlist.Expand(nodeGet.Nodes)\n\tsort.Strings(nodeGet.Nodes)\n\tif nodeGet.Type == wwapiv1.GetNodeList_Simple {\n\t\tnodeList.Output = append(nodeList.Output,\n\t\t\tfmt.Sprintf(\"%-22s %-26s %s\", \"NODE NAME\", \"PROFILES\", \"NETWORK\"))\n\t\tnodeList.Output = append(nodeList.Output, (strings.Repeat(\"=\", 80)))\n\t\tfor _, n := range node.FilterByName(nodes, nodeGet.Nodes) {\n\t\t\tvar netNames []string\n\t\t\tfor k := range n.NetDevs {\n\t\t\t\tnetNames = append(netNames, k)\n\t\t\t}\n\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\tfmt.Sprintf(\"%-22s %-26s %s\", n.Id.Print(), n.Profiles.Print(), strings.Join(netNames, \", \")))\n\t\t}\n\t} else if nodeGet.Type == wwapiv1.GetNodeList_Network {\n\t\tnodeList.Output = append(nodeList.Output,\n\t\t\tfmt.Sprintf(\"%-22s %-8s %-18s %-15s %-15s %-15s\", \"NODE NAME\", \"NAME\", \"HWADDR\", \"IPADDR\", \"GATEWAY\", \"DEVICE\"),\n\t\t\tstrings.Repeat(\"=\", 90))\n\t\tfor _, n := range node.FilterByName(nodes, nodeGet.Nodes) {\n\t\t\tif len(n.NetDevs) > 0 {\n\t\t\t\tfor name := range n.NetDevs {\n\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\tfmt.Sprintf(\"%-22s %-8s %-18s %-15s %-15s %-15s\", n.Id.Print(), name,\n\t\t\t\t\t\t\tn.NetDevs[name].Hwaddr.Print(),\n\t\t\t\t\t\t\tn.NetDevs[name].Ipaddr.Print(),\n\t\t\t\t\t\t\tn.NetDevs[name].Gateway.Print(),\n\t\t\t\t\t\t\tn.NetDevs[name].Device.Print()))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%-22s %-6s %-18s %-15s %-15s\", n.Id.Print(), \"--\", \"--\", \"--\", \"--\")\n\t\t\t}\n\t\t}\n\t} else if nodeGet.Type == wwapiv1.GetNodeList_Ipmi {\n\t\tnodeList.Output = append(nodeList.Output,\n\t\t\tfmt.Sprintf(\"%-22s %-16s %-10s %-20s %-14s\", \"NODE NAME\", \"IPMI IPADDR\", \"IPMI PORT\", \"IPMI USERNAME\", \"IPMI INTERFACE\"),\n\t\t\tstrings.Repeat(\"=\", 98))\n\t\tfor _, n := range node.FilterByName(nodes, nodeGet.Nodes) {\n\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\tfmt.Sprintf(\"%-22s %-16s %-10s %-20s %-14s\", n.Id.Print(),\n\t\t\t\t\tn.Ipmi.Ipaddr.Print(),\n\t\t\t\t\tn.Ipmi.Port.Print(),\n\t\t\t\t\tn.Ipmi.UserName.Print(),\n\t\t\t\t\tn.Ipmi.Interface.Print()))\n\t\t}\n\t} else if nodeGet.Type == wwapiv1.GetNodeList_Long {\n\t\tnodeList.Output = append(nodeList.Output,\n\t\t\tfmt.Sprintf(\"%-22s %-16s %-16s %s\", \"NODE NAME\", \"KERNEL OVERRIDE\", \"CONTAINER\", \"OVERLAYS (S/R)\"),\n\t\t\tstrings.Repeat(\"=\", 85))\n\t\tfor _, n := range node.FilterByName(nodes, nodeGet.Nodes) {\n\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\tfmt.Sprintf(\"%-22s %-16s %-16s %s\", n.Id.Print(),\n\t\t\t\t\tn.Kernel.Override.Print(),\n\t\t\t\t\tn.ContainerName.Print(),\n\t\t\t\t\tn.SystemOverlay.Print()+\"/\"+n.RuntimeOverlay.Print()))\n\t\t}\n\t} else if nodeGet.Type == wwapiv1.GetNodeList_All {\n\t\tfor _, n := range node.FilterByName(nodes, nodeGet.Nodes) {\n\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", \"NODE\", \"FIELD\", \"PROFILE\", \"VALUE\"), strings.Repeat(\"=\", 85))\n\t\t\tnType := reflect.TypeOf(n)\n\t\t\tnVal := reflect.ValueOf(n)\n\t\t\tnConfType := reflect.TypeOf(node.NodeConf{})\n\t\t\tfor i := 0; i < nType.NumField(); i++ {\n\t\t\t\tvar fieldName, fieldSource, fieldVal string\n\t\t\t\tnConfField, ok := nConfType.FieldByName(nType.Field(i).Name)\n\t\t\t\tif ok {\n\t\t\t\t\tfieldName = nConfField.Tag.Get(\"lopt\")\n\t\t\t\t} else {\n\t\t\t\t\tfieldName = nType.Field(i).Name\n\t\t\t\t}\n\t\t\t\tif nType.Field(i).Type == reflect.TypeOf(node.Entry{}) {\n\t\t\t\t\tentr := nVal.Field(i).Interface().(node.Entry)\n\t\t\t\t\tfieldSource = entr.Source()\n\t\t\t\t\tfieldVal = entr.Print()\n\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), fieldName, fieldSource, fieldVal))\n\t\t\t\t} else if nType.Field(i).Type == reflect.TypeOf(map[string]*node.Entry{}) {\n\t\t\t\t\tentrMap := nVal.Field(i).Interface().(map[string]*node.Entry)\n\t\t\t\t\tfor key, val := range entrMap {\n\t\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), key, val.Source(), val.Print()))\n\t\t\t\t\t}\n\t\t\t\t} else if nType.Field(i).Type == reflect.TypeOf(map[string]*node.NetDevEntry{}) {\n\t\t\t\t\tnetDevs := nVal.Field(i).Interface().(map[string]*node.NetDevEntry)\n\t\t\t\t\tfor netName, netWork := range netDevs {\n\t\t\t\t\t\tnetInfoType := reflect.TypeOf(*netWork)\n\t\t\t\t\t\tnetInfoVal := reflect.ValueOf(*netWork)\n\t\t\t\t\t\tnetConfType := reflect.TypeOf(node.NetDevs{})\n\t\t\t\t\t\tfor j := 0; j < netInfoType.NumField(); j++ {\n\t\t\t\t\t\t\tnetConfField, ok := netConfType.FieldByName(netInfoType.Field(j).Name)\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\tif netConfField.Tag.Get(\"lopt\") != \"nettagadd\" {\n\t\t\t\t\t\t\t\t\tfieldName = netName + \":\" + netConfField.Tag.Get(\"lopt\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tfieldName = netName + \":tag\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfieldName = netName + \":\" + netInfoType.Field(j).Name\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif netInfoType.Field(j).Type == reflect.TypeOf(node.Entry{}) {\n\t\t\t\t\t\t\t\tentr := netInfoVal.Field(j).Interface().(node.Entry)\n\t\t\t\t\t\t\t\tfieldSource = entr.Source()\n\t\t\t\t\t\t\t\tfieldVal = entr.Print()\n\t\t\t\t\t\t\t\t// only print fields with lopt\n\t\t\t\t\t\t\t\tif netConfField.Tag.Get(\"lopt\") != \"\" {\n\t\t\t\t\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), fieldName, fieldSource, fieldVal))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if netInfoType.Field(j).Type == reflect.TypeOf(map[string]*node.Entry{}) {\n\t\t\t\t\t\t\t\tfor key, val := range netInfoVal.Field(j).Interface().(map[string]*node.Entry) {\n\t\t\t\t\t\t\t\t\tkeyfieldName := fieldName + \":\" + key\n\t\t\t\t\t\t\t\t\tfieldSource = val.Source()\n\t\t\t\t\t\t\t\t\tfieldVal = val.Print()\n\t\t\t\t\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), keyfieldName, fieldSource, fieldVal))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if nType.Field(i).Type.Kind() == reflect.Ptr {\n\t\t\t\t\tnestInfoType := reflect.TypeOf(nVal.Field(i).Interface())\n\t\t\t\t\tnestInfoVal := reflect.ValueOf(nVal.Field(i).Interface())\n\t\t\t\t\t// nestConfType := reflect.TypeOf(nConfField.Type.Elem().FieldByName())\n\t\t\t\t\tfor j := 0; j < nestInfoType.Elem().NumField(); j++ {\n\t\t\t\t\t\tnestConfField, ok := nConfField.Type.Elem().FieldByName(nestInfoType.Elem().Field(j).Name)\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tfieldName = nestConfField.Tag.Get(\"lopt\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfieldName = nestInfoType.Elem().Field(j).Name\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif nestInfoType.Elem().Field(j).Type == reflect.TypeOf(node.Entry{}) {\n\t\t\t\t\t\t\tentr := nestInfoVal.Elem().Field(j).Interface().(node.Entry)\n\t\t\t\t\t\t\tfieldSource = entr.Source()\n\t\t\t\t\t\t\tfieldVal = entr.Print()\n\t\t\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), fieldName, fieldSource, fieldVal))\n\t\t\t\t\t\t} else if nestInfoType.Elem().Field(j).Type == reflect.TypeOf(map[string]*node.Entry{}) {\n\t\t\t\t\t\t\tfor key, val := range nestInfoVal.Elem().Field(j).Interface().(map[string]*node.Entry) {\n\t\t\t\t\t\t\t\tfieldName = fieldName + \":\" + key\n\t\t\t\t\t\t\t\tfieldSource = val.Source()\n\t\t\t\t\t\t\t\tfieldVal = val.Print()\n\t\t\t\t\t\t\t\tnodeList.Output = append(nodeList.Output,\n\t\t\t\t\t\t\t\t\tfmt.Sprintf(\"%-20s %-18s %-12s %s\", n.Id.Print(), fieldName, fieldSource, fieldVal))\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\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}", "func ctlNodeStart(c *cli.Context) error {\n\tctx, ctxCancel := context.WithCancel(context.Background())\n\tdefer ctxCancel()\n\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"expected 1 argument with id of node to start\")\n\t}\n\n\tnodeId := args[0]\n\tclient := control.NewControlServiceClient(cliApiConn)\n\tresp, err := client.StartNode(ctx, &control.StartNodeRequest{NodeId: nodeId})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Started node\\n\\t/p2p/%s\\n\", resp.GetNodePeerId())\n\n\tif len(resp.GetNodeListenAddrs()) > 0 {\n\t\tfmt.Printf(control.NodeListenResponseString(control.NodeListenResponse(resp)))\n\t}\n\n\treturn nil\n}", "func main() {\n\trouter := mux.NewRouter()\n\t\n\t//initial nodes can be added form the command line \n\tif len(os.Args) > 1 {\n\t\tnodeEndpoints := strings.Split(os.Args[1], \",\")\n\t\tfor ind, node := range nodeEndpoints {\n\t\t\tcounternodes[node] = strconv.Itoa(ind) \n\t\t}\n\t} \n\n\n\tfmt.Println(\"master node started on : 8000\")\n\trouter.HandleFunc(\"/items\", UpdateCount).Methods(\"POST\")\n\trouter.HandleFunc(\"/items/{id}/count\", GetCount).Methods(\"GET\")\n\trouter.HandleFunc(\"/ping\", CheckStatus).Methods(\"GET\")\n\trouter.HandleFunc(\"/addnode\", AddCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/removenode\", RemoveCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/syncnode/{nodeid}\", SyncCounterNode).Methods(\"POST\")\n\tlog.Fatal(http.ListenAndServe(\":8000\", router))\n}", "func findServiceNode(data proto.FindServiceParams) (interface{}, *nprotoo.Error) {\n\tservice := data.Service\n\tmid := data.MID\n\trid := data.RID\n\n\tif mid != \"\" {\n\t\tmkey := proto.MediaInfo{\n\t\t\tDC: dc,\n\t\t\tRID: rid,\n\t\t}.BuildKey()\n\t\tlog.Infof(\"Find mids by mkey %s\", mkey)\n\t\tfor _, key := range redis.Keys(mkey + \"*\") {\n\t\t\tlog.Infof(\"Got: key => %s\", key)\n\t\t\tminfo, err := proto.ParseMediaInfo(key)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfor _, node := range services {\n\t\t\t\tname := node.Info[\"name\"]\n\t\t\t\tid := node.Info[\"id\"]\n\t\t\t\tif service == node.Info[\"service\"] && minfo.NID == id {\n\t\t\t\t\trpcID := discovery.GetRPCChannel(node)\n\t\t\t\t\teventID := discovery.GetEventChannel(node)\n\t\t\t\t\tresp := proto.GetSFURPCParams{Name: name, RPCID: rpcID, EventID: eventID, Service: service, ID: id}\n\t\t\t\t\tlog.Infof(\"findServiceNode: by node ID %s, [%s] %s => %s\", minfo.NID, service, name, rpcID)\n\t\t\t\t\treturn resp, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we don't have a MID, we must place the stream in a room\n\t// This mutex prevents a race condition which could cause\n\t// rooms to split between SFU's\n\troomMutex.Lock()\n\tdefer roomMutex.Unlock()\n\n\t// When we have a RID check for other pubs to colocate streams\n\tif rid != \"\" {\n\t\tlog.Infof(\"findServiceNode: got room id: %s, checking for existing streams\", rid)\n\t\trid := data.RID //util.Val(data, \"rid\")\n\t\tkey := proto.MediaInfo{\n\t\t\tDC: dc,\n\t\t\tRID: rid,\n\t\t}.BuildKey()\n\t\tlog.Infof(\"findServiceNode: RID root key=%s\", key)\n\n\t\tfor _, path := range redis.Keys(key + \"*\") {\n\n\t\t\tlog.Infof(\"findServiceNode media info path = %s\", path)\n\t\t\tminfo, err := proto.ParseMediaInfo(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error parsing media info = %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, node := range services {\n\t\t\t\tname := node.Info[\"name\"]\n\t\t\t\tid := node.Info[\"id\"]\n\t\t\t\tif service == node.Info[\"service\"] && minfo.NID == id {\n\t\t\t\t\trpcID := discovery.GetRPCChannel(node)\n\t\t\t\t\teventID := discovery.GetEventChannel(node)\n\t\t\t\t\tresp := proto.GetSFURPCParams{Name: name, RPCID: rpcID, EventID: eventID, Service: service, ID: id}\n\t\t\t\t\tlog.Infof(\"findServiceNode: by node ID %s, [%s] %s => %s\", minfo.NID, service, name, rpcID)\n\t\t\t\t\treturn resp, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// MID/RID Doesn't exist in Redis\n\t// Find least packed SFU to return\n\tsfuID := \"\"\n\tminStreamCount := math.MaxInt32\n\tfor _, sfu := range services {\n\t\tif service == sfu.Info[\"service\"] {\n\t\t\t// get stream count\n\t\t\tsfuKey := proto.MediaInfo{\n\t\t\t\tDC: dc,\n\t\t\t\tNID: sfu.Info[\"id\"],\n\t\t\t}.BuildKey()\n\t\t\tstreamCount := len(redis.Keys(sfuKey))\n\n\t\t\tlog.Infof(\"findServiceNode looking up sfu stream count [%s] = %v\", sfuKey, streamCount)\n\t\t\tif streamCount <= minStreamCount {\n\t\t\t\tsfuID = sfu.ID\n\t\t\t\tminStreamCount = streamCount\n\t\t\t}\n\t\t}\n\t}\n\tlog.Infof(\"findServiceNode: selecting SFU [%s] = %v\", sfuID, minStreamCount)\n\n\tif node, ok := services[sfuID]; ok {\n\t\tlog.Infof(\"findServiceNode: found best candidate SFU [%s]\", node)\n\t\trpcID := discovery.GetRPCChannel(node)\n\t\teventID := discovery.GetEventChannel(node)\n\t\tname := node.Info[\"name\"]\n\t\tid := node.Info[\"id\"]\n\t\tresp := proto.GetSFURPCParams{Name: name, RPCID: rpcID, EventID: eventID, Service: service, ID: id}\n\t\tlog.Infof(\"findServiceNode: [%s] %s => %s\", service, name, rpcID)\n\t\treturn resp, nil\n\t}\n\n\treturn nil, util.NewNpError(404, fmt.Sprintf(\"Service node [%s] not found\", service))\n}", "func (c *client) getNode(name string) (result, error) {\n\tnode, err := c.queryEndpoint(APINodesEndpoint, name+\"?memory=true\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(node) > 1 {\n\t\treturn nil, fmt.Errorf(\"Error: more than one result returned\")\n\t}\n\treturn node[0], nil\n}", "func (c *Client) queryNode(miniProtocol multiplex.MiniProtocol, dataItems []cbor.DataItem) (*multiplex.ServiceDataUnit, error) {\n\n\t// Step 1: Create message for the request\n\tsdu := multiplex.NewServiceDataUnit(miniProtocol, multiplex.MessageModeInitiator, dataItems)\n\tif log.IsLevelEnabled(log.DebugLevel) {\n\t\tlog.Debug(\"Multiplexed Request:\")\n\t\tfmt.Println(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> R E Q U E S T >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n\t\tfmt.Println(sdu.Debug())\n\t}\n\n\t// Step 2: Send the request\n\tmessageResponse, err := c.socket.Write(sdu.Bytes())\n\tif err != nil && err != io.EOF {\n\t\treturn nil, fmt.Errorf(\"Error writing to socket %w\", err)\n\t}\n\tif log.IsLevelEnabled(log.DebugLevel) && messageResponse != nil {\n\t\tlog.Debug(\"Multiplexed Response:\")\n\t\tfmt.Println(\"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< R E S P O N S E <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\")\n\t\tfmt.Println(messageResponse.Debug())\n\t}\n\n\treturn messageResponse, nil\n}", "func (s *Service) Listen() {\n\n}", "func createNode(id int, myConf *Config, sm *State_Machine) cluster.Server {\n\tinitNode(id, myConf, sm)\n\t//Set up details about cluster nodes form json file.\n\tserver, err := cluster.New(id, \"config/cluster_config.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn server\n}", "func (srv *NetService) createSelfNode() error {\n\thostname, _ := os.Hostname()\n\tnode := &bcstypes.NetServiceInfo{\n\t\tServerInfo: bcstypes.ServerInfo{\n\t\t\tIP: srv.addr,\n\t\t\tPort: uint(srv.port),\n\t\t\tMetricPort: uint(srv.metricPort),\n\t\t\tPid: os.Getpid(),\n\t\t\tHostName: hostname,\n\t\t\tScheme: \"https\",\n\t\t\tVersion: version.GetVersion(),\n\t\t},\n\t}\n\tdata, _ := json.Marshal(node)\n\tself := srv.addr + \":\" + strconv.Itoa(srv.port)\n\tkey := filepath.Join(defaultDiscoveryPath, self)\n\t//clean self node first and then create new one\n\tif exist, _ := srv.store.Exist(key); exist {\n\t\tblog.Warn(\"server node %s exist, clean first\", key)\n\t\tsrv.store.Delete(key)\n\t}\n\terr := srv.store.RegisterAndWatch(key, data)\n\tif err != nil {\n\t\tblog.Errorf(\"create NetService %s temporary node %s err, %v\", srv.addr, key, err)\n\t\treturn err\n\t}\n\tblog.Info(\"NetService %s create temporary node %s success\", srv.addr, key)\n\n\treturn nil\n}", "func AddServer(data map[string]string)(err error) {\n uuid := data[\"uuid\"]\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"AddServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return err\n }\n err = nodeclient.AddServer(ipuuid,portuuid, data)\n if err != nil {\n logs.Error(\"node/AddServer ERROR http data request: \"+err.Error())\n return err\n }\n return nil\n}", "func setUpRPC(nodeRPC string) {\n\trpcServ := new(Service)\n\trpc.Register(rpcServ)\n\trpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\tif err != nil {\n\t\tlog.Fatal(\"listen error:\", err)\n\t}\n\tl, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tfor i := 0; i >= 0; i++ {\n\t\tconn, _ := l.AcceptTCP()\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t\tgo rpc.ServeConn(conn)\n\t\tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t\tcolorprint.Alert(\"=========================================================================================\")\n\t\tdefer conn.Close()\n\t}\n\tl.Close()\n\n\t// rpcServ := new(FTService)\n\t// rpc.Register(rpcServ)\n\t// rpcAddr, err := net.ResolveTCPAddr(\"tcp\", nodeRPC)\n\t// if err != nil {\n\t// \tlog.Fatal(\"listen error:\", err)\n\t// }\n\t// l, e := net.ListenTCP(consts.TransProtocol, rpcAddr)\n\t// if e != nil {\n\t// \tlog.Fatal(\"listen error:\", e)\n\t// }\n\t// for i := 0; i >= 0; i++ {\n\t// \tconn, _ := l.AcceptTCP()\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \tcolorprint.Debug(\"REQ \" + strconv.Itoa(i) + \": ESTABLISHING RPC REQUEST CONNECTION WITH \" + conn.LocalAddr().String())\n\t// \trpc.ServeConn(conn)\n\t// \tcolorprint.Blue(\"REQ \" + strconv.Itoa(i) + \": Request Served\")\n\t// \tcolorprint.Alert(\"=========================================================================================\")\n\t// \t//defer conn.Close()\n\t// }\n\t// l.Close()\n\n}", "func (c *instance) Node(call NodeCall) error {\n\to := bind.NewKeyedTransactor(c.key)\n\n\t// gateway redirect to private chain\n\tclient, err := ethclient.Dial(config.ETHAddr())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\tinstance, err := node.NewAccelerateNode(c.nodeAddr, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn call(instance, o)\n}", "func RunStap(uuid string)(data string, err error){\n if ndb.Db == nil {\n logs.Error(\"RunStap -- Can't acces to database\")\n return \"\", errors.New(\"RunStap -- Can't acces to database\")\n }\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return \"\",err}\n ipnid,portnid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"RunStap ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return \"\",err\n }\n data, err = nodeclient.RunStap(ipnid,portnid,uuid)\n if err != nil {\n logs.Error(\"Stap run ERROR: \"+err.Error())\n return \"\",err\n }\n return data,nil\n}", "func NodeProcess(n Node) {\n\tn.knowns[0] = n.id\n\tfor {\n\t\tselect {\n\t\t// Receive incoming request from Node personal channel containing the ID of the other node\n\t\tcase gotNode:= <- n.nodeChannel:\n\t\t\tpersonalBusUsed++\n\t\t\t// Comment out the next line for ease of reading output\n\t\t\tfmt.Printf (\"Node %d: Received reply via personal bus from Node %d.\\n\", n.id, gotNode.id)\n\t\t\ti := 0\n\t\t\texists := 0\n\t\t\tfor i <= n.knownPointer {\n\t\t\t\tif n.knowns[i] == gotNode.id {\n\t\t\t\t\texists = 1\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t}\n\t\t\t// If node does not know the other node, add it to own address\n\t\t\tif exists == 0 {\n\t\t\t\tn.knownPointer++\n\t\t\t\tn.knowns[n.knownPointer] = gotNode.id\n\t\t\t\tfmt.Printf (\"Updated node %d with list of known nodes: %v\\n\", n.id, n.knowns)\n\t\t\t\tgotNode.nodesThatKnowMe++\n\t\t\t\tif n.knownPointer >= (noOfNodes - 1) {\n\t\t\t\t\tfullyFilledNodes++\n\t\t\t\t\tfmt.Printf(\"Node %d address-book filled.\\n\", n.id)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t// Receive incoming request from bus containing the ID of the other node\n\t\tcase gotNode := <-bus:\n\t\tif (n.id == gotNode.id) {\n\t\tbus <- n\n\t\ttime.Sleep(time.Duration(random(speed/2, 2*speed)) * time.Millisecond)\n\t\t} else {\n\t\t// Comment out the next line for ease of reading output\n\t\tfmt.Printf (\"Node %d: Received request via common bus from Node %d.\\n\", n.id, gotNode.id)\n\t\tcommonBusUsed++\n\t\t\ti := 0\n\t\t\texists := 0\n\t\t\tfor i <= n.knownPointer {\n\t\t\t\tif n.knowns[i] == gotNode.id {\n\t\t\t\t\texists = 1\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t}\n\t\t\t// If node does not know the other node, add it to own address\n\t\t\tif exists == 0 {\n\t\t\t\tn.knownPointer++\n\t\t\t\tn.knowns[n.knownPointer] = gotNode.id\n\t\t\t\tfmt.Print (\"Updated node \", n.id)\n\t\t\t\tfmt.Println (\" with list of known nodes: \", n.knowns)\n\t\t\t\tgotNode.nodesThatKnowMe++\n\t\t\t\tif n.knownPointer >= (noOfNodes - 1) {\n\t\t\t\t\tfullyFilledNodes++\n\t\t\t\t\tfmt.Printf(\"Node %d address-book filled.\\n\", n.id)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Send self Node data to other node if other node does not have me in its address book\n\t\t\tj := 0\n\t\t\totherExists := 0\n\t\t\tfor j <= gotNode.knownPointer {\n\t\t\t\tif gotNode.knowns[j] == n.id {\n\t\t\t\t\totherExists = 1\n\t\t\t\t}\n\t\t\t\tj++\n\t\t\t}\n\t\t\t// If node does not know the other node, add it to own address\n\t\t\tif otherExists == 0 {\n\t\t\t\t// Comment out the next line to simulate without replies on personal channels\n\t\t\t\tgotNode.nodeChannel <- n\n\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase <-time.After(time.Duration(random(speed/2, 2*speed)) * time.Millisecond):\n\t\t\t// Stop broadcasting if everyone knows about this node\n\t\t\tif n.nodesThatKnowMe < (noOfNodes - 1) {\n\t\t\tfmt.Printf (\"Node %d: Placing request in bus.\\n\", n.id)\n\t\t\t\tbus <- n\n\t\t\t} \n\t\t\tbreak\n\t\t}\n\t}\n}", "func (c *consulClient) Nodes(ctx context.Context, query *Query, resultChan chan *NodeInfo, errorChan chan error) {\n\t//todo optimize: reduce the no of calls\n\t//todo health checks passing\n\t//resultChan := make(chan NodeInfo)\n\t//errorChan := make(chan error)\n\tfor _, dc := range query.QString.Datacenters {\n\t\tqo := query.QueryOptions.WithContext(ctx) // returns a new obj with ctx\n\t\tqo.Datacenter = dc\n\t\tqo.Namespace = query.QString.Namespace\n\t\tfor _, tag := range query.QString.Tags {\n\t\t\tgo func(datacenter string, serviceName string, tag string, qo *api.QueryOptions) {\n\t\t\t\tfmt.Println(\"Go routine started\", serviceName, tag, datacenter)\n\t\t\t\tdefer fmt.Println(\"Go routine exited\", serviceName, tag, datacenter)\n\t\t\t\tres, _, err := c.api.Service(query.QString.ServiceName, tag, true, qo)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrorChan <- err\n\t\t\t\t}\n\t\t\t\tfor _, r := range res {\n\t\t\t\t\tnodeInfo := NodeInfo{\n\t\t\t\t\t\tServiceName: r.Service.Service,\n\t\t\t\t\t\tDataCenter: r.Node.Datacenter,\n\t\t\t\t\t\tAddress: r.Node.Address,\n\t\t\t\t\t\tServicePort: r.Service.Port,\n\t\t\t\t\t\t//ServiceTags: r.Node.TaggedAddresses,\n\t\t\t\t\t\tModifyIndex: r.Node.ModifyIndex,\n\t\t\t\t\t}\n\t\t\t\t\tresultChan <- &nodeInfo\n\t\t\t\t}\n\t\t\t}(dc, query.QString.ServiceName, tag, qo)\n\t\t}\n\t}\n}", "func (inn *LocalNode) serviceHandler(id uint64, data interface{}) {\n\tnCh := make(chan nodes.Node)\n\tdefer close(nCh)\n\n\tlwID := atomic.LoadInt64(inn.lwID)\n\tif lwID >= int64(id) {\n\t\tlogger.Logger().Warn(\"event ID less than last processed ID\", zap.Uint64(\"event ID\", id), zap.Int64(\"last processed ID\", lwID))\n\t\treturn\n\t}\n\n\tentries, ok := data.([]*consulapi.ServiceEntry)\n\tif !ok {\n\t\treturn\n\t}\n\tfor _, entry := range entries {\n\t\taddr := fmt.Sprintf(\"%s:%d\", entry.Service.Address, entry.Service.Port)\n\t\tgo inn.registerExternalNode(entry.Node.Node, addr, nCh)\n\t}\n\tcount := len(entries)\n\tns := make([]nodes.Node, 0, count)\n\tfor node := range nCh {\n\t\tcount--\n\t\tif node != nil {\n\t\t\tns = append(ns, node)\n\t\t}\n\t\tif count == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err := inn.kvr.SetNodes(ns); err != nil {\n\t\tlogger.Logger().Error(\"unable to set nodes\", zap.Error(err))\n\t}\n\tlocations, err := inn.keysLocations(context.Background())\n\tif err != nil {\n\t\tlogger.Logger().Error(\"unable to get keys locations\", zap.Error(err))\n\t\treturn\n\t}\n\tif err := inn.Move(context.Background(), locations); err != nil {\n\t\tlogger.Logger().Error(\"local node move failed\", zap.Error(err))\n\t\treturn\n\t}\n\n\tif swapped := atomic.CompareAndSwapInt64(inn.lwID, lwID, int64(id)); !swapped {\n\t\tlogger.Logger().Warn(\"last watcher ID was not swapped\")\n\t\tinn.serviceHandler(id, entries)\n\t\treturn\n\t}\n}", "func GetServer(uuid string, serveruuid string)(data map[string]map[string]string, err error){\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return nil,err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"GetServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return nil,err\n }\n data, err = nodeclient.GetServer(ipuuid,portuuid, serveruuid)\n if err != nil {\n logs.Error(\"node/GetServer ERROR http data request: \"+err.Error())\n return nil, err\n }\n return data,nil\n}", "func getNodeClient() corev1.NodeInterface {\n\tlog.Debug(\"Creating Node client.\")\n\treturn client.CoreV1().Nodes()\n}", "func (s *srvNodeInfo) listNodes() {\n\tnmmu.RLock()\n\tnk := make([]int32, len(s.nodeMap))\n\ti := 0\n\tfor k := range s.nodeMap {\n\t\tnk[i] = k\n\t\ti++\n\t}\n\tsort.Slice(nk, func(i, j int) bool { return nk[i] < nk[j] })\n\tfor i := range nk {\n\t\teni := s.nodeMap[nk[i]]\n\t\tsub := time.Now().Sub(eni.LastAlive) / time.Second\n\t\tlog.Printf(\"%2d[%1d]%20s %-6.6s %-7.7s %14s %3d %2d:%3d %s\\n\", nk[i], eni.NodeType, eni.NodeName, eni.NodePBase, eni.NodeBinVersion, eni.Address, int(sub), eni.Count, eni.Status, eni.Arg)\n\t}\n\tnmmu.RUnlock()\n}", "func (c *Catalog) NodeServiceList(node string, q *QueryOptions) (*CatalogNodeServiceList, *QueryMeta, error) {\n\tr := c.c.newRequest(\"GET\", \"/v1/catalog/node-services/\"+node)\n\tr.setQueryOptions(q)\n\trtt, resp, err := c.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer closeResponseBody(resp)\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\n\tvar out *CatalogNodeServiceList\n\tif err := decodeBody(resp, &out); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn out, qm, nil\n}", "func Test(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Node is up\")\n\tn := GetNode()\n\tfmt.Printf(\"ID: %d\", n.ID)\n\tfmt.Printf(\"Name: %s\", *n.Name)\n\tfmt.Printf(\"IP: %s\", *n.IP)\n\tfmt.Printf(\"Enabled: %t\", n.Enabled)\n\tfmt.Printf(\"Clients: %d\", n.Clients)\n\tfmt.Printf(\"Added: %v\", n.Added)\n}", "func main() {\n\tsnapshotCache := cache.NewSnapshotCache(false, cache.IDHash{}, nil)\n\tserver := xds.NewServer(context.Background(), snapshotCache, nil)\n\tgrpcServer := grpc.NewServer()\n\tlis, _ := net.Listen(\"tcp\", \":5678\")\n\tdiscovery.RegisterAggregatedDiscoveryServiceServer(grpcServer, server)\n\tapi.RegisterEndpointDiscoveryServiceServer(grpcServer, server)\n\tapi.RegisterClusterDiscoveryServiceServer(grpcServer, server)\n\tapi.RegisterRouteDiscoveryServiceServer(grpcServer, server)\n\tapi.RegisterListenerDiscoveryServiceServer(grpcServer, server)\n\n\tgo func() {\n\t\tif err := grpcServer.Serve(lis); err != nil {\n\t\t\tglog.Error(err)\n\t\t}\n\t}()\n\n\tnode := &core.Node{ // 根据yaml文件中定义的id和名称\n\t\tId: \"envoy-64.58\",\n\t\tCluster: \"test\",\n\t}\n\tnodeConf := &NodeConfig{\n\t\tnode: node,\n\t\tendpoints: []types.Resource{},\n\t\tclusters: []types.Resource{},\n\t\troutes: []types.Resource{},\n\t\tlisteners: []types.Resource{},\n\t\truntimes: []types.Resource{},\n\t}\n\tinput := \"\"\n\t{\n\t\tclusterName := \"Cluster_With_Static_Endpoint\"\n\t\tfmt.Printf(\"Enter to update: %s\", clusterName)\n\t\t_, _ = fmt.Scanf(\"\\n\", &input)\n\t\tvar addrs []ADDR\n\t\taddrs = append(addrs, ADDR{\n\t\t\tAddress: \"127.0.0.1\",\n\t\t\tPort: 8081,\n\t\t})\n\t\tcluster := ClusterStatic(clusterName, addrs)\n\t\tnodeConf.clusters = append(nodeConf.clusters, cluster)\n\t\tUpdateSnapshotCache(snapshotCache, nodeConf, time.Now().String())\n\t\tglog.Info(clusterName + \" updated\")\n\t}\n\tselect {}\n}", "func SuperNodeAll() (SuperNodeInfo, error) {\n\tc := Client{}\n\ttimeout := time.Duration(50 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\tnode := strings.Split(model.Supernodes, \"//\")\n\tnode = strings.Split(node[1], \"/\")\n\tc.URL.Host = node[0]\n\tc.URL.Path = \"/nodes\"\n\tc.URL.Scheme = \"https\"\n\treq, err := c.buildReq(nil, nil, http.MethodGet)\n\tif err != nil {\n\t\treturn SuperNodeInfo{}, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn SuperNodeInfo{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn SuperNodeInfo{}, err\n\t}\n\n\tvar data = SuperNodeInfo{}\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn SuperNodeInfo{}, err\n\t}\n\treturn data, nil\n}", "func RunStapServer(uuid string, server string)(data string, err error){\n if ndb.Db == nil {\n logs.Error(\"RunStapServer -- Can't acces to database\")\n return \"\", errors.New(\"RunStapServer -- Can't acces to database\")\n }\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return \"\",err}\n ipnid,portnid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"RunStapServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return \"\",err\n }\n data, err = nodeclient.RunStapServer(ipnid,portnid,server)\n if err != nil {\n logs.Error(\"RunStapServer ERROR: \"+err.Error())\n return \"\",err\n }\n return data,nil\n}", "func (s *Server) start() error {\n\tif err := s.querynode.Start(); err != nil {\n\t\tlog.Error(\"QueryNode start failed\", zap.Error(err))\n\t\treturn err\n\t}\n\tif err := s.querynode.Register(); err != nil {\n\t\tlog.Error(\"QueryNode register service failed\", zap.Error(err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func createNode(cfg *meta.ClusterConfig, nodeUUID, nodeURL string) (*meta.Watcher, *meta.Node, *rpckit.RPCServer, error) {\n\t// create watcher\n\tw, err := meta.NewWatcher(nodeUUID, cfg)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Start a rpc server\n\trpcSrv, err := rpckit.NewRPCServer(fmt.Sprintf(\"datanode-%s\", nodeUUID), nodeURL, rpckit.WithLoggerEnabled(false))\n\tif err != nil {\n\t\tlog.Errorf(\"failed to listen to %s: Err %v\", nodeURL, err)\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// register RPC handlers\n\ttproto.RegisterDataNodeServer(rpcSrv.GrpcServer, &fakeDataNode{nodeUUID: nodeUUID})\n\trpcSrv.Start()\n\ttime.Sleep(time.Millisecond * 50)\n\n\t// create node\n\tnd, err := meta.NewNode(cfg, nodeUUID, nodeURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn w, nd, rpcSrv, nil\n}", "func bootNode() {\n\tlogrus.Info(\"Booting 0DB - The database that is 0% a database!\")\n\tcfg, err := config.GetConfig()\n\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\tzdb := node.New(cfg)\n\t// This will block the main thread\n\thttpendpoint.Listen(cfg.Rest.HttpPort, zdb)\n}", "func (d *Dao) NodeTree(c context.Context, token, bu, team string) (nodes []*model.Node, err error) {\n\tvar (\n\t\treq *http.Request\n\t\tnode string\n\t)\n\tif len(bu) != 0 {\n\t\tnode = \".\" + bu\n\t}\n\tif len(team) != 0 {\n\t\tnode = \".\" + team\n\t}\n\tif len(node) == 0 {\n\t\tnodes = append(nodes, &model.Node{Name: \"main\", Path: \"main\"})\n\t\tnodes = append(nodes, &model.Node{Name: \"ai\", Path: \"ai\"})\n\t\treturn\n\t}\n\tif req, err = http.NewRequest(\"GET\", fmt.Sprintf(nodeURI, node), nil); err != nil {\n\t\tlog.Error(\"Status url(%s) error(%v)\", dataURI, err)\n\t\treturn\n\t}\n\treq.Header.Set(\"X-Authorization-Token\", token)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData *model.Res `json:\"data\"`\n\t\tMessage string `json:\"message\"`\n\t\tStatus int `json:\"status\"`\n\t}\n\tif err = d.client.Do(c, req, &res); err != nil {\n\t\tlog.Error(\"d.Status url(%s) res($s) err(%v)\", dataURI, res, err)\n\t\treturn\n\t}\n\tif res.Code != 90000 {\n\t\terr = fmt.Errorf(\"error code :%d\", res.Code)\n\t\tlog.Error(\"Status url(%s) error(%v)\", dataURI, err)\n\t\treturn\n\t}\n\tfor _, tnode := range res.Data.Data {\n\t\tif bytes.Equal(prefix, []byte(tnode.Path)[0:9]) {\n\t\t\ttnode.Path = string([]byte(tnode.Path)[9:])\n\t\t}\n\t\tnodes = append(nodes, &model.Node{Name: tnode.Name, Path: tnode.Path})\n\t}\n\treturn\n}", "func (sdk *SDK) createNode(req *CreateInstanceRequest) (*cloudsvr.CloudNode, error) {\n\tvar err error\n\n\t// create ecs firstly\n\tecsID, err := sdk.NewEcs(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs create failed: %v\", err)\n\t}\n\tlog.Printf(\"aliyun ecs %s created at %s\", ecsID, req.RegionID)\n\n\t// if create succeed, but other operations failed, clean up the newly created ecs instance to prevent garbage left\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"aliyun cloud node creation failed, clean up the newly created ecs instance %s. [%v]\", ecsID, err)\n\t\t\tsdk.RemoveNode(&cloudsvr.CloudNode{ID: ecsID, RegionOrZoneID: req.RegionID})\n\t\t}\n\t}()\n\n\t// now ecs is stopped, we assign an public ip to it\n\tip, err := sdk.AssignEcsPublicIP(ecsID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s assign public ip failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s assgined public ipaddress %s\", ecsID, ip)\n\n\t// start ecs\n\tif err = sdk.StartEcs(ecsID); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s start failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s starting\", ecsID)\n\n\t// wait ecs to be running\n\tif err = sdk.WaitEcs(req.RegionID, ecsID, \"Running\", time.Second*300); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s waitting to be running failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s is Running now\", ecsID)\n\n\treturn &cloudsvr.CloudNode{\n\t\tID: ecsID,\n\t\tRegionOrZoneID: req.RegionID,\n\t\tInstanceType: req.InstanceType,\n\t\tCloudSvrType: sdk.Type(),\n\t\tIPAddr: ip,\n\t\tPort: \"22\",\n\t\tUser: \"root\",\n\t\tPassword: req.Password,\n\t}, nil\n}", "func (h *Hsc) getNodeInfo() (NodeInfo, error) {\n\tendpoint := fmt.Sprintf(\"%s/node_info\", h.LcdEndpoint)\n\tresp, err := http.Get(endpoint)\n\tif err != nil {\n\t\treturn NodeInfo{}, err\n\t}\n\n\tvar nodeInfo NodeInfo\n\tjdec := json.NewDecoder(resp.Body)\n\terr = jdec.Decode(&nodeInfo)\n\tif err != nil {\n\t\treturn NodeInfo{}, err\n\t}\n\n\treturn nodeInfo, nil\n}", "func broadcastNodeInfo() {\n\tpeers := GetPeers()\n\tlog.Println(\"Broadcasting this node's info to peers...\")\n\tfor _, peer := range peers {\n\t\taddress := fmt.Sprintf(\"%v:%v\", peer.IpAddress, peer.Port)\n\t\tconn, _ := net.Dial(\"tcp\", address)\n\t\tencoder := json.NewEncoder(conn)\n\t\tnodeMessage := NewNodeMessage(*nodeIp, *nodePort, false, true)\n\t\tencoder.Encode(nodeMessage)\n\t\tconn.Close()\n\t}\n}", "func (r *NodeReconciler) specService(node *filecoinv1alpha1.Node, svc *corev1.Service) {\n\tlabels := map[string]string{\n\t\t\"name\": \"node\",\n\t\t\"instance\": node.Name,\n\t}\n\n\tsvc.ObjectMeta.Labels = labels\n\n\tsvc.Spec.Ports = []corev1.ServicePort{\n\t\t{\n\t\t\tName: \"api\",\n\t\t\tPort: int32(node.Spec.APIPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.APIPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t},\n\t\t{\n\t\t\tName: \"p2p\",\n\t\t\tPort: int32(node.Spec.P2PPort),\n\t\t\tTargetPort: intstr.FromInt(int(node.Spec.P2PPort)),\n\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t},\n\t}\n\n\tsvc.Spec.Selector = labels\n}", "func Begin() {\n\t// Add this host.\n\tlogfInfo(\"Using listen IP: %s\", listenIP)\n\n\t// Use IPv6 address length if the listen IP is not an IPv4 address\n\tif GetListenIP().To4() == nil {\n\t\tipLen = net.IPv6len\n\t}\n\n\tme := Node{\n\t\tip: GetListenIP(),\n\t\tport: uint16(GetListenPort()),\n\t\ttimestamp: GetNowInMillis(),\n\t\tpingMillis: PingNoData,\n\t}\n\n\tthisHostAddress = me.Address()\n\tthisHost = &me\n\n\tlogInfo(\"My host address:\", thisHostAddress)\n\n\t// Add this node's status. Don't update any other node's statuses: they'll\n\t// report those back to us.\n\tupdateNodeStatus(thisHost, StatusAlive, 0, thisHost)\n\tAddNode(thisHost)\n\n\tgo listenUDP(GetListenPort())\n\n\t// Add initial hosts as specified by the SMUDGE_INITIAL_HOSTS property\n\tfor _, address := range GetInitialHosts() {\n\t\tn, err := CreateNodeByAddress(address)\n\t\tif err != nil {\n\t\t\tlogfError(\"Could not create node %s: %v\", address, err)\n\t\t} else {\n\t\t\tAddNode(n)\n\t\t}\n\t}\n\n\tif GetMulticastEnabled() {\n\t\tgo listenUDPMulticast(GetMulticastPort())\n\t\tgo multicastAnnounce(GetMulticastAddress())\n\t}\n\n\tgo startTimeoutCheckLoop()\n\n\t// Loop over a randomized list of all known nodes (except for this host\n\t// node), pinging one at a time. If the knownNodesModifiedFlag is set to\n\t// true by AddNode() or RemoveNode(), the we get a fresh list and start\n\t// again.\n\n\tfor {\n\t\tvar randomAllNodes = knownNodes.getRandomNodes(0, thisHost)\n\t\tvar pingCounter int\n\n\t\tfor _, node := range randomAllNodes {\n\t\t\t// Exponential backoff of dead nodes, until such time as they are removed.\n\t\t\tif node.status == StatusDead {\n\t\t\t\tvar dnc *deadNodeCounter\n\t\t\t\tvar ok bool\n\n\t\t\t\tdeadNodeRetries.Lock()\n\t\t\t\tif dnc, ok = deadNodeRetries.m[node.Address()]; !ok {\n\t\t\t\t\tdnc = &deadNodeCounter{retry: 1, retryCountdown: 2}\n\t\t\t\t\tdeadNodeRetries.m[node.Address()] = dnc\n\t\t\t\t}\n\t\t\t\tdeadNodeRetries.Unlock()\n\n\t\t\t\tdnc.retryCountdown--\n\n\t\t\t\tif dnc.retryCountdown <= 0 {\n\t\t\t\t\tdnc.retry++\n\t\t\t\t\tdnc.retryCountdown = int(math.Pow(2.0, float64(dnc.retry)))\n\n\t\t\t\t\tif dnc.retry > maxDeadNodeRetries {\n\t\t\t\t\t\tlogDebug(\"Forgetting dead node\", node.Address())\n\n\t\t\t\t\t\tdeadNodeRetries.Lock()\n\t\t\t\t\t\tdelete(deadNodeRetries.m, node.Address())\n\t\t\t\t\t\tdeadNodeRetries.Unlock()\n\n\t\t\t\t\t\tRemoveNode(node)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrentHeartbeat++\n\n\t\t\tlogfTrace(\"%d - hosts=%d (announce=%d forward=%d)\",\n\t\t\t\tcurrentHeartbeat,\n\t\t\t\tlen(randomAllNodes),\n\t\t\t\temitCount(),\n\t\t\t\tpingRequestCount())\n\n\t\t\tPingNode(node)\n\t\t\tpingCounter++\n\n\t\t\ttime.Sleep(time.Millisecond * time.Duration(GetHeartbeatMillis()))\n\n\t\t\tif knownNodesModifiedFlag {\n\t\t\t\tknownNodesModifiedFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif pingCounter == 0 {\n\t\t\tlogDebug(\"No nodes to ping. So lonely. :(\")\n\t\t\ttime.Sleep(time.Millisecond * time.Duration(GetHeartbeatMillis()))\n\t\t}\n\t}\n}", "func (ct *ctrlerCtx) diffNode(apicl apiclient.Services) {\n\topts := api.ListWatchOptions{}\n\n\t// get a list of all objects from API server\n\tobjlist, err := apicl.ClusterV1().Node().List(context.Background(), &opts)\n\tif err != nil {\n\t\tct.logger.Errorf(\"Error getting a list of objects. Err: %v\", err)\n\t\treturn\n\t}\n\n\tct.logger.Infof(\"diffNode(): NodeList returned %d objects\", len(objlist))\n\n\t// build an object map\n\tobjmap := make(map[string]*cluster.Node)\n\tfor _, obj := range objlist {\n\t\tobjmap[obj.GetKey()] = obj\n\t}\n\n\tlist, err := ct.Node().List(context.Background(), &opts)\n\tif err != nil && !strings.Contains(err.Error(), \"not found in local cache\") {\n\t\tct.logger.Infof(\"Failed to get a list of objects. Err: %s\", err)\n\t\treturn\n\t}\n\n\t// if an object is in our local cache and not in API server, trigger delete for it\n\tfor _, obj := range list {\n\t\t_, ok := objmap[obj.GetKey()]\n\t\tif !ok {\n\t\t\tct.logger.Infof(\"diffNode(): Deleting existing object %#v since its not in apiserver\", obj.GetKey())\n\t\t\tevt := kvstore.WatchEvent{\n\t\t\t\tType: kvstore.Deleted,\n\t\t\t\tKey: obj.GetKey(),\n\t\t\t\tObject: &obj.Node,\n\t\t\t}\n\t\t\tct.handleNodeEvent(&evt)\n\t\t}\n\t}\n\n\t// trigger create event for all others\n\tfor _, obj := range objlist {\n\t\tct.logger.Infof(\"diffNode(): Adding object %#v\", obj.GetKey())\n\t\tevt := kvstore.WatchEvent{\n\t\t\tType: kvstore.Created,\n\t\t\tKey: obj.GetKey(),\n\t\t\tObject: obj,\n\t\t}\n\t\tct.handleNodeEvent(&evt)\n\t}\n}", "func (nd Node) Run(nodeAddr string) error {\n\tpeerAddr, err := ParseNodeAddr(nodeAddr)\n\tif err != nil {\n\t\treturn error\n\t}\n\n\tversion, err := protocol.NewVersionMsg(\n\t\tnd.Network,\n\t\tpeerAddr.IP,\n\t\tpeerAddr.Port,\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsgSerialized, err := binary.Marshal(version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.Dial(\"tcp\", nodeAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\t_, err = conn.Write(msgSerialized)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo nd.monitorPeers()\n\t//go nd.mempool.Run() // TODO: uncomment\n\n\ttmp := make([]byte, protocol.MsgHeaderLength)\n\nloop:\n\tfor {\n\t\tn, err := conn.Read(tmp)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbreak loop\n\t\t}\n\n\t\tvar msgHeader protocol.MessageHeader\n\t\tif err := utils.DeserializeWithReader(&msgHeader, bytes.NewReader(tmp[:n])); err != nil {\n\t\t\tfmt.Errorf(\"invalide header: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := msgHeader.Validate(); err != nil {\n\t\t\tfmt.Errorf(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"received message: %s\\n\", msgHeader.Command)\n\n\t\tswitch msgHeader.CommandString() {\n\t\tcase \"version\":\n\t\t\tif err := nd.handleVersion(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'version': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"verack\":\n\t\t\tif err := nd.handleVerack(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handler 'verack': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"ping\":\n\t\t\tif err := nd.handlePing(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'ping': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"pong\":\n\t\t\tif err := nd.handlePong(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Errorf(\"failed to handle 'pong': %+v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \"inv\":\n\t\t\t//if err := no.handleInv(&msgHeader, conn); err != nil {\n\t\t\t//\tfmt.Errorf(\"failed to handle 'inv': %+v\", err)\n\t\t\t//\tcontinue\n\t\t\t//}\n\t\tcase \"tx\":\n\t\t\tif err := no.handleTx(&msgHeader, conn); err != nil {\n\t\t\t\tfmt.Printf(\"failed to handle 'tx': %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func NewNodeService() NodeService {\n\tf, err := indexer.NewFileIndexer()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while creating the node service: %v\", err)\n\t}\n\n\treturn NodeService{Indexer: f}\n}", "func NodeGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tif &node != nil {\n\t\tw.WriteHeader(200)\n\t\tif err := json.NewEncoder(w).Encode(node); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tparamError := swl.ParamError{\n\t\t\tError: \"Node not found\",\n\t\t}\n\t\tw.WriteHeader(404)\n\t\tif err := json.NewEncoder(w).Encode(paramError); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func getNode(nd *wssdcloud.Node) *cloud.Node {\n\treturn &cloud.Node{\n\t\tName: &nd.Name,\n\t\tLocation: &nd.LocationName,\n\t\tNodeProperties: &cloud.NodeProperties{\n\t\t\tFQDN: &nd.Fqdn,\n\t\t\tPort: &nd.Port,\n\t\t\tAuthorizerPort: &nd.AuthorizerPort,\n\t\t\tCertificate: &nd.Certificate,\n\t\t\tStatuses: getNodeStatuses(nd),\n\t\t},\n\t\tVersion: &nd.Status.Version.Number,\n\t}\n}", "func startNode(cfg *Config) error {\n\tapp, err := app.NewApplication(cfg.App())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmcfg, nodeLogger, nodeKey, err := setupNode()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup config: %w\", err)\n\t}\n\n\tn, err := node.NewNode(tmcfg,\n\t\tprivval.LoadOrGenFilePV(tmcfg.PrivValidatorKeyFile(), tmcfg.PrivValidatorStateFile()),\n\t\tnodeKey,\n\t\tproxy.NewLocalClientCreator(app),\n\t\tnode.DefaultGenesisDocProviderFunc(tmcfg),\n\t\tnode.DefaultDBProvider,\n\t\tnode.DefaultMetricsProvider(tmcfg.Instrumentation),\n\t\tnodeLogger,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.Start()\n}", "func (sn *SimNode) Start(snapshots map[string][]byte) error {\n\tnewService := func(name string) func(ctx *node.ServiceContext) (node.Service, error) {\n\t\treturn func(nodeCtx *node.ServiceContext) (node.Service, error) {\n\t\t\tctx := &ServiceContext{\n\t\t\t\tRPCDialer: sn.adapter,\n\t\t\t\tNodeContext: nodeCtx,\n\t\t\t\tConfig: sn.config,\n\t\t\t}\n\t\t\tif snapshots != nil {\n\t\t\t\tctx.Snapshot = snapshots[name]\n\t\t\t}\n\t\t\tserviceFunc := sn.adapter.services[name]\n\t\t\tservice, err := serviceFunc(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsn.running[name] = service\n\t\t\treturn service, nil\n\t\t}\n\t}\n\n\t// ensure we only register the services once in the case of the node\n\t// being stopped and then started again\n\tvar regErr error\n\tsn.registerOnce.Do(func() {\n\t\tfor _, name := range sn.config.Services {\n\t\t\tif err := sn.node.Register(newService(name)); err != nil {\n\t\t\t\tregErr = err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\tif regErr != nil {\n\t\treturn regErr\n\t}\n\n\tif err := sn.node.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t// create an in-process RPC client\n\thandler, err := sn.node.RPCHandler()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsn.lock.Lock()\n\tsn.client = rpc.DialInProc(handler)\n\tsn.lock.Unlock()\n\n\treturn nil\n}", "func (sp *ServiceProcessor) renderNodePorts() error {\n\tsp.Log.Debug(\"ServiceProcessor - renderNodePorts()\")\n\n\tvar npServices []*renderer.ContivService\n\tfor _, svc := range sp.services {\n\t\tcontivSvc := svc.GetContivService()\n\t\tif contivSvc == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif contivSvc.HasNodePort() {\n\t\t\tnpServices = append(npServices, contivSvc)\n\t\t}\n\t}\n\tfor _, renderer := range sp.renderers {\n\t\terr := renderer.UpdateNodePortServices(sp.getNodeIPs(), npServices)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *requester) do(ctx context.Context, handler func(pr protocol.Reply, r *rpcclient.RPCReply)) (*rpcclient.Stats, error) {\n\ttargets := make([]string, len(r.client.targets))\n\tvar err error\n\n\tr.client.Lock()\n\tcopy(targets, r.client.targets)\n\tdiscoverer := r.client.ns\n\tfilters := r.client.filters\n\tfw := r.client.fw\n\n\topts := []rpcclient.RequestOption{}\n\tdiscoveryStart := time.Now()\n\n\tif r.client.ddl.Metadata.Service {\n\t\topts = append(opts, rpcclient.ServiceRequest(), rpcclient.Workers(1))\n\t} else if len(targets) == 0 {\n\t\tif r.client.clientOpts.progress {\n\t\t\tfmt.Print(\"Discovering nodes .... \")\n\t\t} else {\n\t\t\tr.client.infof(\"Starting discovery\")\n\t\t}\n\n\t\ttargets, err = discoverer.Discover(ctx, fw, filters)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(targets) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no nodes were discovered\")\n\t\t}\n\n\t\tif r.client.clientOpts.progress {\n\t\t\tfmt.Printf(\"%d\\n\", len(targets))\n\t\t} else {\n\t\t\tr.client.infof(\"Discovered %d nodes\", len(targets))\n\t\t}\n\t}\n\tdiscoveryEnd := time.Now()\n\n\tif r.client.workers > 0 {\n\t\topts = append(opts, rpcclient.Workers(r.client.workers))\n\t}\n\n\tif r.client.exprFilter != \"\" {\n\t\topts = append(opts, rpcclient.ReplyExprFilter(r.client.exprFilter))\n\t}\n\n\tif len(targets) > 0 {\n\t\topts = append(opts, rpcclient.Targets(targets))\n\t}\n\n\topts = append(opts, r.client.clientRPCOpts...)\n\n\tr.client.Unlock()\n\n\tif r.client.clientOpts.progress {\n\t\tfmt.Println()\n\t\tr.configureProgress(len(targets))\n\t}\n\n\tagent, err := rpcclient.New(r.client.fw, r.client.ddl.Metadata.Name, rpcclient.DDL(r.client.ddl))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not create client: %s\", err)\n\t}\n\n\tif r.client.clientOpts.progress {\n\t\topts = append(opts, rpcclient.ReplyHandler(func(pr protocol.Reply, rpcr *rpcclient.RPCReply) {\n\t\t\tr.progress.Incr()\n\t\t\thandler(pr, rpcr)\n\t\t}))\n\t} else if !r.client.noReplies {\n\t\topts = append(opts, rpcclient.ReplyHandler(handler))\n\t}\n\n\tif !r.client.clientOpts.progress {\n\t\tr.client.debugf(\"Invoking %s#%s action with %#v\", r.client.ddl.Metadata.Name, r.action, r.args)\n\t}\n\n\tres, err := agent.Do(ctx, r.action, r.args, opts...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not perform request: %s\", err)\n\t}\n\n\tif r.client.clientOpts.progress {\n\t\tuiprogress.Stop()\n\t\tfmt.Println()\n\t}\n\n\tif !discoveryStart.IsZero() && !discoveryEnd.IsZero() {\n\t\tres.Stats().OverrideDiscoveryTime(discoveryStart, discoveryEnd)\n\t}\n\n\treturn res.Stats(), nil\n}", "func (s *MultipassServer) Nodes(ctx context.Context, request *apigrpc.NodeGroupServiceRequest) (*apigrpc.NodesReply, error) {\n\tglog.V(5).Infof(\"Call server Nodes: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tnodeGroup := s.Groups[request.GetNodeGroupID()]\n\n\tif nodeGroup == nil {\n\t\tglog.Errorf(errNodeGroupNotFound, request.GetNodeGroupID())\n\n\t\treturn &apigrpc.NodesReply{\n\t\t\tResponse: &apigrpc.NodesReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errNodeGroupNotFound, request.GetNodeGroupID()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tinstances := make([]*apigrpc.Instance, 0, len(nodeGroup.Nodes))\n\n\tfor nodeName, node := range nodeGroup.Nodes {\n\t\tinstances = append(instances, &apigrpc.Instance{\n\t\t\tId: nodeGroup.providerIDForNode(nodeName),\n\t\t\tStatus: &apigrpc.InstanceStatus{\n\t\t\t\tState: apigrpc.InstanceState(node.State),\n\t\t\t\tErrorInfo: nil,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn &apigrpc.NodesReply{\n\t\tResponse: &apigrpc.NodesReply_Instances{\n\t\t\tInstances: &apigrpc.Instances{\n\t\t\t\tItems: instances,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (s *SimulationPaxosProtocol) Node(config *onet.SimulationConfig) error {\n\tindex, _ := config.Roster.Search(config.Server.ServerIdentity.ID)\n\tif index < 0 {\n\t\tlog.Fatal(\"Didn't find this node in roster\")\n\t}\n\tlog.Lvl3(\"Initializing node-index\", index)\n\treturn s.SimulationBFTree.Node(config)\n}", "func (instance *NDiscovery) getNodeList(message *lygo_n_commons.Command) interface{} {\n\tresponse := make(map[string]interface{})\n\tif nil != instance.storage {\n\t\tnetworkId := message.GetParamAsString(\"network_id\")\n\t\tresponse[\"publishers\"] = instance.storage.QueryPublishersAll()\n\t\tresponse[\"nodes\"] = instance.storage.QueryNodes(networkId)\n\t}\n\treturn response\n}", "func Stap(n string) (data map[string]bool, err error) {\n err = ndb.GetTokenByUuid(n); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return nil,err}\n ip,port,err := ndb.ObtainPortIp(n)\n if err != nil {\n logs.Error(\"Stap ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return nil,err\n } \n data, err = nodeclient.Stap(ip,port,n)\n if err != nil {\n logs.Error(\"Stap ERROR: \"+err.Error())\n return nil,err\n }\n return data,nil\n}", "func (s *Client) Subscribe1Node(name string) (chan ServiceNode, error){\n\tresChan := make(chan ServiceNode)\n\tdone := make(chan struct{})\n\tnodeChan, _ := s.SubscribeNodes(name,done)\n\n\tgo func() {\n\t\tfor nodes := range nodeChan {\n\t\t\tif len(nodes) == 0 {\n\t\t\tclose(resChan)\n\t\t\tclose(done)\n\t\t\t}else if len(nodes) != 1 {\n\t\t\t\tlog.Printf(\"not suppose to see multiple primary nodes\")\n\t\t\t}else {\n\t\t\t\tresChan <- *nodes[0]\n\t\t\t}\n\t\t}\n\t}()\n\treturn resChan,nil\n}", "func startNodeCommunication(nodeAddress string, bc *Blockchain) {\n\tlistener, err := net.Listen(protocol, nodeAddress)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error: %s\\n\", err)\n\t\t}\n\t\tgo handleConnection(conn, bc)\n\t}\n}", "func getAllNodes() (types.NodesListResponse, error) {\n\tvar ret types.NodesListResponse\n\n\t// If a smartgroup name was specified, we need to perform a search first\n\t// and append it onto the URI.\n\tvar url string\n\tvar err error\n\tif smartgroup != \"\" {\n\t\tsearchID, err := getSearchID()\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\t\tsearchQ := client.Parameters{\n\t\t\tName: \"searchId\",\n\t\t\tValue: searchID,\n\t\t}\n\t\turl, err = client.GetURL(nodeURI, searchQ)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\t} else {\n\t\turl, err = client.GetURL(nodeURI)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\t}\n\n\treq, err := client.BuildReq(nil, url, http.MethodGet, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tbody, err := client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t// Decode the response.\n\terr = json.Unmarshal(body, &ret)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn ret, nil\n}", "func (n *Node) RegisterWithRingServer(ringUrl string) {\n nodeDataArray := []ConHash.NodeData {}\n //copy(tempNodeDataArray,localRing.ringNodeDataArray)\n //TODO: Can we do deduplication on the node side?\n for i := 0; i < n.NumTokens +1; i ++ {\n id := fmt.Sprintf(\"%s%d\", n.CName, i)\n hash := ConHash.HashMD5(id, 0, RING_MAX_ID)\n nodeDataArray = append(nodeDataArray, ConHash.NewNodeData(id, n.CName, hash, n.IP, n.Port))\n }\n log.Println(\"Length: \", len(nodeDataArray))\n n.NodeDataArray = nodeDataArray\n requestBody, err := json.Marshal(nodeDataArray)\n // Send the Ring Server\n //TODO: Refactor this into a function\n //TODO: Change RING_URL to be accessed from an attribute\n postURL := fmt.Sprintf(\"%s/%s\", ringUrl, REGISTER_ENDPOINT)\n resp, err := http.Post(postURL, \"application/json\", bytes.NewReader(requestBody))\n if err != nil {\n log.Println(\"Check if RingServer is up and running\")\n log.Fatalln(err)\n }\n defer resp.Body.Close()\n\n body, err := ioutil.ReadAll(resp.Body)\n //TODO: print status code instead of the response itself\n fmt.Println(\"Response from registering w Ring Server: \", string(body))\n if err != nil {\n log.Fatalln(err)\n }\n}", "func main() {\n\tvar settingsFile string\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tif len(os.Args) >= 2 {\n\t\tsettingsFile = os.Args[1]\n\t} else {\n\t\tsettingsFile = \"appsettings.json\"\n\t}\n\n\tc := swift.NewConfig(settingsFile)\n\ts := swift.NewStore(c)\n\tsvc := swift.NewStorageService(c, s...)\n\n\tfmt.Println(\"Add or update a node...\")\n\n\tvar r swift.Register\n\tr.Store = \"\"\n\tr.Network = \"\"\n\tr.Domain = \"\"\n\tr.Starts = time.Now().UTC().AddDate(0, 0, 1)\n\tr.Expires = time.Now().UTC().AddDate(0, 3, 0)\n\tr.Role = 1\n\n\tsuccess := false\n\tisUpdate := false\n\tfor !success {\n\n\t\t// Get the store to use\n\t\tif r.StoreError != \"\" {\n\t\t\tfmt.Println(r.StoreError)\n\t\t}\n\t\tfmt.Println(\"Select a store to use in the add or update operation:\")\n\t\tfor _, s := range svc.GetStoreNames() {\n\t\t\tfmt.Printf(\"\\t- %s\\r\\n\", s)\n\t\t}\n\t\tfmt.Printf(\"Store [%s]: \", r.Store)\n\t\tstore, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Store = store\n\n\t\t// Get the network name\n\t\tif r.NetworkError != \"\" {\n\t\t\tfmt.Println(r.NetworkError)\n\t\t}\n\t\tfmt.Printf(\"Node network name [%s]: \", r.Network)\n\t\tnetwork, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Network = network\n\n\t\t// Get the node domain\n\t\tfmt.Printf(\"Node domain [%s]: \", r.Domain)\n\t\tdomain, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.Domain = domain\n\n\t\t// get the node startdate\n\n\t\tfmt.Printf(\"Start date [%s]: \", r.Starts.Format(time.RFC3339))\n\t\tstarts, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif starts != \"\" {\n\t\t\tr.Starts, err = time.Parse(time.RFC3339, starts)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\t// get the node expiry date\n\t\tif r.ExpiresError != \"\" {\n\t\t\tfmt.Println(r.ExpiresError)\n\t\t}\n\t\tfmt.Printf(\"Expires date [%s]: \", r.Expires.Format(time.RFC3339))\n\t\texpires, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif expires != \"\" {\n\t\t\tr.Expires, err = time.Parse(time.RFC3339, expires)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\t// get the node role\n\t\tfmt.Println(\"Select a node role:\")\n\t\tprintNodeTypes()\n\t\tfmt.Printf(\"Role [%d]: \", r.Role)\n\t\trole, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif role != \"\" {\n\t\t\ti, err := strconv.Atoi(role)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tr.Role = i\n\t\t}\n\n\t\t// check if details are correct\n\t\tfmt.Println()\n\t\tfmt.Println(\"Confirm the details are correct!:\")\n\t\tfmt.Printf(\"\\tStore: %s\\r\\n\", r.Store)\n\t\tfmt.Printf(\"\\tNetwork Name: %s\\r\\n\", r.Network)\n\t\tfmt.Printf(\"\\tDomain Name: %s\\r\\n\", r.Domain)\n\t\tfmt.Printf(\"\\tStart Date: %s\\r\\n\", r.Starts.Format(time.RFC3339))\n\t\tfmt.Printf(\"\\tExpiry Date: %s\\r\\n\", r.Expires.Format(time.RFC3339))\n\t\tfmt.Printf(\"\\tRole: %d\\r\\n\", r.Role)\n\t\tfmt.Printf(\"Correct? (Y/n) [Y]: \")\n\t\tcorrect, err := scan(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif correct != \"y\" &&\n\t\t\tcorrect != \"Y\" &&\n\t\t\tcorrect != \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// set the node\n\t\tsuccess, isUpdate = svc.SetNode(&r)\n\t\tif !success {\n\t\t\tfmt.Println(\"There were some errors, check your values:\")\n\t\t}\n\t}\n\n\t// confirmation\n\tif isUpdate {\n\t\tfmt.Println(\"Node updated!\")\n\t} else {\n\t\tfmt.Println(\"Node added!\")\n\t}\n}", "func main() {\n\tlog.SetFlags(log.LstdFlags | log.Lmicroseconds)\n\tlog.Printf(\"My peers are %v\", os.Getenv(\"PEERS\"))\n\tlog.Printf(\"traffic is %v\", os.Getenv(\"TRAFFIC\"))\n\tpeers := []*node.Peer{}\n\tfor _, s := range strings.Split(os.Getenv(\"PEERS\"), \" \") {\n\t\tp := &node.Peer{\n\t\t\tHost: fmt.Sprintf(\"node-%s\", s),\n\t\t\tPort: s}\n\t\tpeers = append(peers, p)\n\t}\n\n\n\tvar traffic = false\n\tif os.Getenv(\"TRAFFIC\") == \"1\" {\n\t\ttraffic = true\n\t}\n\n\tclientNode = client.NewClient(fmt.Sprintf(\"node-%s\", os.Getenv(\"PORT\")), os.Getenv(\"PORT\"), peers, uiChannel, nodeChannel, traffic)\n\n\terr := clientNode.SetupRPC()\n\tif err != nil {\n\t\tlog.Fatal(\"RPC setup error:\", err)\n\t}\n\terr = clientNode.Peer()\n\tif err != nil {\n\t\tlog.Fatal(\"Peering error:\", err)\n\t}\n\n\tfs := http.FileServer(http.Dir(\"../public\"))\n\thttp.Handle(\"/\", fs)\n\n\thttp.HandleFunc(\"/ws\", handleConnections)\n\thttp.HandleFunc(\"/disconnect\", handleDisconnect)\n\thttp.HandleFunc(\"/connect\", handleConnect)\n\thttp.HandleFunc(\"/getID\", handleGetID)\n\tgo handleMessages()\n\n\tgo func() {\n\t\terr := http.ListenAndServe(HttpPort, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t\t}\n\t}()\n\n\tif traffic == true{\n\t\tclientNode.Start()\n\t}\n\n\tfor {\n\t\ttime.Sleep(time.Hour)\n\t}\n}", "func watchFirstServer(node string) {\n\tpath := fmt.Sprintf(\"%s/%s\", Conf.Zookeeper.RootPath, node)\n\tfor {\n\t\tsubNodes, watch, err := getNodesW(path)\n\t\tif err != nil {\n\t\t\tLog.Error(\"watch node:%s error (%v)\", node, err)\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\t// If exist server then set it into NodeInfo\n\t\tif len(subNodes) != 0 {\n\t\t\tsort.Strings(subNodes)\n\t\t\tdata, _, err := zk.Get(fmt.Sprintf(\"%s/%s\", path, subNodes[0]))\n\t\t\tif err != nil {\n\t\t\t\tLog.Error(\"watch node:%s error (%v)\", node, err)\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tNodeInfo[node] = data\n\t\t} else {\n\t\t\tNodeInfo[node] = \"\"\n\t\t}\n\n\t\tLog.Info(\"begin to watch node:%s\", node)\n\t\tevent := <-watch\n\t\tLog.Info(\"end to watch node:%s event:%v\", node, event)\n\t}\n}", "func (rh *RegionHandler) NodeChangeHandler() {\n\t// log.Println(\"NodeChangeHandler started\")\n\tfor {\n\t\tncInfo := <-rh.RegionChange\n\n\t\tif ncInfo.PrevConn == nil && ncInfo.CurrConn == nil {\n\n\t\t\t// one node edge case: dump everything into primary\n\t\t\t// log.Println(\"one node edge case\")\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\trh.Regions[rid] = r \n\t\t\t\tr.SetReady()\n\t\t\t\tgo r.MaintainRegion()\n\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t}\n\t\t\t// log.Println(\"Number of reg handling: \")\n\t\t\trh.mux.Unlock()\n\n\n\t\t} else if ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// onSuccessorJoin:\n\t\t\t// move regions on curr node that hash to curr region to joined node\n\t\t\t// log.Println(\"onSuccessorJoin\", ncInfo.Curr, ncInfo.Prev)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \t// conn := ncInfo.PrevConn\n\t\t\t// \t// _, err = regionClient.RemoveRegion(context.Background(), &region_pb.IdRegionRequest{Id: rid})\n\t\t\t// \t// if err != nil {\n\t\t\t// \t// \tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t// }\n\t\t\t// }\n\n\t\t} else if ncInfo.Successor && !ncInfo.Join {\n\n\t\t\t// onSuccessorLeave:\n\t\t\t// move regions on curr node that hash to curr region to new successor\n\t\t\t// log.Println(\"onSuccessorLeave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\t// rh.mux.RLock()\n\t\t\t// for rid, r := range rh.Regions {\n\t\t\t// \tregionsCopy[rid] = r \n\t\t\t// }\n\t\t\t// rh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegion(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t} else if !ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// on predecessor join:\n\t\t\t// remove regions on curr node that hash to prepredecessor\n\t\t\t// log.Println(\"on predecessor join\", ncInfo.Curr, ncInfo.Prev)\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, _ := range rh.BackupRegions {\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) != ncInfo.Curr {\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// remove region on successor for which now I'm backup\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trmRegions := []*IdRegionRequest{}\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tlog.Println(\"Checking\", rid, rh.RegionHash[rid], rh.Router.Successor(rh.RegionHash[rid]), ncInfo.Curr, rh.Router.Hash)\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == ncInfo.Curr {\n\t\t\t\t\t// regionsCopy[rid] = r\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()}) \n\t\t\t\t\trmRegions = append(rmRegions, &IdRegionRequest{Id: rid})\n\t\t\t\t\tr.Quit <- true\n\t\t\t\t\tr.ClearAllBlobCache()\n\t\t\t\t\trh.BackupRegions[rid] = r\n\t\t\t\t\tdelete(rh.Regions, rid)\n\t\t\t\t\t// r.UnsetReady()\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// move regions that hash to joining node from curr node to joining node\n\t\t\t// remove regions on successor that hash to joining node\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tPredcessorConn := rh.Router.GetPredecessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.RemoveRegions(context.Background(), &RemoveRegionsRequest{Regions: rmRegions})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\t\t\tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t_, err = regionClient.TransferPrimary(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.RemoveRegion(context.Background(), &IdRegionRequest{Id: rid})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\n\t\t\t// \tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t// \t_, err = regionClient.TransferPrimary(context.Background(), &FoodRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \tr.UnsetReady()\n\t\t\t// }\n\n\t\t} else {\n\n\t\t\t// move regions that hashed to node that left to successor\n\t\t\t// log.Println(\"on predecessor leave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\t// log.Println(\"Checking\", rid, rh.RegionHash[rid])\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == rh.Router.Hash {\n\t\t\t\t\t// log.Println(\"Moving\", rid, \"from bkup to prim\")\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()})\n\t\t\t\t\t//regionsCopy[rid] = r\n\t\t\t\t\trh.Regions[rid] = r\n\t\t\t\t\tr.SetReady()\n\t\t\t\t\tgo r.MaintainRegion()\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\t\t}\n\t\t\n\t}\n}", "func (p *Plugin) NodeGetInfo(\n\tctx context.Context,\n\treq *csi.NodeGetInfoRequest) (\n\t*csi.NodeGetInfoResponse, error) {\n\n\tglog.Info(\"start to GetNodeInfo\")\n\tdefer glog.Info(\"end to GetNodeInfo\")\n\n\tif client == nil {\n\t\tmsg := \"client is nil\"\n\t\tglog.Error(msg)\n\t\treturn nil, status.Error(codes.InvalidArgument, msg)\n\t}\n\n\thostName, err := connector.GetHostName()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to get node name %v\", err)\n\t\tglog.Error(msg)\n\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\n\t}\n\n\tvar initiators []string\n\n\tvolDriverTypes := []string{connector.FcDriver, connector.IscsiDriver}\n\n\tfor _, volDriverType := range volDriverTypes {\n\t\tvolDriver := connector.NewConnector(volDriverType)\n\t\tif volDriver == nil {\n\t\t\tglog.Errorf(\"unsupport volDriver: %s\", volDriverType)\n\t\t\tcontinue\n\t\t}\n\n\t\tinitiator, err := volDriver.GetInitiatorInfo()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"cannot get initiator for driver volume type %s, err: %v\", volDriverType, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tinitiators = append(initiators, initiator)\n\t}\n\n\tif len(initiators) == 0 {\n\t\tmsg := fmt.Sprintf(\"cannot get any initiator for host %s\", hostName)\n\t\tglog.Error(msg)\n\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\n\t}\n\n\tnodeId := hostName + \",\" + strings.Join(initiators, \",\")\n\n\tglog.Infof(\"node info is %s\", nodeId)\n\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: nodeId,\n\t}, nil\n}", "func (a *FileStorageApiService) GetNodeExecute(r ApiGetNodeRequest) (SingleNode, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue SingleNode\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.Ctx, \"FileStorageApiService.GetNode\")\n\tif localBasePath == \"/\" {\n\t localBasePath = \"\"\n\t}\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v2/file_storage/buckets/{bucket_id}/nodes/{node_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"bucket_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_bucketId, \"\")) , -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node_id\"+\"}\", _neturl.PathEscape(parameterToString(r.P_nodeId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.P_directorySize != nil {\n\t\tlocalVarQueryParams.Add(\"directory_size\", parameterToString(*r.P_directorySize, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.Ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c *Client) NodeStats(ctx context.Context, n *NodeInfo) (NodeStats, error) {\n\tvar start = time.Now()\n\tvar l = c.l.With(\"node\", n)\n\n\t// retrieve details from stats API\n\ts, err := c.d.ContainerStats(ctx, n.DockerID, false)\n\tif err != nil {\n\t\tl.Errorw(\"failed to get container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tdefer s.Body.Close()\n\tb, err := ioutil.ReadAll(s.Body)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tvar stats rawContainerStats\n\tif err = json.Unmarshal(b, &stats); err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// retrieve details from container inspection\n\tinfo, err := c.d.ContainerInspect(ctx, n.DockerID)\n\tif err != nil {\n\t\tl.Errorw(\"failed to inspect container\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tcreated, err := time.Parse(time.RFC3339, info.Created)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container detail\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// check disk usage\n\tusage, err := dirSize(n.DataDir)\n\tif err != nil {\n\t\tl.Errorw(\"failed to calculate disk usage\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to calculate disk usage\")\n\t}\n\n\t// get peer ID\n\tvar cfgPath = filepath.Join(n.DataDir, \"config\")\n\tpeer, err := getConfig(cfgPath)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read node configuration\", \"error\", err, \"path\", cfgPath)\n\t\treturn NodeStats{}, fmt.Errorf(\"failed to get network node configuration\")\n\t}\n\n\tc.l.Debugw(\"retrieved node container data\",\n\t\t\"network_id\", n.NetworkID,\n\t\t\"docker_id\", n.DockerID,\n\t\t\"stat.duration\", time.Since(start))\n\n\treturn NodeStats{\n\t\tPeerID: peer.Identity.PeerID,\n\t\tPeerKey: peer.Identity.PrivKey,\n\t\tUptime: time.Since(created),\n\t\tStats: stats,\n\t\tDiskUsage: usage,\n\t}, nil\n}", "func (s *Server) getNodes() (nodeMap, error) {\n\tscopedLog := log\n\tif s.CiliumURI != \"\" {\n\t\tscopedLog = log.WithField(\"URI\", s.CiliumURI)\n\t}\n\tscopedLog.Debug(\"Sending request for /healthz ...\")\n\n\tresp, err := s.Daemon.GetHealthz(nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get agent health: %s\", err)\n\t}\n\tlog.Debug(\"Got cilium /healthz\")\n\n\tif resp == nil || resp.Payload == nil || resp.Payload.Cluster == nil {\n\t\treturn nil, fmt.Errorf(\"received nil health response\")\n\t}\n\n\tif resp.Payload.Cluster.Self != \"\" {\n\t\ts.RWMutex.Lock()\n\t\ts.localStatus = &healthModels.SelfStatus{\n\t\t\tName: resp.Payload.Cluster.Self,\n\t\t}\n\t\ts.RWMutex.Unlock()\n\t}\n\n\tnodes := make(nodeMap)\n\tfor _, n := range resp.Payload.Cluster.Nodes {\n\t\tif n.PrimaryAddress != nil {\n\t\t\tif n.PrimaryAddress.IPV4 != nil {\n\t\t\t\tnodes[ipString(n.PrimaryAddress.IPV4.IP)] = NewHealthNode(n)\n\t\t\t}\n\t\t\tif n.PrimaryAddress.IPV6 != nil {\n\t\t\t\tnodes[ipString(n.PrimaryAddress.IPV6.IP)] = NewHealthNode(n)\n\t\t\t}\n\t\t}\n\t\tfor _, addr := range n.SecondaryAddresses {\n\t\t\tnodes[ipString(addr.IP)] = NewHealthNode(n)\n\t\t}\n\t\tif n.HealthEndpointAddress != nil {\n\t\t\tif n.HealthEndpointAddress.IPV4 != nil {\n\t\t\t\tnodes[ipString(n.HealthEndpointAddress.IPV4.IP)] = NewHealthNode(n)\n\t\t\t}\n\t\t\tif n.HealthEndpointAddress.IPV6 != nil {\n\t\t\t\tnodes[ipString(n.HealthEndpointAddress.IPV6.IP)] = NewHealthNode(n)\n\t\t\t}\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func main() {\n\tflag.Parse()\n\n\tclusterNodeConfig := config.NewClusterNodeConfig(nodeID, raftDir, raftAddr, httpAddr, joinHttpAddr)\n\n\tnode := server.NewClusterNode(clusterNodeConfig)\n\n\t// Request to join cluster leader node if not bootstrap\n\tif !clusterNodeConfig.IsBootstrap() {\n\t\tif err := node.RequestJoinCluster(clusterNodeConfig.JoinHttpAddr, clusterNodeConfig.RaftAddr, clusterNodeConfig.NodeID); err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\t// Start http handler\n\thttpHandler := server.NewNodeHttpHandler(node, clusterNodeConfig.HttpAddr)\n\tif err := httpHandler.Start(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tnode.Logger.Println(\"Cluster Node Id \\\"\", nodeID, \"\\\" started successfully\")\n\n\tterminate := make(chan os.Signal, 1)\n\tsignal.Notify(terminate, os.Kill, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)\n\t<-terminate\n\n\t// snapshot when process terminated\n\tnode.SnapshotClusterNode()\n\tnode.Logger.Println(\"Cluster Node Id \\\"\", nodeID, \"\\\" exiting\")\n\n}", "func resourceNodeV1Create(d *schema.ResourceData, meta interface{}) error {\n\tclient, err := meta.(*Clients).GetIronicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the node object in Ironic\n\tcreateOpts := schemaToCreateOpts(d)\n\tresult, err := nodes.Create(client, createOpts).Extract()\n\tif err != nil {\n\t\td.SetId(\"\")\n\t\treturn err\n\t}\n\n\t// Setting the ID is what tells terraform we were successful in creating the node\n\tlog.Printf(\"[DEBUG] Node created with ID %s\\n\", d.Id())\n\td.SetId(result.UUID)\n\n\t// Create ports as part of the node object - you may also use the native port resource\n\tportSet := d.Get(\"ports\").(*schema.Set)\n\tif portSet != nil {\n\t\tportList := portSet.List()\n\t\tfor _, portInterface := range portList {\n\t\t\tport := portInterface.(map[string]interface{})\n\n\t\t\t// Terraform map can't handle bool... seriously.\n\t\t\tvar pxeEnabled bool\n\t\t\tif port[\"pxe_enabled\"] != nil {\n\t\t\t\tif port[\"pxe_enabled\"] == \"true\" {\n\t\t\t\t\tpxeEnabled = true\n\t\t\t\t} else {\n\t\t\t\t\tpxeEnabled = false\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// FIXME: All values other than address and pxe\n\t\t\tportCreateOpts := ports.CreateOpts{\n\t\t\t\tNodeUUID: d.Id(),\n\t\t\t\tAddress: port[\"address\"].(string),\n\t\t\t\tPXEEnabled: &pxeEnabled,\n\t\t\t}\n\t\t\t_, err := ports.Create(client, portCreateOpts).Extract()\n\t\t\tif err != nil {\n\t\t\t\t_ = resourcePortV1Read(d, meta)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make node manageable\n\tif d.Get(\"manage\").(bool) || d.Get(\"clean\").(bool) || d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"manage\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not manage: %s\", err)\n\t\t}\n\t}\n\n\t// Clean node\n\tif d.Get(\"clean\").(bool) {\n\t\tif err := setRAIDConfig(client, d); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to set raid config: %s\", err)\n\t\t}\n\n\t\tvar cleanSteps []nodes.CleanStep\n\t\tif cleanSteps, err = buildManualCleaningSteps(d.Get(\"raid_interface\").(string), d.Get(\"raid_config\").(string), d.Get(\"bios_settings\").(string)); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to build raid clean steps: %s\", err)\n\t\t}\n\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"clean\", nil, nil, cleanSteps); err != nil {\n\t\t\treturn fmt.Errorf(\"could not clean: %s\", err)\n\t\t}\n\t}\n\n\t// Inspect node\n\tif d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"inspect\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not inspect: %s\", err)\n\t\t}\n\t}\n\n\t// Make node available\n\tif d.Get(\"available\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"provide\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not make node available: %s\", err)\n\t\t}\n\t}\n\n\t// Change power state, if required\n\tif targetPowerState := d.Get(\"target_power_state\").(string); targetPowerState != \"\" {\n\t\terr := changePowerState(client, d, nodes.TargetPowerState(targetPowerState))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not change power state: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceNodeV1Read(d, meta)\n}", "func (s *NodeService) Status(ctx context.Context) (*GetNodeStatus, *http.Response, error) {\n\tvar responseStruct *GetNodeStatus\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"node/status\", nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func GetCommand(processNodePtr *nd.Node) {\n\tATA := &(*(*processNodePtr).ATAPtr)\n\tlogger := (*processNodePtr).Logger\n\tloggerByte := (*processNodePtr).LoggerByte\n\tloggerPerSec := (*processNodePtr).LoggerPerSec\n\tdestPortNum := (*processNodePtr).DestPortNum\n\tvmNumStr := (*processNodePtr).VmNumStr\n\tmyService := (*processNodePtr).MyService\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tbyteSent := 0\n\tfor {\n\t\tscanner.Scan()\n\t\tcommand := scanner.Text()\n\n\t\tif command == \"gossip\" {\n\t\t\tfmt.Println(\"Changing to Gossip\")\n\t\t\tloggerPerSec.Println(\"Changing to Gossip\")\n\t\t\tlogger.Println(\"Changing to Gossip\")\n\t\t\t*ATA = false\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"gossip\", destPortNum)\n\t\t\tloggerByte.Println(\"Command(Gossip) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"ata\" {\n\t\t\tfmt.Println(\"Changing to ATA\")\n\t\t\t*ATA = true\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"ata\", destPortNum)\n\t\t\tloggerPerSec.Println(\"Changing to ATA\")\n\t\t\tlogger.Println(\"Changing to ATA\")\n\n\t\t\tloggerByte.Println(\"Command(ATA) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"leave\" {\n\t\t\tfmt.Println(\"(Leave)Terminating vm_\", vmNumStr)\n\t\t\tloggerPerSec.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tlogger.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tos.Exit(1)\n\t\t} else if command == \"memberlist\" {\n\t\t\tfmt.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tloggerPerSec.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tlogger.Println(\"\\nMembership List: \\n\" + (*processNodePtr).PrintLog())\n\t\t} else if command == \"id\" {\n\t\t\tfmt.Println(\"Current IP and port:\", myService)\n\t\t\tloggerPerSec.Println(\"\\nCurrent IP and port: \" + myService + \"\\n\")\n\t\t\tlogger.Println(\"\\nCurrent IP and port:: \" + myService + \"\\n\")\n\t\t} else if command == \"-h\" {\n\t\t\tfmt.Println(\"gossip\t\t\t\t:\tchange the system into a gossip heartbeating\")\n\t\t\tfmt.Println(\"ata\t\t\t\t:\tchange the system into a All-to-All heartbeating\")\n\t\t\tfmt.Println(\"leave\t\t\t\t: \tvoluntarily leave the system. (halt)\")\n\t\t\tfmt.Println(\"memberlist\t\t\t: \tprint VM's memberlist to the terminal\")\n\t\t\tfmt.Println(\"id\t\t\t\t\t:\tprint current IP address and assigned Port number\")\n\t\t\tfmt.Println(\"heartbeat\t\t\t:\tprint the current heartbeat type\")\n\t\t\tfmt.Println(\"put <filename>\t\t: put a <filename> to the distributed system\")\n\t\t\tfmt.Println(\"pull <filename>\t: pull a <filename> from the distributed system and store in the the local folder\")\n\t\t\tfmt.Println(\"ls -l\t\t\t\t:\tprint the list of distributed files and its size in the current process\")\n\t\t\tfmt.Println(\"ls \t\t\t\t:\tprint the list of sdfsfile's in the system\")\n\t\t\tfmt.Println(\"ls <filename>\t\t:\tprint the list of IDs having a file <filename>\")\n\t\t\tfmt.Println(\"store\t\t\t\t:\tprint the list of distributed's in the process\")\n\t\t\tfmt.Println(\"remove <filename>\t:\tremove the <filename> from the system\")\n\t\t} else if command == \"heartbeat\" {\n\t\t\tif *ATA == true {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: ATA\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: Gossip\")\n\t\t\t}\n\t\t} else if len(command) > 3 && command[:3] == \"put\" {\n\t\t\tfilename := command[4:]\n\t\t\tfs.Put(processNodePtr, filename, 1)\n\n\t\t} else if len(command) > 4 && command[:4] == \"pull\" {\n\t\t\tfilename := command[5:]\n\t\t\tfs.Pull(processNodePtr, filename, 1)\n\n\t\t} else if command == \"ls -l\" { // list file names and its size of the files stored in the distributed folder\n\t\t\tfiles, err := ioutil.ReadDir(processNodePtr.DistributedPath)\n\t\t\tCheckError(err)\n\n\t\t\tfor i, file := range files {\n\t\t\t\tfmt.Println(strconv.Itoa(i)+\". \"+file.Name()+\":\", file.Size(), \"bytes\")\n\t\t\t}\n\t\t} else if command[0:2] == \"ls\" {\n\t\t\tFilenames := fs.GetFileList(processNodePtr)\n\n\t\t\tif len(command) > 2 { // list all machine (VM) addresses where this file is currently being stored\n\t\t\t\tfilename := command[3:]\n\n\t\t\t\t_, exist := Filenames[filename]\n\n\t\t\t\tif !exist {\n\t\t\t\t\tfmt.Println(\"no such file exist in DFS\")\n\t\t\t\t} else {\n\t\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\t\tif filename == file {\n\t\t\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\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} else { // list all file info\n\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if command == \"store\" { //list all files currently being stored at this machine\n\t\t\tfmt.Println(\"Files currently stored at this machine:\")\n\t\t\tfor _, file := range *processNodePtr.DistributedFilesPtr {\n\t\t\t\tfmt.Println(file)\n\t\t\t}\n\n\t\t} else if len(command) > 6 && command[:6] == \"remove\" { // remove the file\n\t\t\tfilename := command[7:]\n\t\t\tfs.RemoveFile(processNodePtr, filename)\n\n\t\t} else {\n\t\t\tfmt.Println(\"Invalid Command\")\n\t\t}\n\t}\n}", "func (c ClusterNodes) checkStatusOfClusterNodes() {\n\n}", "func determineService(startTLS string, node *Node) (err error){\n\n\tvar service, optimalProtocol string\n\n\tconn, err := net.Dial(\"tcp\", node.hostPort())\n\tconn.Close()\n\tif err != nil {\n\t\tlog.Error(\"Failed to connect to \", node, \"\\n\", err.Error())\n\t\treturn\n\t}\n\n\tif startTLS == \"\" { // no STARTTLS.\n\t\tsclient_auth(node)\n\t\t// TODO: Defunct? optimalProtocol = determineOptimalProtocol(\"https\") // TODO : Not sure is it's ok to hard-code this argument\n\t\tvar ua string\n\t\tif Options.GetBool(Sneaky) {\n\t\t\tua = UA_SNEAKY\n\t\t} else {\n\t\t\tua = UA_STD\n\t\t}\n\t\tnode.GetReq11 = `GET, `+node.Path+` HTTP/1.1\nHost:, `+node.Host +`\nUser-Agent:, `+ua+`\nAccept-Encoding: identity\nAccept: text/*\nConnection: Close\n\n`\n\t\tservice = serviceDetection(optimalProtocol, node)\n\t} else { // STARTTLS\n\t\tservice = startTLS\n\n\t\tvar protocol string\n\t\tif service == \"postgres\" {\n\t\t\tprotocol = \"postgres\"\n\t\t} else {\n\t\t\tprotocol = RxFinalS.ReplaceAllString(service, \"\") // strip trailing 's' in ftp(s), smtp(s), pop3(s), etc\n\t\t}\n\t\tswitch protocol {\n\t\tcase \"ftp\", \"smtp\", \"lmtp\", \"pop3\", \"imap\", \"xmpp\", \"telnet\", \"ldap\", \"postgres\", \"mysql\", \"nntp\":\n\t\t\tnode.startTlsOpts = \"-starttls \" + protocol\n\t\t\tSNI = \"\"\n\t\t\tswitch protocol {\n\t\t\tcase \"xmpp\":\n\t\t\t\t// for XMPP, openssl has a problem using -connect, NODEIP:$PORT. thus we use -connect, NODE:$PORT instead!\n\t\t\t\t// NODEIP = \"$NODE\" TODO: figure this out\n\t\t\t\tif Options.GetString(XmppHost) != \"\" {\n\t\t\t\t\tif !Meta.HasXmpp {\n\t\t\t\t\t\tlog.Fatal(\"Your, OPENSSL does not support the \\\"-xmpphost\\\" option\", ERR_OSSLBIN)\n\t\t\t\t\t}\n\t\t\t\t\tnode.startTlsOpts = node.startTlsOpts + \" -xmpphost, XMPP_HOST\" // small hack -- instead of changing calls all over the place\n\t\t\t\t\t// see http://xmpp.org/rfcs/rfc3920.html\n\t\t\t\t} else {\n\t\t\t\t\tif node.IsIpv4Addr() {\n\t\t\t\t\t\t// XMPP needs a jabber domainname\n\t\t\t\t\t\tif rDNS := node.Host; rDNS != \"\" {\n\t\t\t\t\t\t\tlog.Warn(\" IP address doesn't work for XMPP, trying PTR record, rDNS\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.Fatal(\"No DNS supplied and no PTR record available which I can try for XMPP\", ERR_DNSLOOKUP)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"postgres\":\n\t\t\t\t// Check if openssl version supports postgres.\n\t\t\t\tif ! Meta.HasPostgres {\n\t\t\t\t\tlog.Fatal(\"Your, OPENSSL does not support the \\\"-starttls postgres\\\" option\", ERR_OSSLBIN)\n\t\t\t\t}\n\t\t\tcase \"mysql\":\n\t\t\t\t// Check if openssl version supports mysql.\n\t\t\t\tif ! Meta.HasMysql {\n\t\t\t\t\tlog.Fatal(\"Your, OPENSSL does not support the \\\"-starttls mysql\\\" option\", ERR_OSSLBIN)\n\t\t\t\t}\n\n\t\t\tcase \"lmtp\":\n\t\t\t\t// Check if openssl version supports lmtp.\n\t\t\t\tif ! Meta.HasLmtp {\n\t\t\t\t\tlog.Fatal(\"Your, OPENSSL does not support the \\\"-starttls lmtp\\\" option\", ERR_OSSLBIN)\n\t\t\t\t}\n\t\t\tcase \"nntp\":\n\t\t\t\t// Check if openssl version supports lmtp.\n\t\t\t\tif ! Meta.HasNntp {\n\t\t\t\t\tlog.Fatal(\"Your, OPENSSL does not support the \\\"-starttls nntp\\\" option\", ERR_OSSLBIN)\n\t\t\t\t}\n\t\t\t}\n\t\t\tstdOut, stdErr, _ :=runOssl(\"s_client\", s_client_options(\"-connect\", \"NODEIP:$PORT\", PROXY, BugsOpt, node.startTlsOpts), \"\")\n\t\t\tif stdErr != \"\" {\n\t\t\t\tlog.Fatal( \", OPENSSL couldn't establish STARTTLS via, protocol to, NODEIP:$PORT\", ERR_CONNECT)\n\t\t\t}\n\t\t\tif strings.Contains(stdOut, \"Server Temp Key\") {\n\t\t\t\tHAS_DH_BITS = true // FIX //190\n\t\t\t}\n\t\t\tout(\" Service set:$CORRECT_SPACES STARTTLS via \")\n\t\t\tout( strings.ToUpper(protocol))\n\t\t\tif protocol == \"mysql\" {\n\t\t\t\tout(\" -- attention, this is experimental\")\n\t\t\t}\n\t\t\tfileout(\"service\", \"INFO\", protocol)\n\t\t\tif Options.GetString(XmppHost) != \"\"{\n\t\t\t\tout( \" (XMPP domain='$XMPP_HOST')\")\n\t\t\t}\n\t\t\toutln()\n\n\t\tdefault:\n\t\t\tlog.Fatal(\"currently only ftp, smtp, lmtp, pop3, imap, xmpp, telnet, ldap, postgres, and mysql allowed\", ERR_CMDLINE)\n\n\t\t}\n\t}\n\t// tmpfile_handle, {FUNCNAME[0]}.txt\n\treturn\n}", "func (c channelBasedHealthChecker) WatchNodeService(\n\tnodeName types.NodeName,\n\tserviceID string,\n\tresultCh chan<- health.Result,\n\terrCh chan<- error,\n\tquitCh <-chan struct{},\n) {\n\tinputCh, ok := c.resultsChans[nodeName]\n\tif ok {\n\t\tfor result := range inputCh {\n\t\t\tresultCh <- result\n\t\t}\n\t} else {\n\t\tc.t.Fatalf(\"No results channel configured for %s\", nodeName)\n\t}\n}", "func (s *Server) Service() string { return \"mtd\" }", "func resourceNodeV1Read(d *schema.ResourceData, meta interface{}) error {\n\tclient, err := meta.(*Clients).GetIronicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnode, err := nodes.Get(client, d.Id()).Extract()\n\tif err != nil {\n\t\td.SetId(\"\")\n\t\treturn err\n\t}\n\n\t// TODO: Ironic's Create is different than the Node object itself, GET returns things like the\n\t// RaidConfig, we need to add those and handle them in CREATE\n\terr = d.Set(\"boot_interface\", node.BootInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"conductor_group\", node.ConductorGroup)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"console_interface\", node.ConsoleInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"deploy_interface\", node.DeployInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"driver\", node.Driver)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"driver_info\", node.DriverInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"extra\", node.Extra)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"inspect_interface\", node.InspectInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"instance_uuid\", node.InstanceUUID)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"management_interface\", node.ManagementInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"name\", node.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"network_interface\", node.NetworkInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"owner\", node.Owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"power_interface\", node.PowerInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"power_state\", node.PowerState)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"root_device\", node.Properties[\"root_device\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\tdelete(node.Properties, \"root_device\")\n\terr = d.Set(\"properties\", node.Properties)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"raid_interface\", node.RAIDInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"rescue_interface\", node.RescueInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"resource_class\", node.ResourceClass)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"storage_interface\", node.StorageInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = d.Set(\"vendor_interface\", node.VendorInterface)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn d.Set(\"provision_state\", node.ProvisionState)\n}", "func synchRequest() {\n\n\tfmt.Println(\" Network: \", getLocalConfigValue(_LEDGER_NETWORK_KEY))\n\tok, err := pingServer(_LEDGER)\n\t//ok, err := pingServer(_ATLAS)\n\t//ok := false\n\tif ok {\n\t\t// things are good.\n\t\tfmt.Println(\" Current ledger node is ACTIVE at address:\", getLocalConfigValue(_LEDGER_ADDRESS_KEY))\n\t\treturn // done.\n\t}\n\n\t// could not successful access the current ledger node. Proceed to check for other nodes.\n\tfmt.Println(\" Default ledger node is NOT ACTIVE:\", getLocalConfigValue(_LEDGER_ADDRESS_KEY))\n\tfmt.Println(\" Searching for a new primary ledger node .....\")\n\n\t// Obtain current list of available ledger nodes from look up directory (atlas)\n\tnodeList, err := getLedgerNodeList()\n\tif err != nil {\n\t\tfmt.Println(\" \", err)\n\t\t// Suggest a fix for certain circumstances\n\t\tif strings.Contains(err.Error(), \"does not exist\") {\n\t\t\tfmt.Printf(\" You may need to set or update local config variable: '%s'\\n\", _LEDGER_NETWORK_KEY)\n\t\t\tfmt.Printf(\" To view local and global variables try: %s config --list\\n\", filepath.Base(os.Args[0]))\n\t\t}\n\t\treturn\n\t}\n\t// Check if list is empty\n\tif len(nodeList) == 0 {\n\t\tfmt.Printf(\" The network '%s' has no ledger nodes registered\\n\", getLocalConfigValue(_LEDGER_NETWORK_KEY))\n\t\treturn\n\t}\n\tnewNodeFound := false\n\tfor _, node := range nodeList {\n\t\tif newNodeFound {\n\t\t\tbreak // from for loop.\n\t\t}\n\t\t//fmt.Println(\" Checking node:\", node.APIURL)\n\t\tok, err := pingServer(node.APIURL)\n\t\tif err != nil {\n\t\t\t//fmt.Println(\" \", err)\n\t\t}\n\t\tif ok {\n\t\t\tnewNodeFound = true\n\t\t\tsetLocalConfigValue(_LEDGER_ADDRESS_KEY, node.APIURL)\n\t\t\tfmt.Printf(\" Found ACTIVE ledger node at: '%s'\\n\", node.APIURL)\n\t\t\tfmt.Println(\" UPDATING default ledger node in config to:\", node.APIURL)\n\t\t}\n\t}\n\tif newNodeFound == false {\n\t\tfmt.Printf(\" Not able to locate an active ledger node referring the %s directory\\n\", _ATLAS)\n\t}\n}", "func (r *aerospikeReceiver) emitNode(info map[string]string, now pcommon.Timestamp, errs *scrapererror.ScrapeErrors) {\n\tr.logger.Debugf(\"emitNode len(info): %v\", len(info))\n\tfor k, v := range info {\n\t\tswitch k {\n\t\tcase \"client_connections\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionOpenDataPoint(now, v, metadata.AttributeConnectionTypeClient))\n\t\tcase \"fabric_connections\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionOpenDataPoint(now, v, metadata.AttributeConnectionTypeFabric))\n\t\tcase \"heartbeat_connections\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionOpenDataPoint(now, v, metadata.AttributeConnectionTypeHeartbeat))\n\t\tcase \"client_connections_closed\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeClient, metadata.AttributeConnectionOpClose))\n\t\tcase \"client_connections_opened\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeClient, metadata.AttributeConnectionOpOpen))\n\t\tcase \"fabric_connections_closed\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeFabric, metadata.AttributeConnectionOpClose))\n\t\tcase \"fabric_connections_opened\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeFabric, metadata.AttributeConnectionOpOpen))\n\t\tcase \"heartbeat_connections_closed\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeHeartbeat, metadata.AttributeConnectionOpClose))\n\t\tcase \"heartbeat_connections_opened\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeConnectionCountDataPoint(now, v, metadata.AttributeConnectionTypeHeartbeat, metadata.AttributeConnectionOpOpen))\n\t\tcase \"system_free_mem_pct\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeMemoryFreeDataPoint(now, v))\n\t\tcase \"query_tracked\":\n\t\t\taddPartialIfError(errs, r.mb.RecordAerospikeNodeQueryTrackedDataPoint(now, v))\n\t\t}\n\t}\n\n\trb := r.mb.NewResourceBuilder()\n\trb.SetAerospikeNodeName(info[\"node\"])\n\tr.mb.EmitForResource(metadata.WithResource(rb.Emit()))\n\tr.logger.Debug(\"finished emitNode\")\n}", "func getNode(ex SessionExecutor, msg CommonMessage) (rep CommonReply) {\n\tnodeMsg := msg.(nodeMessage)\n\n\tselectNodeTmpl := ex.getQuery(selectNodeOp)\n\tcn := newNode()\n\trows, err := ex.Query(fmt.Sprintf(selectNodeTmpl, nodeMsg.GetNodeTable()))\n\tif err != nil {\n\t\tdbLogger.Errorf(\"getNode query error:%s\", err)\n\t\treturn newNodeReply(nil, err)\n\t}\n\tdefer closeRowsAndLog(rows)\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&cn.name, &cn.ip, &cn.isCollector, &cn.duration, &cn.description, &cn.coords, &cn.address)\n\t\tif err != nil {\n\t\t\tdbLogger.Errorf(\"getNode fetch node row:%s\", err)\n\t\t\treturn newNodeReply(nil, err)\n\t\t}\n\t\t// Try to match the node.\n\t\tdbLogger.Infof(\"trying node matching with name:%s ip:%s\", cn.name, cn.ip)\n\t\tname, ip := nodeMsg.getNodeName(), nodeMsg.getNodeIP()\n\t\tif (name == cn.name && name != \"\") || (ip == cn.ip && ip != \"\") {\n\t\t\treturn newNodeReply(cn, nil)\n\t\t}\n\t}\n\n\treturn newNodeReply(nil, errNoNode)\n}", "func (c *Client) NodeID() uint64 { return c.nodeID }", "func PrintNodes() {\n\tcfg := &etcd.ClientConfig{\n\t\tConfig: &clientv3.Config{\n\t\t\tEndpoints: []string{\"127.0.0.1:32379\"},\n\t\t},\n\t\tOpTimeout: 1 * time.Second,\n\t}\n\tlogger := logrus.DefaultLogger()\n\tlogger.SetLevel(logging.FatalLevel)\n\tw := tabwriter.NewWriter(os.Stdout, 0, 8, 4, '\\t', 0)\n\t// Create connection to etcd.\n\tdb, err := etcd.NewEtcdConnectionWithBytes(*cfg, logger)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\titr, err := db.ListValues(\"/vnf-agent/contiv-ksr/allocatedIDs/\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting values\")\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"id\\tname\\t\\tip_address\\t\\tman_ip_addr\\tbuild_date\\t\\t\\tbuild_version\\t\\tstart_time\\tstate\\n\")\n\tw.Flush()\n\tfor {\n\t\tkv, stop := itr.GetNext()\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\tbuf := kv.GetValue()\n\t\tnodeInfo := &nodeinfomodel.NodeInfo{}\n\t\terr = json.Unmarshal(buf, nodeInfo)\n\t\t//fmt.Printf(\"NodeInfo: %+v\\n\", nodeInfo)\n\t\t// Do whatever processing we need to do\n\t\tbytes := http.GetNodeInfo(nodeInfo.ManagementIpAddress, \"liveness\")\n\t\tvar liveness telemetrymodel.NodeLiveness\n\t\terr = json.Unmarshal(bytes, &liveness)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tliveness.BuildDate = \"Not Available\"\n\t\t}\n\n\t\tfmt.Fprintf(w, \"%+v\\t%s\\t%s\\t%s\\t%s\\t%s\\t%d\\t%d\\n\",\n\t\t\tnodeInfo.Id,\n\t\t\tnodeInfo.Name,\n\t\t\tnodeInfo.IpAddress,\n\t\t\tnodeInfo.ManagementIpAddress,\n\t\t\tliveness.BuildDate,\n\t\t\tliveness.BuildVersion,\n\t\t\tliveness.StartTime,\n\t\t\tliveness.State)\n\n\t\tw.Flush()\n\t}\n\tdb.Close()\n}", "func NewNODES(config configuration.CONFIGURATION) *NODES_IMPL {\r\n client := new(NODES_IMPL)\r\n client.config = config\r\n return client\r\n}", "func main() {\n\tserverIP := os.Args[1]\n\tdataPath := os.Args[2]\n\n\tPublicIp = node.GeneratePublicIP()\n\tfmt.Println(\"The public IP is: [%s], DataPath is: %s\", ERR_COL+PublicIp+ERR_END, ERR_COL+dataPath+ERR_END)\n\t// Listener for clients -> cluster\n\tln1, _ := net.Listen(\"tcp\", PublicIp+\"0\")\n\n\t// Listener for server and other nodes\n\tln2, _ := net.Listen(\"tcp\", PublicIp+\"0\")\n\n\tInitializeDataStructs()\n\t// Open Filesystem on Disk\n\tnode.MountFiles(dataPath, WriteIdCh)\n\t// Open Peer to Peer RPC\n\tListenPeerRpc(ln2)\n\t// Connect to the Server\n\tnode.InitiateServerConnection(serverIP, PeerRpcAddr)\n\t// Open Cluster to App RPC\n\tListenClusterRpc(ln1)\n}", "func ListenOnPort(conn *net.UDPConn, nodePtr *nd.Node) (ms.MsList, string) {\n\tvar portLog string\n\tvar buf [5120]byte\n\tn, addr, err := conn.ReadFromUDP(buf[0:])\n\tif err != nil {\n\t\tfmt.Println(\"err != nil\")\n\t\treturn ms.MsList{}, \"\"\n\t}\n\n\tmessage := pk.DecodePacket(buf[:n])\n\tmessageType := message.Ptype\n\n\t// special command received\n\tif messageType == \"gossip\" {\n\t\tfmt.Println(\"changing to gossip\")\n\t\tportLog = \"changing to gossip\"\n\t\t(*(*nodePtr).ATAPtr) = false\n\t\tconn.WriteToUDP(pk.EncodePacket((*nodePtr).Id.IPAddress+\" turned into gossip\", nil), addr)\n\t\treturn ms.MsList{}, portLog\n\t} else if messageType == \"ata\" {\n\t\tfmt.Println(\"changing to ATA\")\n\t\tportLog = \"changing to ATA\"\n\t\t(*(*nodePtr).ATAPtr) = true\n\t\tconn.WriteToUDP(pk.EncodePacket((*nodePtr).Id.IPAddress+\" turned into ata\", nil), addr)\n\t\treturn ms.MsList{}, portLog\n\t} else if messageType == \"ReplicaList\" { // a processor has sent a request about the list of destinations to store its replica (only a leader should receive this)\n\t\tmsg := pk.DecodeIdList(message)\n\n\t\tN := nodePtr.MaxFail\n\t\tfilename := msg.Filename\n\t\toriginalID := msg.OriginalID\n\t\t// replicas stores the List of IDs to send the replicas\n\t\treplicas := (*nodePtr).PickReplicas(N, []ms.Id{originalID})\n\n\t\treplicaPackage := pk.IdListpacket{0, ms.Id{\"\", \"\"}, replicas, filename}\n\t\treplicaEncoded := pk.EncodeIdList(replicaPackage)\n\t\tencodedMsg := pk.EncodePacket(\"ReplicaList\", replicaEncoded)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\tLog := \"Sending Replicas\"\n\n\t\treturn ms.MsList{}, Log\n\t} else if messageType == \"FileNodeList\" { // a processor has send a request for the list of nodes that has the file\n\t\tmsg := pk.DecodeIdList(message)\n\n\t\tfilename := msg.Filename\n\n\t\t//send nodes that contains the requested file\n\t\tfileNodes := nodePtr.LeaderPtr.FileList[filename]\n\n\t\tfileNodePackage := pk.IdListpacket{0, ms.Id{\"\", \"\"}, fileNodes, filename}\n\t\tfileNodeEncoded := pk.EncodeIdList(fileNodePackage)\n\n\t\tencodedMsg := pk.EncodePacket(\"FileNodeList\", fileNodeEncoded)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\tLog := \"Sending FileNodes List\"\n\n\t\treturn ms.MsList{}, Log\n\t} else if messageType == \"updateFileList\" { // a process has sent PutListpacket for the leader to update\n\t\tmsg := pk.DecodePut(message)\n\t\tidInfo := msg.Id\n\t\tfilename := msg.Filename\n\t\tencodedMsg := pk.EncodePacket(\"empty\", nil)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\n\t\t// update FileList\n\t\tnodePtr.LeaderPtr.FileList[filename] = append(nodePtr.LeaderPtr.FileList[filename], idInfo)\n\n\t\t// update IdList\n\t\tnodePtr.LeaderPtr.IdList[idInfo] = append(nodePtr.LeaderPtr.IdList[idInfo], filename)\n\n\t\treturn ms.MsList{}, \"\"\n\t} else if messageType == \"get filelist\" { // ls sdfsfilename (leader send the list of all distributed files)\n\t\t// make a packet consists of list of files\n\t\tFileListEncoded := pk.EncodeFileList(pk.FileListpacket{nodePtr.LeaderPtr.FileList})\n\t\tencodedMsg := pk.EncodePacket(\"file list packet\", FileListEncoded)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\tLog := \"sending sdfsfilename List\"\n\n\t\treturn ms.MsList{}, Log\n\n\t} else if messageType == \"openTCP\" { // a processor has requested to open a TCP port for it\n\t\tmsg := pk.DecodeTCPcmd(message)\n\t\tcmd := msg.Cmd\n\t\tfileName := msg.Filename\n\t\tisPull := msg.IsPull\n\t\tLog := \"TCP Opened\"\n\n\t\t// open the TCP port\n\t\tfs.ListenTCP(cmd, fileName, nodePtr, conn, addr, isPull)\n\n\t\treturn ms.MsList{}, Log\n\n\t} else if messageType == \"send\" { // leader has commanded to send the file to processors\n\t\tmsg := pk.DecodeTCPsend(message)\n\t\tIsPull := msg.IsPull\n\t\tfileName := msg.Filename\n\t\ttoList := msg.ToList // processors to send the file\n\n\t\tencodedMsg := pk.EncodePacket(\"send command received\", nil)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\tLog := \"sending files to anothe processor\"\n\n\t\t// send the file\n\t\tfs.Send(nodePtr, fileName, toList, IsPull)\n\n\t\treturn ms.MsList{}, Log\n\n\t} else if messageType == \"election\" { // election ping for electing a leader\n\n\t\telectionPacket := pk.DecodeRingData(message)\n\t\tmyIndex := electionPacket.YourIndex // my index in the ring\n\t\tring := electionPacket.Ring\n\t\telectionPacket.YourIndex = (myIndex + 1) % len(ring) // update the receiver\n\t\tnewLeader := electionPacket.NewLeader\n\t\tinitiator := electionPacket.Initiator\n\n\t\tencodedMsg := pk.EncodePacket(\"election msg received\", nil)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\n\t\tif electionPacket.Elected {\n\t\t\t// election is done.\n\t\t\tif newLeader == nodePtr.MyService {\n\t\t\t\tfailedLeader := *nodePtr.LeaderServicePtr\n\t\t\t\t// electiton intiator ptr is on dormant\n\t\t\t\t*nodePtr.ElectionInitiatorPtr = \"\"\n\t\t\t\t//update current leader to new leader\n\t\t\t\t*nodePtr.LeaderServicePtr = newLeader\n\t\t\t\tfmt.Println(\"Elected Leader: \", newLeader)\n\t\t\t\tfs.LeaderInit(nodePtr, failedLeader)\n\t\t\t} else {\n\t\t\t\t//update current leader to new leader\n\t\t\t\t*nodePtr.LeaderServicePtr = newLeader\n\t\t\t\t//send the result to the next processor in the ring\n\t\t\t\tnd.SendElection(electionPacket)\n\t\t\t}\n\t\t\t// a leader hasn't selected yet\n\t\t} else {\n\t\t\tif initiator < *nodePtr.ElectionInitiatorPtr {\n\t\t\t\t// do nothing\n\t\t\t} else {\n\t\t\t\t*(nodePtr.ElectionInitiatorPtr) = initiator\n\t\t\t\tif newLeader == nodePtr.MyService { // Leader is the current processor, now let others know the new leader\n\t\t\t\t\telectionPacket.Elected = true\n\t\t\t\t} else if newLeader < nodePtr.MyService {\n\t\t\t\t\t//update the packet by making myself as the leader\n\t\t\t\t\telectionPacket.NewLeader = nodePtr.MyService\n\t\t\t\t}\n\t\t\t\t// pass the result to the next processor in the ring\n\t\t\t\tnd.SendElection(electionPacket)\n\t\t\t}\n\t\t}\n\t\treturn ms.MsList{}, \"\"\n\t} else if messageType == \"send a filelist\" { // a leader has requested to send the list of files (used for leader initiation)\n\n\t\tId := nodePtr.Id\n\t\tfilenames := *(*nodePtr).DistributedFilesPtr //list of files in a distributed folder\n\n\t\tpacket := pk.EncodeFilesPacket(pk.FilesPacket{Id, filenames})\n\t\tconn.WriteToUDP(pk.EncodePacket(\"List of files\", packet), addr)\n\n\t\tCheckError(err)\n\n\t\treturn ms.MsList{}, \"\"\n\t} else if messageType == \"request\" { // a processor has requested a file (pull)\n\t\tmsg := pk.DecodeTCPsend(message)\n\t\tvar message string\n\t\tdestinations := msg.ToList\n\t\tfilename := msg.Filename\n\n\t\t// file information inside the leader\n\t\tfileOwners, exists := nodePtr.LeaderPtr.FileList[filename]\n\n\t\t// check if file exists\n\t\tif !exists {\n\t\t\tmessage = filename + \" is not found in the system\"\n\t\t} else {\n\t\t\tmessage = (\"telling DFs to send a file to you...\")\n\t\t}\n\n\t\t// reply to the requestor\n\t\tencodedMsg := pk.EncodePacket(message, nil)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\n\t\tif exists {\n\t\t\tfrom := fileOwners[0]\n\t\t\tService := from.IPAddress + \":\" + strconv.Itoa(nodePtr.DestPortNum)\n\t\t\tif Service == nodePtr.MyService { // if the sender is the current node (Leader)\n\t\t\t\tfs.Send(nodePtr, filename, destinations, true)\n\t\t\t} else { // else tell the service to send the file to the requestor\n\t\t\t\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", Service)\n\t\t\t\tCheckError(err)\n\t\t\t\tconn, err := net.DialUDP(\"udp\", nil, udpAddr)\n\t\t\t\tCheckError(err)\n\t\t\t\tpacket := pk.EncodeTCPsend(pk.TCPsend{destinations, filename, true})\n\t\t\t\t// command a fileowner to send the file to the requested process\n\t\t\t\t_, err = conn.Write(pk.EncodePacket(\"send\", packet))\n\t\t\t\tCheckError(err)\n\t\t\t\tvar buf [512]byte\n\t\t\t\t_, err = conn.Read(buf[0:])\n\t\t\t\tCheckError(err)\n\t\t\t}\n\t\t}\n\t\treturn ms.MsList{}, \"\"\n\t} else if messageType == \"Remove\" { // a processor has requested to remove a file\n\t\tfilename := string(message.EncodePacket)\n\t\tfileOwners, exists := nodePtr.LeaderPtr.FileList[filename]\n\n\t\t//udate filelist\n\t\tdelete(nodePtr.LeaderPtr.FileList, filename)\n\n\t\t//update idlist\n\t\tfor id, filelist := range nodePtr.LeaderPtr.IdList {\n\t\t\tfile_deleted := 0\n\t\t\tfor i, file := range filelist {\n\t\t\t\tif file == filename {\n\t\t\t\t\tto_delete := i - file_deleted\n\t\t\t\t\t(*nodePtr.LeaderPtr).IdList[id] = append((*nodePtr.LeaderPtr).IdList[id][:to_delete], (*nodePtr.LeaderPtr).IdList[id][to_delete+1:]...)\n\t\t\t\t\tfile_deleted += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif exists {\n\t\t\tencodedMsg := pk.EncodePacket(\"File Found and removed it\", nil)\n\t\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\t} else {\n\t\t\tencodedMsg := pk.EncodePacket(\"File not Found\", nil)\n\t\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\t}\n\n\t\t// make each owner to remove the file\n\t\tfor _, fileOwner := range fileOwners {\n\t\t\tService := fileOwner.IPAddress + \":\" + strconv.Itoa(nodePtr.DestPortNum)\n\t\t\tif Service == nodePtr.MyService {\n\t\t\t\tfs.Remove(nodePtr, filename)\n\n\t\t\t} else {\n\t\t\t\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", Service)\n\t\t\t\tCheckError(err)\n\t\t\t\tconn, err := net.DialUDP(\"udp\", nil, udpAddr)\n\t\t\t\tCheckError(err)\n\n\t\t\t\t_, err = conn.Write(pk.EncodePacket(\"RemoveFile\", []byte(filename)))\n\t\t\t\tCheckError(err)\n\t\t\t\tvar buf [512]byte\n\t\t\t\t_, err = conn.Read(buf[0:])\n\t\t\t\tCheckError(err)\n\t\t\t}\n\t\t}\n\t\treturn ms.MsList{}, \"\"\n\t} else if messageType == \"RemoveFile\" { // remove the file\n\t\tfilename := string(message.EncodePacket)\n\n\t\tencodedMsg := pk.EncodePacket(\"Remove request received\", nil)\n\t\tconn.WriteToUDP(encodedMsg, addr)\n\n\t\tfs.Remove(nodePtr, filename)\n\t\treturn ms.MsList{}, \"\"\n\t}\n\n\tfmt.Println(\"not a valid packet, packet name:\", messageType)\n\treturn ms.MsList{}, \"string\"\n}", "func svcHandler()", "func (node *hostNode) Start() error {\n\tif err := node.discoveryProtocol.Start(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *Client) NodeList(params *NodeListParams) (*NodeListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewNodeListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"NodeList\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/nodes\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &NodeListReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*NodeListOK), nil\n\n}", "func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error) {\n\tr := c.c.newRequest(\"GET\", \"/v1/catalog/node/\"+node)\n\tr.setQueryOptions(q)\n\trtt, resp, err := c.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer closeResponseBody(resp)\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\n\tvar out *CatalogNode\n\tif err := decodeBody(resp, &out); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn out, qm, nil\n}", "func start(id ID, port int, connectTo string) (tapestry *Node, err error) {\n\n\t// Create the RPC server\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the hostname of this machine\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to get hostname of local machine to start Tapestry node. Reason: %v\", err)\n\t}\n\n\t// Get the port we are bound to\n\t_, actualport, err := net.SplitHostPort(lis.Addr().String()) //fmt.Sprintf(\"%v:%v\", name, port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The actual address of this node\n\taddress := fmt.Sprintf(\"%s:%s\", name, actualport)\n\n\t// Uncomment for xtrace\n\t// xtr.NewTask(\"startup\")\n\t// Trace.Print(\"Tapestry Starting up...\")\n\t// xtr.SetProcessName(fmt.Sprintf(\"Tapestry %X... (%v)\", id[:5], address))\n\n\t// Create the local node\n\ttapestry = NewTapestryNode(RemoteNode{Id: id, Address: address})\n\tfmt.Printf(\"Created tapestry node %v\\n\", tapestry)\n\n\tRegisterTapestryRPCServer(tapestry.server, tapestry)\n\t//fmt.Printf(\"Registered RPC Server\\n\")\n\tgo tapestry.server.Serve(lis)\n\n\t// If specified, connect to the provided address\n\tif connectTo != \"\" {\n\t\t// Get the node we're joining\n\t\tnode, err := SayHelloRPC(connectTo, tapestry.node)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error joining existing tapestry node %v, reason: %v\", address, err)\n\t\t}\n\t\terr = tapestry.Join(node)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn tapestry, nil\n}", "func startNode(dr *pb.DefineRequest) (string, error) {\n\tfor _, node := range dr.Nodes {\n\t\tif node.Start == true {\n\t\t\treturn node.Id, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"machine %v does not specify a start node: %v\", dr.Id, dr.Nodes)\n}", "func getNodePort(client kubernetes.Interface, ns, name string) (port, nodePort int32, err error) {\n\tglog.V(2).Infof(\"Waiting for %v/%v\", ns, name)\n\n\tvar svc *v1.Service\n\twait.Poll(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\tsvc, err = client.Core().Services(ns).Get(name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tfor _, p := range svc.Spec.Ports {\n\t\t\tif p.NodePort != 0 {\n\t\t\t\tport = p.Port\n\t\t\t\tnodePort = p.NodePort\n\t\t\t\tglog.V(3).Infof(\"Node port %v\", nodePort)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\treturn\n}", "func getNode(ctx context.Context, client client.Interface, nodeName string) *libapi.Node {\n\tnode, err := client.Nodes().Get(ctx, nodeName, options.GetOptions{})\n\tif err != nil {\n\t\tif _, ok := err.(cerrors.ErrorResourceDoesNotExist); !ok {\n\t\t\tlog.WithError(err).WithField(\"Name\", nodeName).Info(\"Unable to query node configuration\")\n\t\t\tlog.Warn(\"Unable to access datastore to query node configuration\")\n\t\t\tutils.Terminate()\n\t\t}\n\n\t\tlog.WithField(\"Name\", nodeName).Info(\"Building new node resource\")\n\t\tnode = libapi.NewNode()\n\t\tnode.Name = nodeName\n\t}\n\n\treturn node\n}", "func (c *Container) GetClusterNodes(ctx echo.Context) error {\n response := models.ClusterNodesResponse{\n Data: []models.NodeData{},\n }\n tabletServersFuture := make(chan helpers.TabletServersFuture)\n clusterConfigFuture := make(chan helpers.ClusterConfigFuture)\n go helpers.GetTabletServersFuture(helpers.HOST, tabletServersFuture)\n go helpers.GetClusterConfigFuture(helpers.HOST, clusterConfigFuture)\n tabletServersResponse := <-tabletServersFuture\n if tabletServersResponse.Error != nil {\n return ctx.String(http.StatusInternalServerError,\n tabletServersResponse.Error.Error())\n }\n // Use the cluster config API to get the read-replica (If any) placement UUID\n clusterConfigResponse := <-clusterConfigFuture\n readReplicaUuid := \"\"\n if clusterConfigResponse.Error == nil {\n for _, replica := range clusterConfigResponse.\n ClusterConfig.ReplicationInfo.ReadReplicas {\n readReplicaUuid = replica.PlacementUuid\n }\n }\n mastersFuture := make(chan helpers.MastersFuture)\n go helpers.GetMastersFuture(helpers.HOST, mastersFuture)\n\n nodeList := helpers.GetNodesList(tabletServersResponse)\n versionInfoFutures := map[string]chan helpers.VersionInfoFuture{}\n for _, nodeHost := range nodeList {\n versionInfoFuture := make(chan helpers.VersionInfoFuture)\n versionInfoFutures[nodeHost] = versionInfoFuture\n go helpers.GetVersionFuture(nodeHost, versionInfoFuture)\n }\n activeYsqlConnectionsFutures := map[string]chan helpers.ActiveYsqlConnectionsFuture{}\n activeYcqlConnectionsFutures := map[string]chan helpers.ActiveYcqlConnectionsFuture{}\n masterMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n tserverMemTrackersFutures := map[string]chan helpers.MemTrackersFuture{}\n for _, nodeHost := range nodeList {\n activeYsqlConnectionsFuture := make(chan helpers.ActiveYsqlConnectionsFuture)\n activeYsqlConnectionsFutures[nodeHost] = activeYsqlConnectionsFuture\n go helpers.GetActiveYsqlConnectionsFuture(nodeHost, activeYsqlConnectionsFuture)\n activeYcqlConnectionsFuture := make(chan helpers.ActiveYcqlConnectionsFuture)\n activeYcqlConnectionsFutures[nodeHost] = activeYcqlConnectionsFuture\n go helpers.GetActiveYcqlConnectionsFuture(nodeHost, activeYcqlConnectionsFuture)\n masterMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n masterMemTrackersFutures[nodeHost] = masterMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, true, masterMemTrackerFuture)\n tserverMemTrackerFuture := make(chan helpers.MemTrackersFuture)\n tserverMemTrackersFutures[nodeHost] = tserverMemTrackerFuture\n go helpers.GetMemTrackersFuture(nodeHost, false, tserverMemTrackerFuture)\n }\n masters := map[string]helpers.Master{}\n mastersResponse := <-mastersFuture\n if mastersResponse.Error == nil {\n for _, master := range mastersResponse.Masters {\n if len(master.Registration.PrivateRpcAddresses) > 0 {\n masters[master.Registration.PrivateRpcAddresses[0].Host] = master\n }\n }\n }\n currentTime := time.Now().UnixMicro()\n hostToUuid, errHostToUuidMap := helpers.GetHostToUuidMap(helpers.HOST)\n for placementUuid, obj := range tabletServersResponse.Tablets {\n // Cross check the placement UUID of the node with that of read-replica cluster\n isReadReplica := false\n if readReplicaUuid == placementUuid {\n isReadReplica = true\n }\n for hostport, nodeData := range obj {\n host, _, err := net.SplitHostPort(hostport)\n // If we can split hostport, just use host as name.\n // Otherwise, use hostport as name.\n // However, we can only get version information if we can get the host\n hostName := hostport\n versionNumber := \"\"\n activeYsqlConnections := int64(0)\n activeYcqlConnections := int64(0)\n isMasterUp := true\n ramUsedTserver := int64(0)\n ramUsedMaster := int64(0)\n ramLimitTserver := int64(0)\n ramLimitMaster := int64(0)\n masterUptimeUs := int64(0)\n totalDiskBytes := int64(0)\n if err == nil {\n hostName = host\n versionInfo := <-versionInfoFutures[hostName]\n if versionInfo.Error == nil {\n versionNumber = versionInfo.VersionInfo.VersionNumber\n }\n ysqlConnections := <-activeYsqlConnectionsFutures[hostName]\n if ysqlConnections.Error == nil {\n activeYsqlConnections += ysqlConnections.YsqlConnections\n }\n ycqlConnections := <-activeYcqlConnectionsFutures[hostName]\n if ycqlConnections.Error == nil {\n activeYcqlConnections += ycqlConnections.YcqlConnections\n }\n masterMemTracker := <-masterMemTrackersFutures[hostName]\n if masterMemTracker.Error == nil {\n ramUsedMaster = masterMemTracker.Consumption\n ramLimitMaster = masterMemTracker.Limit\n }\n tserverMemTracker := <-tserverMemTrackersFutures[hostName]\n if tserverMemTracker.Error == nil {\n ramUsedTserver = tserverMemTracker.Consumption\n ramLimitTserver = tserverMemTracker.Limit\n }\n if master, ok := masters[hostName]; ok {\n isMasterUp = master.Error == nil\n if isMasterUp {\n masterUptimeUs = currentTime - master.InstanceId.StartTimeUs\n }\n }\n if errHostToUuidMap == nil {\n query :=\n fmt.Sprintf(QUERY_LIMIT_ONE, \"system.metrics\", \"total_disk\",\n hostToUuid[hostName])\n session, err := c.GetSession()\n if err == nil {\n iter := session.Query(query).Iter()\n var ts int64\n var value int64\n var details string\n iter.Scan(&ts, &value, &details)\n totalDiskBytes = value\n }\n }\n }\n totalSstFileSizeBytes := int64(nodeData.TotalSstFileSizeBytes)\n uncompressedSstFileSizeBytes :=\n int64(nodeData.UncompressedSstFileSizeBytes)\n userTabletsTotal := int64(nodeData.UserTabletsTotal)\n userTabletsLeaders := int64(nodeData.UserTabletsLeaders)\n systemTabletsTotal := int64(nodeData.SystemTabletsTotal)\n systemTabletsLeaders := int64(nodeData.SystemTabletsLeaders)\n activeConnections := models.NodeDataMetricsActiveConnections{\n Ysql: activeYsqlConnections,\n Ycql: activeYcqlConnections,\n }\n ramUsedBytes := ramUsedMaster + ramUsedTserver\n ramProvisionedBytes := ramLimitMaster + ramLimitTserver\n isBootstrapping := true\n // For now we hard code isBootstrapping here, and we use the\n // GetIsLoadBalancerIdle endpoint separately to determine if\n // a node is bootstrapping on the frontend, since yb-admin is a\n // bit slow. Once we get a faster way of doing this we can move\n // the implementation here.\n // For now, assuming that IsMaster and IsTserver are always true\n // The UI frontend doesn't use these values so this should be ok for now\n response.Data = append(response.Data, models.NodeData{\n Name: hostName,\n Host: hostName,\n IsNodeUp: nodeData.Status == \"ALIVE\",\n IsMaster: true,\n IsTserver: true,\n IsReadReplica: isReadReplica,\n IsMasterUp: isMasterUp,\n IsBootstrapping: isBootstrapping,\n Metrics: models.NodeDataMetrics{\n // Eventually we want to change models.NodeDataMetrics so that\n // all the int64 fields are uint64. But currently openapi\n // generator only generates int64s. Ideally if we set\n // minimum: 0 in the specs, the generator should use uint64.\n // We should try to implement this into openapi-generator.\n MemoryUsedBytes: int64(nodeData.RamUsedBytes),\n TotalSstFileSizeBytes: &totalSstFileSizeBytes,\n UncompressedSstFileSizeBytes: &uncompressedSstFileSizeBytes,\n ReadOpsPerSec: nodeData.ReadOpsPerSec,\n WriteOpsPerSec: nodeData.WriteOpsPerSec,\n TimeSinceHbSec: nodeData.TimeSinceHbSec,\n UptimeSeconds: int64(nodeData.UptimeSeconds),\n UserTabletsTotal: userTabletsTotal,\n UserTabletsLeaders: userTabletsLeaders,\n SystemTabletsTotal: systemTabletsTotal,\n SystemTabletsLeaders: systemTabletsLeaders,\n ActiveConnections: activeConnections,\n MasterUptimeUs: masterUptimeUs,\n RamUsedBytes: ramUsedBytes,\n RamProvisionedBytes: ramProvisionedBytes,\n DiskProvisionedBytes: totalDiskBytes,\n },\n CloudInfo: models.NodeDataCloudInfo{\n Cloud: nodeData.Cloud,\n Region: nodeData.Region,\n Zone: nodeData.Zone,\n },\n SoftwareVersion: versionNumber,\n })\n }\n }\n sort.Slice(response.Data, func(i, j int) bool {\n return response.Data[i].Name < response.Data[j].Name\n })\n return ctx.JSON(http.StatusOK, response)\n}", "func (n *Node) OnStart() error {\n\t// Create & add listener\n\tl := p2p.NewListener(\n\t\tn.config.P2p.ListenAddr,\n\t\tn.config.P2p.ExternalAddr,\n\t\tn.config.P2p.Upnp,\n\t\tn.Logger.With(\"module\", \"p2p\"))\n\tn.adapter.AddListener(l)\n\n\t// Generate node PrivKey\n\tnodeKey, err := p2p.LoadOrGenNodeKey(n.config.NodeKeyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn.Logger.Info(\"P2p NodeId\", \"NodeId\", nodeKey.NodeId(), \"file\", n.config.NodeKeyFile)\n\n\tnodeInfo := n.makeNodeInfo(nodeKey.NodeId())\n\tn.adapter.SetNodeInfo(nodeInfo)\n\tn.adapter.SetNodeKey(nodeKey)\n\n\t// Add ourselves to addrbook to prevent dialing ourselves\n\tn.addrBook.AddOurAddress(nodeInfo.NetAddress())\n\n\t// Start the RPC server before the P2P server\n\t// so we can eg. receive txs for the first block\n\tif len(n.config.Rpc.ListenAddrs) > 0 {\n\t\t// TODO\n\t}\n\n\t// Start the adapter (the P2P server).\n\terr = n.adapter.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Always connect to persistent peers\n\tif len(n.config.P2p.PersistentPeers) > 0 {\n\t\terr = n.adapter.DialPeersAsync(n.addrBook, n.config.P2p.PersistentPeers, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func NodeProcessRequestFromMaster(r *http.Request) {\n\n\tlog.Println(\"NodeProcessRequestFromMaster .......\")\n}" ]
[ "0.6636706", "0.6527941", "0.6475853", "0.6468961", "0.6375092", "0.6348987", "0.6281095", "0.62069684", "0.62015045", "0.6137437", "0.6107315", "0.6094435", "0.6035908", "0.60183156", "0.5954477", "0.59266543", "0.591429", "0.59039694", "0.59034646", "0.5901773", "0.5898528", "0.5894441", "0.5883966", "0.5854184", "0.58390915", "0.5833914", "0.5815564", "0.5809277", "0.58002454", "0.5771207", "0.575994", "0.57559466", "0.5726046", "0.5719909", "0.57172316", "0.5716914", "0.57153213", "0.57138157", "0.5700536", "0.570014", "0.5689124", "0.56821525", "0.56751513", "0.56748444", "0.5673433", "0.5655667", "0.5643657", "0.56435317", "0.56327873", "0.56144077", "0.56086826", "0.5596921", "0.5595352", "0.5582851", "0.5578543", "0.5573932", "0.5571409", "0.55593646", "0.5559157", "0.5556067", "0.55516434", "0.5550273", "0.55460733", "0.55439436", "0.55404377", "0.5534171", "0.55337346", "0.55217695", "0.5509482", "0.55093473", "0.5507899", "0.54925364", "0.5486728", "0.5486134", "0.54832447", "0.5474584", "0.54645044", "0.54587644", "0.54579747", "0.54537106", "0.545075", "0.5446777", "0.54445386", "0.54336864", "0.5423457", "0.5422934", "0.54185605", "0.54108405", "0.54098356", "0.53957665", "0.53854996", "0.538056", "0.53773147", "0.53715557", "0.5371375", "0.5370096", "0.5366758", "0.5364719", "0.53541255", "0.5351777", "0.5348684" ]
0.0
-1
getVolumeAndAttachment Get volume and attachment with volumeId and attachmentId
func getVolumeAndAttachment(volumeId string, attachmentId string) (*model.VolumeSpec, *model.VolumeAttachmentSpec, error) { vol, err := client.GetVolume(volumeId) if nil != err || nil == vol { msg := fmt.Sprintf("volume %s does not exist, %v", volumeId, err) glog.Error(msg) return nil, nil, status.Error(codes.NotFound, msg) } attachment, err := client.GetVolumeAttachment(attachmentId) if nil != err || nil == attachment { msg := fmt.Sprintf("the volume attachment %s does not exist, %v", attachmentId, err) glog.Error(msg) return nil, nil, status.Error(codes.FailedPrecondition, msg) } return vol, attachment, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getVolumeAndAttachmentByVolumeId(volId string) (*model.VolumeSpec, *model.VolumeAttachmentSpec, error) {\n\tif r := getReplicationByVolume(volId); r != nil {\n\t\tvolId = r.Metadata[KAttachedVolumeId]\n\t}\n\n\tvol, err := client.GetVolume(volId)\n\tif nil != err || nil == vol {\n\t\tmsg := fmt.Sprintf(\"volume does not exist, %v\", err)\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.NotFound, msg)\n\t}\n\n\tattachments, err := client.ListVolumeAttachments()\n\tif nil != err {\n\t\tmsg := fmt.Sprintf(\"list volume attachments failed, %v\", err)\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.NotFound, msg)\n\t}\n\n\tvar attachment *model.VolumeAttachmentSpec\n\n\thostName, err := connector.GetHostName()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"faild to get host name %v\", err)\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.FailedPrecondition, msg)\n\t}\n\n\tfor _, attach := range attachments {\n\t\tif attach.VolumeId == volId && attach.Host == hostName {\n\t\t\tattachment = attach\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif attachment == nil {\n\t\tmsg := fmt.Sprintf(\"attachment is not exist\")\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.FailedPrecondition, msg)\n\t}\n\n\treturn vol, attachment, nil\n}", "func (s *StackEbrc) GetVolumeAttachment(serverID, id string) (*abstract.VolumeAttachment, fail.Error) {\n\tlogrus.Debugf(\">>> stacks.ebrc::GetVolumeAttachment(%s)\", id)\n\tdefer logrus.Debugf(\"<<< stacks.ebrc::GetVolumeAttachment(%s)\", id)\n\n\tvats, err := s.ListVolumeAttachments(serverID)\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error getting attachment\"))\n\t}\n\n\tfor _, vat := range vats {\n\t\tif vat.ID == id && vat.ServerID == serverID {\n\t\t\treturn &vat, nil\n\t\t}\n\t}\n\n\treturn nil, fail.Errorf(fmt.Sprintf(\"Attachment [%s] to [%s] not found\", id, serverID), nil)\n}", "func (s *Stack) GetVolumeAttachment(serverID, id string) (*resources.VolumeAttachment, error) {\n\tif s == nil {\n\t\treturn nil, scerr.InvalidInstanceError()\n\t}\n\tif serverID == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"serverID\", \"cannot be empty string\")\n\t}\n\tif id == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"id\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, \"('\"+serverID+\"', '\"+id+\"')\", true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tva, err := volumeattach.Get(s.ComputeClient, serverID, id).Extract()\n\tif err != nil {\n\t\treturn nil, scerr.Wrap(err, fmt.Sprintf(\"error getting volume attachment %s: %s\", id, ProviderErrorToString(err)))\n\t}\n\treturn &resources.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}, nil\n}", "func (client *Client) GetVolumeAttachment(serverID, id string) (*api.VolumeAttachment, error) {\n\tva, err := volumeattach.Get(client.Compute, serverID, id).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\treturn &api.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}, nil\n}", "func GetVolumeAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentState, opts ...pulumi.ResourceOption) (*VolumeAttachment, error) {\n\tvar resource VolumeAttachment\n\terr := ctx.ReadResource(\"digitalocean:index/volumeAttachment:VolumeAttachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (pstFile *File) GetAttachment(message *Message, attachmentNumber int, formatType string, encryptionType string) (Attachment, error) {\n\tif !message.HasAttachments() {\n\t\treturn Attachment{}, nil\n\t}\n\n\tattachmentsTableContext, err := pstFile.GetAttachmentsTableContext(message, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tif attachmentNumber > len(attachmentsTableContext) {\n\t\treturn Attachment{}, errors.New(fmt.Sprintf(\"invalid attachment number, there are only %d attachments\", len(attachmentsTableContext)))\n\t}\n\n\tattachmentTableContextItem := attachmentsTableContext[attachmentNumber]\n\n\tvar attachmentReferenceHNID int\n\n\tfor _, attachmentTableContextItemColumn := range attachmentTableContextItem {\n\t\tif attachmentTableContextItemColumn.PropertyID == 26610 {\n\t\t\tattachmentReferenceHNID = attachmentTableContextItemColumn.ReferenceHNID\n\t\t\tbreak\n\t\t}\n\t}\n\n\tattachmentLocalDescriptor, err := FindLocalDescriptor(message.LocalDescriptors, attachmentReferenceHNID, formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentLocalDescriptorLocalDescriptorsIdentifier, err := attachmentLocalDescriptor.GetLocalDescriptorsIdentifier(formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentLocalDescriptorLocalDescriptors, err := pstFile.GetLocalDescriptorsFromIdentifier(attachmentLocalDescriptorLocalDescriptorsIdentifier, formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentHeapOnNode, err := pstFile.NewHeapOnNodeFromLocalDescriptor(attachmentLocalDescriptor, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentPropertyContext, err := pstFile.GetPropertyContext(attachmentHeapOnNode, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\treturn Attachment{\n\t\tPropertyContext: attachmentPropertyContext,\n\t\tLocalDescriptors: attachmentLocalDescriptorLocalDescriptors,\n\t}, nil\n}", "func GetVolumeAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentState, opts ...pulumi.ResourceOption) (*VolumeAttachment, error) {\n\tvar resource VolumeAttachment\n\terr := ctx.ReadResource(\"aws:ec2/volumeAttachment:VolumeAttachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (vpcIks *IksVpcSession) GetVolumeAttachment(volumeAttachmentRequest provider.VolumeAttachmentRequest) (*provider.VolumeAttachmentResponse, error) {\n\tvpcIks.Logger.Debug(\"Entry of IksVpcSession.GetVolumeAttachment method...\")\n\tdefer vpcIks.Logger.Debug(\"Exit from IksVpcSession.GetVolumeAttachment method...\")\n\treturn vpcIks.IksSession.GetVolumeAttachment(volumeAttachmentRequest)\n}", "func (this *Value) GetAttachment(key string) interface{} {\n\tif this.attachments != nil {\n\t\treturn this.attachments[key]\n\t}\n\treturn nil\n}", "func (c *PostAttachmentClient) Get(ctx context.Context, id int) (*PostAttachment, error) {\n\treturn c.Query().Where(postattachment.ID(id)).Only(ctx)\n}", "func (vpcs *VPCSession) WaitForAttachVolume(volumeAttachmentTemplate provider.VolumeAttachmentRequest) (*provider.VolumeAttachmentResponse, error) {\n\tvpcs.Logger.Debug(\"Entry of WaitForAttachVolume method...\")\n\tdefer vpcs.Logger.Debug(\"Exit from WaitForAttachVolume method...\")\n\tvpcs.Logger.Info(\"Validating basic inputs for WaitForAttachVolume method...\", zap.Reflect(\"volumeAttachmentTemplate\", volumeAttachmentTemplate))\n\terr := vpcs.validateAttachVolumeRequest(volumeAttachmentTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmaxTimeout, maxRetryAttempt, retryGapDuration := vpcs.Config.GetTimeOutParameters()\n\tretryCount := 0\n\tvpcs.Logger.Info(\"Waiting for volume to be attached\", zap.Int(\"maxTimeout\", maxTimeout))\n\tfor retryCount < maxRetryAttempt {\n\t\tcurrentVolAttachment, errAPI := vpcs.GetVolumeAttachment(volumeAttachmentTemplate)\n\t\tif errAPI == nil && currentVolAttachment.Status == StatusAttached {\n\t\t\t// volume is attached return no error\n\t\t\tvpcs.Logger.Info(\"Volume attachment is complete\", zap.Int(\"retry attempt\", retryCount), zap.Int(\"max retry attepmts\", maxRetryAttempt), zap.Reflect(\"currentVolAttachment\", currentVolAttachment))\n\t\t\treturn currentVolAttachment, nil\n\t\t} else if errAPI != nil {\n\t\t\t// do not retry if there is error\n\t\t\tvpcs.Logger.Error(\"Error occured while finding volume attachment\", zap.Error(errAPI))\n\t\t\tuserErr := userError.GetUserError(string(userError.VolumeAttachFailed), errAPI, volumeAttachmentTemplate.VolumeID, volumeAttachmentTemplate.InstanceID)\n\t\t\treturn nil, userErr\n\t\t}\n\t\t// retry if attach status is not \"attached\"\n\t\tretryCount = retryCount + 1\n\t\tvpcs.Logger.Info(\"Volume is still attaching. Retry..\", zap.Int(\"retry attempt\", retryCount), zap.Int(\"max retry attepmts\", maxRetryAttempt), zap.Reflect(\"currentVolAttachment\", currentVolAttachment))\n\t\ttime.Sleep(retryGapDuration)\n\t}\n\tuserErr := userError.GetUserError(string(userError.VolumeAttachTimedOut), nil, volumeAttachmentTemplate.VolumeID, volumeAttachmentTemplate.InstanceID, vpcs.Config.Timeout)\n\tvpcs.Logger.Info(\"Wait for attach timed out\", zap.Error(userErr))\n\n\treturn nil, userErr\n}", "func Attach(c *golangsdk.ServiceClient, opts AttachOpts) (*jobs.Job, error) {\n\tb, err := golangsdk.BuildRequestBody(opts, \"volumeAttachment\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r jobs.Job\n\t_, err = c.Post(attachURL(c, opts.ServerId), b, &r, &golangsdk.RequestOpts{\n\t\tMoreHeaders: requestOpts.MoreHeaders,\n\t})\n\treturn &r, err\n}", "func GetAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AttachmentState, opts ...pulumi.ResourceOption) (*Attachment, error) {\n\tvar resource Attachment\n\terr := ctx.ReadResource(\"alicloud:slb/attachment:Attachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func List(c *golangsdk.ServiceClient, serverId string) ([]VolumeAttachment, error) {\n\tvar rst golangsdk.Result\n\t_, err := c.Get(rootURL(c, serverId), &rst.Body, &golangsdk.RequestOpts{\n\t\tMoreHeaders: requestOpts.MoreHeaders,\n\t})\n\tif err == nil {\n\t\tvar r []VolumeAttachment\n\t\trst.ExtractIntoSlicePtr(&r, \"volumeAttachments\")\n\t\treturn r, nil\n\t}\n\treturn nil, err\n}", "func GetVolumeAttachmentList(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentListState, opts ...pulumi.ResourceOption) (*VolumeAttachmentList, error) {\n\tvar resource VolumeAttachmentList\n\terr := ctx.ReadResource(\"kubernetes:storage.k8s.io/v1beta1:VolumeAttachmentList\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *EventItemRequestBuilder) AttachmentsById(id string)(*ia583e36d9ac073d787b4f5e0abb093224bbfbbb0acf8b3a6f1b0f1e7dfd13a55.AttachmentItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"attachment%2Did\"] = id\n }\n return ia583e36d9ac073d787b4f5e0abb093224bbfbbb0acf8b3a6f1b0f1e7dfd13a55.NewAttachmentItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (db *DB) GetAttachment(ctx context.Context, docID, rev, filename string) (*Attachment, error) {\n\tcType, md5sum, body, err := db.driverDB.GetAttachment(ctx, docID, rev, filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Attachment{\n\t\tReadCloser: body,\n\t\tFilename: filename,\n\t\tContentType: cType,\n\t\tMD5: MD5sum(md5sum),\n\t}, nil\n}", "func (client DnsClient) getSteeringPolicyAttachment(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/steeringPolicyAttachments/{steeringPolicyAttachmentId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetSteeringPolicyAttachmentResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *DataStore) ListLonghornVolumeAttachmentByVolumeRO(name string) ([]*longhorn.VolumeAttachment, error) {\n\tvolumeSelector, err := getVolumeSelector(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.lhVALister.VolumeAttachments(s.namespace).List(volumeSelector)\n}", "func (client *Client) CreateVolumeAttachment(request api.VolumeAttachmentRequest) (*api.VolumeAttachment, error) {\n\t// Create the attachment\n\tva, err := volumeattach.Create(client.Compute, request.ServerID, volumeattach.CreateOpts{\n\t\tVolumeID: request.VolumeID,\n\t}).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating volume attachment between server %s and volume %s: %s\", request.ServerID, request.VolumeID, ProviderErrorToString(err))\n\t}\n\n\tvaapi := &api.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}\n\n\t// Update the metadata\n\n\tmtdVol, err := metadata.LoadVolume(providers.FromClient(client), request.VolumeID)\n\tif err != nil {\n\n\t\t// Detach volume\n\t\tdetach_err := volumeattach.Delete(client.Compute, va.ServerID, va.ID).ExtractErr()\n\t\tif detach_err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error deleting volume attachment %s: %s\", va.ID, ProviderErrorToString(err))\n\t\t}\n\n\t\treturn nil, err\n\t}\n\terr = mtdVol.Attach(vaapi)\n\tif err != nil {\n\t\t// Detach volume\n\t\tdetach_err := volumeattach.Delete(client.Compute, va.ServerID, va.ID).ExtractErr()\n\t\tif detach_err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error deleting volume attachment %s: %s\", va.ID, ProviderErrorToString(err))\n\t\t}\n\n\t\treturn vaapi, err\n\t}\n\n\treturn vaapi, nil\n}", "func (cl *Client) VolumeAttach(ctx context.Context, vaa *csp.VolumeAttachArgs) (*csp.Volume, error) {\n\tsvc, vid, _ := VolumeIdentifierParse(vaa.VolumeIdentifier)\n\tswitch svc {\n\tcase ServiceGCE:\n\t\treturn cl.gceVolumeAttach(ctx, vaa, vid)\n\t}\n\treturn nil, fmt.Errorf(\"storage type currently unsupported\")\n}", "func (a *Client) GetAttachments(params *GetAttachmentsParams, authInfo runtime.ClientAuthInfoWriter) (*GetAttachmentsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAttachmentsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetAttachments\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/attachments\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetAttachmentsReader{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.(*GetAttachmentsOK)\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 GetAttachments: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a *EmailControllerApiService) GetAttachments(ctx _context.Context, emailId string) ([]AttachmentMetaData, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []AttachmentMetaData\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/emails/{emailId}/attachments\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"emailId\"+\"}\", _neturl.QueryEscape(parameterToString(emailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v []AttachmentMetaData\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (n *Client) GetAttachment(siteSlug string, pageSlug string, id int, options *Options) (attachment *Attachment, result *Result) {\n\tu := fmt.Sprintf(\"/sites/%s/pages/%s/attachments/%d\", siteSlug, pageSlug, id)\n\tr := n.getRequest(\"GET\", u, options)\n\ta := &attachmentWrap{}\n\tresult = n.retrieve(r, a)\n\tattachment = a.Attachment\n\n\treturn\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WithContext(ctx context.Context) *ReadStorageV1alpha1VolumeAttachmentParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (s stack) InspectVolumeAttachment(ctx context.Context, hostRef, vaID string) (*abstract.VolumeAttachment, fail.Error) {\n\tif valid.IsNil(s) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\treturn nil, fail.NotImplementedError(\"implement me\")\n}", "func (r Notification_Occurrence_Event) GetAttachedFile(attachmentId *int) (resp []byte, err error) {\n\tparams := []interface{}{\n\t\tattachmentId,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Notification_Occurrence_Event\", \"getAttachedFile\", params, &r.Options, &resp)\n\treturn\n}", "func GetIssueAttachment(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueGetIssueAttachment\n\t// ---\n\t// summary: Get an issue attachment\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: index\n\t// in: path\n\t// description: index of the issue\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// - name: attachment_id\n\t// in: path\n\t// description: id of the attachment to get\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Attachment\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/error\"\n\n\tissue := getIssueFromContext(ctx)\n\tif issue == nil {\n\t\treturn\n\t}\n\n\tattach := getIssueAttachmentSafeRead(ctx, issue)\n\tif attach == nil {\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToAPIAttachment(ctx.Repo.Repository, attach))\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WithExact(exact *bool) *ReadStorageV1alpha1VolumeAttachmentParams {\n\to.SetExact(exact)\n\treturn o\n}", "func (d DobsClient) AttachVolume(ctx Context, volumeID string, dropletID string) (error) {\n\tdropletIDI, err := strconv.Atoi(dropletID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvol, _, err := d.GodoClient.Storage.GetVolume(ctx, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(vol.DropletIDs) > 0 {\n\t\totherDropletID := vol.DropletIDs[0]\n\t\tif otherDropletID == dropletIDI {\n\t\t\tlog.Printf(\"Volume %s already attached to this droplet, skipping attach\\n\", volumeID)\n\t\t\treturn nil\n\t\t}\n\t\t\n\t\treturn fmt.Errorf(\"Volume %s already attached to different droplet %d\", volumeID, otherDropletID)\n\t}\n\n\taction, _, err := d.GodoClient.StorageActions.Attach(ctx, volumeID, dropletIDI)\t\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.waitForAction(ctx, volumeID, action)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (pstFile *File) GetAttachments(message *Message, formatType string, encryptionType string) ([]Attachment, error) {\n\tif !message.HasAttachments() {\n\t\treturn nil, nil\n\t}\n\n\tattachmentsTableContext, err := pstFile.GetAttachmentsTableContext(message, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar attachments []Attachment\n\n\tfor i := 0; i < len(attachmentsTableContext); i++ {\n\t\tattachment, err := pstFile.GetAttachment(message, i, formatType, encryptionType)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tattachments = append(attachments, attachment)\n\t}\n\n\treturn attachments, nil\n}", "func GetVolumeInfo(awsSession *session.Session, targets []string) (info []VolInfo, err error) {\n\tclient := ec2.New(awsSession)\n\tinfo = make([]VolInfo, 0)\n\n\tfilters := make([]*ec2.Filter, 0)\n\n\tparams := &ec2.DescribeVolumesInput{}\n\n\t// process targets and massage them into aws type variables\n\tif targets != nil {\n\t\tawsnames := make([]*string, 0)\n\n\t\tfor _, name := range targets {\n\t\t\tawsnames = append(awsnames, aws.String(name))\n\t\t}\n\n\t\tnameFilter := ec2.Filter{\n\t\t\tName: aws.String(\"attachment.instance-id\"),\n\t\t\tValues: awsnames,\n\t\t}\n\n\t\tfilters = append(filters, &nameFilter)\n\t}\n\n\t// add the filters if they exist\n\tif len(filters) > 0 {\n\t\tparams.Filters = filters\n\t}\n\n\t// actually call aws for volume information\n\tresult, err := client.DescribeVolumes(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, \"error searching volumes\")\n\t\t\t\treturn info, err\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.Wrapf(err, \"error searching volumes\")\n\t\t\treturn info, err\n\t\t}\n\t}\n\n\t// loop through the resulting info, and set up the info we need\n\tfor _, vol := range result.Volumes {\n\t\tinstanceId := *vol.Attachments[0].InstanceId\n\t\tdeviceName := *vol.Attachments[0].Device\n\n\t\ti := VolInfo{\n\t\t\tInstanceId: instanceId,\n\t\t\tDeviceName: deviceName,\n\t\t\tVolumeId: *vol.VolumeId,\n\t\t}\n\n\t\tinfo = append(info, i)\n\t}\n\n\treturn info, err\n}", "func (a *EmailControllerApiService) GetAttachmentMetaData(ctx _context.Context, attachmentId string, emailId string) (AttachmentMetaData, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AttachmentMetaData\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/emails/{emailId}/attachments/{attachmentId}/metadata\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"attachmentId\"+\"}\", _neturl.QueryEscape(parameterToString(attachmentId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"emailId\"+\"}\", _neturl.QueryEscape(parameterToString(emailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v AttachmentMetaData\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func GetVolume(id string, name string) (*xmsv3.Volume, error) {\n\tvolume, err := xms.GetVolume(id, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn volume.Content, nil\n}", "func GetAttachmentData() []*types.Attachment {\n\treturn []*types.Attachment{\n\t\t{\n\t\t\tID: \"fakeID0\",\n\t\t\tName: \"fakeName0\",\n\t\t\tUploadURL: \"fakeUploadURL0\",\n\t\t\tDownloadURL: \"fakeDownloadURL0\",\n\t\t\tUploaded: true,\n\t\t},\n\t\t{\n\t\t\tID: \"fakeID1\",\n\t\t\tName: \"fakeName1\",\n\t\t\tUploadURL: \"fakeUploadURL1\",\n\t\t\tDownloadURL: \"fakeDownloadURL1\",\n\t\t\tUploaded: false,\n\t\t},\n\t}\n}", "func (p *Poloniex) GetVolume(ctx context.Context) (interface{}, error) {\n\tvar resp interface{}\n\tpath := \"/public?command=return24hVolume\"\n\n\treturn resp, p.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}", "func isVolumePublished(canAtMultiNode bool, attachReq *model.VolumeAttachmentSpec,\n\tmetadata map[string]string) (*model.VolumeAttachmentSpec, error) {\n\tglog.V(5).Infof(\"start to isVolumePublished, canAtMultiNode = %v, attachReq = %v\",\n\t\tcanAtMultiNode, attachReq)\n\n\tattachments, err := Client.ListVolumeAttachments()\n\tif err != nil {\n\t\tglog.V(5).Info(\"ListVolumeAttachments failed: \" + err.Error())\n\t\treturn nil, status.Error(codes.FailedPrecondition, err.Error())\n\t}\n\n\tfor _, attachSpec := range attachments {\n\t\tif attachSpec.VolumeId == attachReq.VolumeId {\n\t\t\tif attachSpec.Host != attachReq.Host {\n\t\t\t\tif !canAtMultiNode {\n\t\t\t\t\tmsg := fmt.Sprintf(\"the volume %s has been published to another node and does not have MULTI_NODE volume capability\",\n\t\t\t\t\t\tattachReq.VolumeId)\n\t\t\t\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Opensds does not have volume_capability and readonly parameters,\n\t\t\t\t// but needs to check other parameters to determine compatibility?\n\t\t\t\tif attachSpec.Platform == attachReq.Platform &&\n\t\t\t\t\tattachSpec.OsType == attachReq.OsType &&\n\t\t\t\t\tattachSpec.Initiator == attachReq.Initiator &&\n\t\t\t\t\tisStringMapEqual(attachSpec.Metadata, metadata) &&\n\t\t\t\t\tattachSpec.AccessProtocol == attachReq.AccessProtocol {\n\t\t\t\t\tglog.V(5).Info(\"Volume published and is compatible\")\n\n\t\t\t\t\treturn attachSpec, nil\n\t\t\t\t}\n\n\t\t\t\tglog.Error(\"Volume published but is incompatible, incompatible attachement Id = \" + attachSpec.Id)\n\t\t\t\treturn nil, status.Error(codes.AlreadyExists, \"Volume published but is incompatible\")\n\t\t\t}\n\t\t}\n\t}\n\n\tglog.V(5).Info(\"Need to create a new attachment\")\n\treturn nil, nil\n}", "func (a *Client) GetAttachmentsID(params *GetAttachmentsIDParams, authInfo runtime.ClientAuthInfoWriter) (*GetAttachmentsIDOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAttachmentsIDParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetAttachmentsID\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/attachments/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetAttachmentsIDReader{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.(*GetAttachmentsIDOK)\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 GetAttachmentsID: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (vs *volumeSet) getVolume(id string) *api.Volume {\n\treturn vs.volumes[id].volume\n}", "func (digitalocean DigitalOcean) GetVolume(id string) (*godo.Volume, error) {\n\tdoc, err := DigitalOceanClient()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvolume, _, err := doc.client.Storage.GetVolume(doc.context, id)\n\n\tif err != nil {\n\t\t//log.Fatal(err)\n\t}\n\n\treturn volume, err\n}", "func getSqliteFileAttach(c *echo.Context) error {\n\tsf := SqliteFile{DeviceID: c.Param(\"DeviceID\")}\n\thas, err := g_engine.Get(&sf)\n\tif err != nil {\n\t\treturn jsonResp(c, err.Error())\n\t}\n\tif !has {\n\t\treturn jsonResp(c, \"not exists\")\n\t}\n\n\tc.Response().Header().Set(echo.ContentDisposition, \"attachment; filename=\"+sf.Name)\n\n\thttp.ServeContent(c.Response(), c.Request(), sf.Name, sf.Mtime, bytes.NewReader(sf.Context))\n\n\treturn nil\n}", "func Get(c *golangsdk.ServiceClient, server_id string, volume_id string) (r GetResult) {\n\t_, r.Err = c.Get(getURL(c, server_id, volume_id), &r.Body, nil)\n\treturn\n}", "func DeleteAttach(Ob map[string]interface{}, userId string) *utils.Response {\n\tvar (\n\t\tattach *model.Attachment\n\t\tpath []interface{}\n\t\tnotePath string\n\t\tattlist []string\n\t)\n\tif _, ok := Ob[\"Uuid\"].([]interface{}); ok {\n\t\tpath = Ob[\"Uuid\"].([]interface{})\n\t} else {\n\t\treturn utils.WITHOUT_PARAMETERS\n\t}\n\tif _, ok := Ob[\"NotePath\"].(string); ok {\n\t\tnotePath = Ob[\"NotePath\"].(string)\n\t} else {\n\t\treturn utils.WITHOUT_PARAMETERS\n\t}\n\tattachone := model.NewAttachmentList(notePath)\n\tattachList, err := attachone.GetList()\n\tif err != nil {\n\t\tbeego.Error(err)\n\t\treturn utils.NewResponse(utils.SYSTEM_CODE, err.Error(), nil)\n\t}\n\tfor i := 0; i < len(attachList); i++ {\n\t\tattlist = append(attlist, attachList[i].ID)\n\t}\n\tif len(path) == 0 {\n\t\tif err := DeleteAttachment(notePath); err != nil {\n\t\t\tbeego.Error(err)\n\t\t\treturn utils.NewResponse(utils.SYSTEM_CODE, err.Error(), nil)\n\t\t}\n\t}\n\tfor i := 0; i < len(path); i++ {\n\t\tid := path[i].(string)\n\t\tattach = model.NewAttachment(id)\n\t\tattach.NotePath = notePath\n\t\tif !attach.IsExist() {\n\t\t\treturn utils.ATTACH_NOT_EXIST\n\t\t}\n\t\tif utils.CheckString(attlist, id) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := attach.Remove(); err != nil {\n\t\t\tbeego.Error(err)\n\t\t\treturn utils.NewResponse(utils.SYSTEM_CODE, err.Error(), nil)\n\t\t}\n\t\tcloudBoxService := GetCloudBoxService()\n\t\tcloudBoxService.DeleteQiuniu(id)\n\n\t}\n\n\tt := struct {\n\t\tResult string\n\t}{\"success\"}\n\treturn utils.NewResponse(0, \"\", t)\n}", "func (a *HyperflexApiService) GetHyperflexVolumeByMoid(ctx context.Context, moid string) ApiGetHyperflexVolumeByMoidRequest {\n\treturn ApiGetHyperflexVolumeByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (ec *executionContext) _Attachment_id(ctx context.Context, field graphql.CollectedField, obj *Attachment) (ret graphql.Marshaler) {\n\tctx = ec.Tracer.StartFieldExecution(ctx, field)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t\tec.Tracer.EndFieldExecution(ctx)\n\t}()\n\trctx := &graphql.ResolverContext{\n\t\tObject: \"Attachment\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: false,\n\t}\n\tctx = graphql.WithResolverContext(ctx, rctx)\n\tctx = ec.Tracer.StartFieldResolverExecution(ctx, rctx)\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !ec.HasError(rctx) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\trctx.Result = res\n\tctx = ec.Tracer.StartFieldChildExecution(ctx)\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func getVolumeDetails(svc *ec2.Client, output *ec2.DescribeVolumesOutput, region string) ([]*resource.Resource, error) {\n\tvar ebsVolumes []*resource.Resource\n\tebsLogger.Debug(\"Fetching Ebs Details\")\n\tfor _, volume := range output.Volumes {\n\t\ttags := make(resource.Tags)\n\t\tfor _, t := range volume.Tags {\n\t\t\ttags[*t.Key] = *t.Value\n\t\t}\n\t\t// We need the creation-date when parsing Tags for relative defintions\n\t\t// Ebs Volumes Launch Time is not the creation date. It's the time it was last launched.\n\t\t// TODO To get the creation date we might want to get the creation date of the EBS attached to the Ebs instead\n\t\ttags[\"creation-date\"] = (*volume.CreateTime).String()\n\t\tebsResource := NewResource(*volume.VolumeId, ec2Name)\n\t\tebsResource.Region = region\n\t\t// Get CreationDate by getting LaunchTime of attached Volume\n\t\tebsResource.CreationDate = *volume.CreateTime\n\t\tebsResource.Tags = tags\n\t\tebsResource.Status = resource.Running\n\t\tif len(volume.Attachments) == 0 {\n\t\t\tebsResource.Status = resource.Unused\n\t\t}\n\t\tebsVolumes = append(ebsVolumes, ebsResource)\n\t}\n\n\treturn ebsVolumes, nil\n}", "func (o *GetAttachmentParams) WithContext(ctx context.Context) *GetAttachmentParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (a *EmailControllerApiService) DownloadAttachment(ctx _context.Context, attachmentId string, emailId string, localVarOptionals *DownloadAttachmentOpts) (string, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue string\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/emails/{emailId}/attachments/{attachmentId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"attachmentId\"+\"}\", _neturl.QueryEscape(parameterToString(attachmentId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"emailId\"+\"}\", _neturl.QueryEscape(parameterToString(emailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.ApiKey.IsSet() {\n\t\tlocalVarQueryParams.Add(\"apiKey\", parameterToString(localVarOptionals.ApiKey.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/octet-stream\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v string\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (*VolumeAttachment) Descriptor() ([]byte, []int) {\n\treturn file_msgType_proto_rawDescGZIP(), []int{9}\n}", "func (c *PostClient) QueryAttachments(po *Post) *PostAttachmentQuery {\n\tquery := &PostAttachmentQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := po.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(post.Table, post.FieldID, id),\n\t\t\tsqlgraph.To(postattachment.Table, postattachment.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, post.AttachmentsTable, post.AttachmentsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(po.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (c *Core) AttachVolume(id types.VolumeID, extra map[string]string) (*types.Volume, error) {\n\tc.lock.Lock(id.Name)\n\tdefer c.lock.Unlock(id.Name)\n\n\tv, dv, err := c.getVolumeDriver(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := driver.Contexts()\n\n\t// merge extra to volume spec extra.\n\tfor key, value := range extra {\n\t\tv.Spec.Extra[key] = value\n\t}\n\n\tif d, ok := dv.(driver.AttachDetach); ok {\n\t\tif err := d.Attach(ctx, v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// update meta info.\n\tif err := c.store.Put(v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (r *PostAttachmentsCollectionRequest) Get(ctx context.Context) ([]Attachment, error) {\n\treturn r.GetN(ctx, 0)\n}", "func (driver *Driver) Attach(volumeName, instanceID string) (string, error) {\n\tvolumes, err := driver.sdm.GetVolume(\"\", volumeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase len(volumes) == 0:\n\t\treturn \"\", errors.New(\"No volumes returned by name\")\n\tcase len(volumes) > 1:\n\t\treturn \"\", errors.New(\"Multiple volumes returned by name\")\n\t}\n\n\t_, err = driver.sdm.AttachVolume(true, volumes[0].VolumeID, instanceID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvolumes, err = driver.sdm.GetVolume(\"\", volumeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn volumes[0].NetworkName, nil\n}", "func NewGetBootVolumeAttachmentParamsWithHTTPClient(client *http.Client) *GetBootVolumeAttachmentParams {\n\tvar ()\n\treturn &GetBootVolumeAttachmentParams{\n\t\tHTTPClient: client,\n\t}\n}", "func (client VolumesClient) Get(ctx context.Context, location string, storageSubSystem string, storagePool string, volume string) (result Volume, err error) {\n\treq, err := client.GetPreparer(ctx, location, storageSubSystem, storagePool, volume)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (d *DefaultDriver) AttachVolume(volumeID string) (string, error) {\n\treturn \"\", &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"CreateVolume()\",\n\t}\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WithHTTPClient(client *http.Client) *ReadStorageV1alpha1VolumeAttachmentParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func LookupVpcAttachment(ctx *pulumi.Context, args *GetVpcAttachmentArgs) (*GetVpcAttachmentResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"filters\"] = args.Filters\n\t\tinputs[\"id\"] = args.Id\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\toutputs, err := ctx.Invoke(\"aws:ec2transitgateway/getVpcAttachment:getVpcAttachment\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetVpcAttachmentResult{\n\t\tDnsSupport: outputs[\"dnsSupport\"],\n\t\tFilters: outputs[\"filters\"],\n\t\tId: outputs[\"id\"],\n\t\tIpv6Support: outputs[\"ipv6Support\"],\n\t\tSubnetIds: outputs[\"subnetIds\"],\n\t\tTags: outputs[\"tags\"],\n\t\tTransitGatewayId: outputs[\"transitGatewayId\"],\n\t\tVpcId: outputs[\"vpcId\"],\n\t\tVpcOwnerId: outputs[\"vpcOwnerId\"],\n\t}, nil\n}", "func NewGetBootVolumeAttachmentParams() *GetBootVolumeAttachmentParams {\n\tvar ()\n\treturn &GetBootVolumeAttachmentParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (m *Client) GetAttachment(arg0 context.Context, arg1 int64) (zendesk.Attachment, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAttachment\", arg0, arg1)\n\tret0, _ := ret[0].(zendesk.Attachment)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.Exact != nil {\n\n\t\t// query param exact\n\t\tvar qrExact bool\n\t\tif o.Exact != nil {\n\t\t\tqrExact = *o.Exact\n\t\t}\n\t\tqExact := swag.FormatBool(qrExact)\n\t\tif qExact != \"\" {\n\t\t\tif err := r.SetQueryParam(\"exact\", qExact); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.Export != nil {\n\n\t\t// query param export\n\t\tvar qrExport bool\n\t\tif o.Export != nil {\n\t\t\tqrExport = *o.Export\n\t\t}\n\t\tqExport := swag.FormatBool(qrExport)\n\t\tif qExport != \"\" {\n\t\t\tif err := r.SetQueryParam(\"export\", qExport); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// path param name\n\tif err := r.SetPathParam(\"name\", o.Name); err != nil {\n\t\treturn err\n\t}\n\n\tif o.Pretty != nil {\n\n\t\t// query param pretty\n\t\tvar qrPretty string\n\t\tif o.Pretty != nil {\n\t\t\tqrPretty = *o.Pretty\n\t\t}\n\t\tqPretty := qrPretty\n\t\tif qPretty != \"\" {\n\t\t\tif err := r.SetQueryParam(\"pretty\", qPretty); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *StackEbrc) ListVolumeAttachments(serverID string) ([]abstract.VolumeAttachment, fail.Error) {\n\tvms, err := s.findVmNames()\n\tif err != nil {\n\t\treturn []abstract.VolumeAttachment{}, err\n\t}\n\n\t_, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn []abstract.VolumeAttachment{}, fail.Wrap(err, fmt.Sprintf(\"Error deleting volume\"))\n\t}\n\n\tvar attachments []abstract.VolumeAttachment\n\n\tfor _, vmname := range vms {\n\t\tvm, err := s.findVMByName(vmname)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ittem := range vm.VM.VirtualHardwareSection.Item {\n\t\t\tif ittem != nil {\n\t\t\t\tif ittem.ResourceType == 17 {\n\t\t\t\t\tdadr := ittem.HostResource[0].Disk\n\t\t\t\t\tthedi, err := vdc.FindDiskByHREF(dadr)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\treid := abstract.VolumeAttachment{\n\t\t\t\t\t\tID: serverID + \":\" + thedi.Disk.Id,\n\t\t\t\t\t\tVolumeID: thedi.Disk.Id,\n\t\t\t\t\t\tServerID: serverID,\n\t\t\t\t\t}\n\n\t\t\t\t\tattachments = append(attachments, reid)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attachments, nil\n}", "func (s *VolumeListener) Attach(inctx context.Context, in *protocol.VolumeAttachmentRequest) (_ *googleprotobuf.Empty, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(inctx, &err)\n\tdefer fail.OnExitWrapError(inctx, &err, \"cannot attach volume\")\n\n\tempty := &googleprotobuf.Empty{}\n\tif s == nil {\n\t\treturn empty, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn empty, fail.InvalidParameterCannotBeNilError(\"in\")\n\t}\n\tif inctx == nil {\n\t\treturn nil, fail.InvalidParameterCannotBeNilError(\"inctx\")\n\t}\n\n\tvolumeRef, _ := srvutils.GetReference(in.GetVolume())\n\tif volumeRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for volume\")\n\t}\n\thostRef, _ := srvutils.GetReference(in.GetHost())\n\tif hostRef == \"\" {\n\t\treturn empty, fail.InvalidRequestError(\"neither name nor id given as reference for host\")\n\t}\n\tmountPath := in.GetMountPath()\n\n\tfilesystem := in.GetFormat()\n\tdoNotFormat := in.DoNotFormat\n\tdoNotMount := in.DoNotMount\n\n\tjob, xerr := PrepareJob(inctx, in.GetVolume().GetTenantId(), fmt.Sprintf(\"/volume/%s/host/%s/attach\", volumeRef, hostRef))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\thandler := VolumeHandler(job)\n\tif xerr = handler.Attach(volumeRef, hostRef, mountPath, filesystem, doNotFormat, doNotMount); xerr != nil {\n\t\treturn empty, xerr\n\t}\n\n\treturn empty, nil\n}", "func readVolume(devicebytes []byte, keyBlock uint16, debug int) (Volume, error) {\n\tv := Volume{\n\t\tkeyBlock: &VolumeDirectoryKeyBlock{},\n\t\tsubdirsByBlock: make(map[uint16]*Subdirectory),\n\t\tsubdirsByName: make(map[string]*Subdirectory),\n\t\tfirstSubdirBlocks: make(map[uint16]uint16),\n\t}\n\n\tif err := disk.UnmarshalBlock(devicebytes, v.keyBlock, keyBlock); err != nil {\n\t\treturn v, fmt.Errorf(\"cannot read first block of volume directory (block %d): %v\", keyBlock, err)\n\t}\n\t// if debug {\n\t// \tfmt.Fprintf(os.Stderr, \"keyblock: %#v\\n\", v.keyBlock)\n\t// }\n\n\tvbm, err := readVolumeBitMap(devicebytes, v.keyBlock.Header.BitMapPointer)\n\tif err != nil {\n\t\treturn v, err\n\t}\n\n\tv.bitmap = &vbm\n\n\t// if debug {\n\t// \tfmt.Fprintf(os.Stderr, \"volume bitmap: %#v\\n\", v.bitmap)\n\t// }\n\n\tfor block := v.keyBlock.Next; block != 0; block = v.blocks[len(v.blocks)-1].Next {\n\t\tvdb := VolumeDirectoryBlock{}\n\t\tif err := disk.UnmarshalBlock(devicebytes, &vdb, block); err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tv.blocks = append(v.blocks, &vdb)\n\t\tv.firstSubdirBlocks[block] = keyBlock\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \" firstSubdirBlocks[%d] → %d\\n\", block, keyBlock)\n\t\t}\n\t\t// if debug {\n\t\t// \tfmt.Fprintf(os.Stderr, \"block: %#v\\n\", vdb)\n\t\t// }\n\t}\n\n\tsdds := v.subdirDescriptors()\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"got %d top-level subdir descriptors\\n\", len(sdds))\n\t}\n\n\tfor i := 0; i < len(sdds); i++ {\n\t\tsdd := sdds[i]\n\t\tsub, err := readSubdirectory(devicebytes, sdd)\n\t\tif err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tv.subdirsByBlock[sdd.KeyPointer] = &sub\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \" subdirsByBlock[%d] → %q\\n\", sdd.KeyPointer, sub.keyBlock.Header.Name())\n\t\t}\n\t\tsdds = append(sdds, sub.subdirDescriptors()...)\n\t\tfor _, block := range sub.blocks {\n\t\t\tv.firstSubdirBlocks[block.block] = sdd.KeyPointer\n\t\t\tif debug > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \" firstSubdirBlocks[%d] → %d\\n\", block.block, sdd.KeyPointer)\n\t\t\t}\n\t\t}\n\t}\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"got %d total subdir descriptors\\n\", len(sdds))\n\t}\n\n\tfor _, sd := range v.subdirsByBlock {\n\t\tname := sd.keyBlock.Header.Name()\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \"processing subdir %q\\n\", name)\n\t\t}\n\t\tparentName, err := parentDirName(sd.keyBlock.Header.ParentPointer, keyBlock, v.subdirsByBlock, v.firstSubdirBlocks)\n\t\tif err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tif parentName != \"\" {\n\t\t\tname = parentName + \"/\" + name\n\t\t}\n\n\t\tv.subdirsByName[name] = sd\n\t}\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"subdirsByName:\\n\")\n\t\tfor k := range v.subdirsByName {\n\t\t\tfmt.Fprintf(os.Stderr, \" %s\\n\", k)\n\t\t}\n\t}\n\treturn v, nil\n}", "func (s *StackEbrc) CreateVolumeAttachment(request abstract.VolumeAttachmentRequest) (string, fail.Error) {\n\tlogrus.Debugf(\">>> stacks.ebrc::CreateVolumeAttachment(%s)\", request.Name)\n\tdefer logrus.Debugf(\"<<< stacks.ebrc::CreateVolumeAttachment(%s)\", request.Name)\n\n\tvm, err := s.findVMByID(request.HostID)\n\tif err != nil || utils.IsEmpty(vm) {\n\t\treturn \"\", fail.Wrap(err, fmt.Sprintf(\"Error creating attachment, vm empty\"))\n\t}\n\n\tdisk, err := s.findDiskByID(request.VolumeID)\n\tif err != nil || utils.IsEmpty(disk) {\n\t\treturn \"\", fail.Wrap(err, fmt.Sprintf(\"Error creating attachment, disk empty\"))\n\t}\n\n\tattask, err := vm.AttachDisk(&types.DiskAttachOrDetachParams{Disk: &types.Reference{HREF: disk.Disk.HREF}})\n\tif err != nil {\n\t\treturn \"\", fail.Wrap(err, fmt.Sprintf(\"Error creating attachment\"))\n\t}\n\n\terr = attask.WaitTaskCompletion()\n\tif err != nil {\n\t\treturn \"\", fail.Wrap(err, fmt.Sprintf(\"Error creating attachment\"))\n\t}\n\n\treturn getAttachmentID(request.HostID, request.VolumeID), nil\n}", "func Attachment(namespaceId, mosaicName string, quantity float64) base.Mosaic {\n\treturn base.Mosaic{\n\t\tMosaicID: base.MosaicID{\n\t\t\tNamespaceID: namespaceId,\n\t\t\tName: mosaicName,\n\t\t},\n\t\tQuantity: quantity,\n\t}\n}", "func (c *Core) getVolume(id types.VolumeID) (*types.Volume, error) {\n\tctx := driver.Contexts()\n\n\t// first, try to get volume from local store.\n\tobj, err := c.store.Get(id.Name)\n\tif err == nil {\n\t\tv, ok := obj.(*types.Volume)\n\t\tif !ok {\n\t\t\treturn nil, volerr.ErrVolumeNotFound\n\t\t}\n\n\t\t// get the volume driver.\n\t\tdv, err := driver.Get(v.Spec.Backend)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// if the driver implements Getter interface.\n\t\tif d, ok := dv.(driver.Getter); ok {\n\t\t\tcurV, err := d.Get(ctx, id.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, volerr.ErrVolumeNotFound\n\t\t\t}\n\n\t\t\tv.Status.MountPoint = curV.Status.MountPoint\n\t\t}\n\n\t\treturn v, nil\n\t}\n\n\tif err != metastore.ErrObjectNotFound {\n\t\treturn nil, err\n\t}\n\n\t// scan all drivers\n\tlogrus.Debugf(\"probing all drivers for volume with name(%s)\", id.Name)\n\tdrivers, err := driver.GetAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, dv := range drivers {\n\t\td, ok := dv.(driver.Getter)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tv, err := d.Get(ctx, id.Name)\n\t\tif err != nil {\n\t\t\t// not found, ignore it\n\t\t\tcontinue\n\t\t}\n\n\t\t// store volume meta\n\t\tif err := c.store.Put(v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn v, nil\n\t}\n\n\treturn nil, volerr.ErrVolumeNotFound\n}", "func (cl *Client) gceVolumeAttach(ctx context.Context, vaa *csp.VolumeAttachArgs, vid string) (*csp.Volume, error) {\n\tcomputeService, err := cl.getComputeService(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdeviceName := vid\n\tif !strings.HasPrefix(deviceName, nuvoNamePrefix) {\n\t\tdeviceName = nuvoNamePrefix + vid\n\t}\n\tdisk := &compute.AttachedDisk{\n\t\tDeviceName: deviceName,\n\t\tSource: fmt.Sprintf(diskSourceURL, cl.projectID, cl.attrs[AttrZone].Value, deviceName),\n\t}\n\top, err := computeService.Instances().AttachDisk(cl.projectID, cl.attrs[AttrZone].Value, vaa.NodeIdentifier, disk).Context(ctx).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = cl.waitForOperation(ctx, op); err != nil {\n\t\treturn nil, err\n\t}\n\tvol, err := cl.vr.gceVolumeGet(ctx, vid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn vol, nil\n}", "func (m *ChatMessage) GetAttachments()([]ChatMessageAttachmentable) {\n return m.attachments\n}", "func (o *GetAttachmentParams) WithTimeout(timeout time.Duration) *GetAttachmentParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (client *Client) DeleteVolumeAttachment(serverID, id string) error {\n\tva, err := client.GetVolumeAttachment(serverID, id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = volumeattach.Delete(client.Compute, serverID, id).ExtractErr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\tmtdVol, err := metadata.LoadVolume(providers.FromClient(client), id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = mtdVol.Detach(va)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\treturn nil\n}", "func (s *DataStore) GetLHVolumeAttachmentRO(name string) (*longhorn.VolumeAttachment, error) {\n\treturn s.lhVALister.VolumeAttachments(s.namespace).Get(name)\n}", "func (c *UnsavedPostAttachmentClient) Get(ctx context.Context, id int) (*UnsavedPostAttachment, error) {\n\treturn c.Query().Where(unsavedpostattachment.ID(id)).Only(ctx)\n}", "func (o *GetBootVolumeAttachmentParams) WithTimeout(timeout time.Duration) *GetBootVolumeAttachmentParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (o *GetBootVolumeAttachmentParams) WithHTTPClient(client *http.Client) *GetBootVolumeAttachmentParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func (o *GetBootVolumeAttachmentParams) WithContext(ctx context.Context) *GetBootVolumeAttachmentParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (d *Data) GetVolume(v dvid.VersionID, vox *Labels, supervoxels bool, scale uint8, roiname dvid.InstanceName) ([]byte, error) {\n\tr, err := imageblk.GetROI(v, roiname, vox)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := d.GetLabels(v, supervoxels, scale, vox, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn vox.Data(), nil\n}", "func (o *GetAttachmentParams) WithAttachmentID(attachmentID *string) *GetAttachmentParams {\n\to.SetAttachmentID(attachmentID)\n\treturn o\n}", "func (c *BlockVolumeClient) Details(id string) (*BlockVolume, error) {\n\tvar result BlockVolume\n\tparams := BlockVolumeParams{UniqID: id}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/details\", params, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}", "func (s stack) ListVolumeAttachments(ctx context.Context, serverRef string) ([]*abstract.VolumeAttachment, fail.Error) {\n\tif valid.IsNil(s) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\treturn nil, fail.NotImplementedError(\"implement me\")\n}", "func (digitalocean DigitalOcean) DetachVolume(volumeID string) error {\n\tdoc, err := DigitalOceanClient()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = doc.client.Storage.DeleteVolume(doc.context, volumeID)\n\n\treturn err\n}", "func (srv *VolumeService) Get(ref string) (*api.Volume, error) {\n\tvolumes, err := srv.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, volume := range volumes {\n\t\tif volume.ID == ref || volume.Name == ref {\n\t\t\treturn &volume, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Volume '%s' does not exists\", ref)\n}", "func (_m *Client) GetAttachment(_a0 context.Context, _a1 build.GetAttachmentArgs) (io.ReadCloser, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 io.ReadCloser\n\tif rf, ok := ret.Get(0).(func(context.Context, build.GetAttachmentArgs) io.ReadCloser); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(io.ReadCloser)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.GetAttachmentArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (o VolumeV2Output) Attachments() VolumeV2AttachmentArrayOutput {\n\treturn o.ApplyT(func(v *VolumeV2) VolumeV2AttachmentArrayOutput { return v.Attachments }).(VolumeV2AttachmentArrayOutput)\n}", "func NewGetAttachmentParams() *GetAttachmentParams {\n\tvar ()\n\treturn &GetAttachmentParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (bt *BlipTester) SendRevWithAttachment(input SendRevWithAttachmentInput) (sent bool, req, res *blip.Message) {\n\n\tdefer func() {\n\t\t// Clean up all profile handlers that are registered as part of this test\n\t\tdelete(bt.blipContext.HandlerForProfile, \"getAttachment\")\n\t}()\n\n\t// Create a doc with an attachment\n\tmyAttachment := db.DocAttachment{\n\t\tContentType: \"application/json\",\n\t\tDigest: input.attachmentDigest,\n\t\tLength: input.attachmentLength,\n\t\tRevpos: 1,\n\t\tStub: true,\n\t}\n\n\tdoc := NewRestDocument()\n\tif len(input.body) > 0 {\n\t\tunmarshalErr := json.Unmarshal(input.body, &doc)\n\t\tif unmarshalErr != nil {\n\t\t\tpanic(fmt.Sprintf(\"Error unmarshalling body into restDocument. Error: %v\", unmarshalErr))\n\t\t}\n\t}\n\n\tdoc.SetAttachments(db.AttachmentMap{\n\t\tinput.attachmentName: &myAttachment,\n\t})\n\n\tdocBody, err := base.JSONMarshal(doc)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error marshalling doc. Error: %v\", err))\n\t}\n\n\tgetAttachmentWg := sync.WaitGroup{}\n\n\tbt.blipContext.HandlerForProfile[\"getAttachment\"] = func(request *blip.Message) {\n\t\tdefer getAttachmentWg.Done()\n\t\tif request.Properties[\"digest\"] != myAttachment.Digest {\n\t\t\tpanic(fmt.Sprintf(\"Unexpected digest. Got: %v, expected: %v\", request.Properties[\"digest\"], myAttachment.Digest))\n\t\t}\n\t\tresponse := request.Response()\n\t\tresponse.SetBody([]byte(input.attachmentBody))\n\t}\n\n\t// Push a rev with an attachment.\n\tgetAttachmentWg.Add(1)\n\tsent, req, res, _ = bt.SendRevWithHistory(\n\t\tinput.docId,\n\t\tinput.revId,\n\t\tinput.history,\n\t\tdocBody,\n\t\tblip.Properties{},\n\t)\n\t// Expect a callback to the getAttachment endpoint\n\tgetAttachmentWg.Wait()\n\n\treturn sent, req, res\n\n}", "func (util *PortworxVolumeUtil) AttachVolume(m *portworxVolumeMounter) (string, error) {\n\tdriver, err := util.getPortworxDriver(m.plugin.host, true /*localOnly*/)\n\tif err != nil || driver == nil {\n\t\tglog.Errorf(\"Failed to get portworx driver. Err: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tdevicePath, err := driver.Attach(m.volName)\n\tif err != nil {\n\t\tglog.Errorf(\"Error attaching Portworx Volume (%v): %v\", m.volName, err)\n\t\treturn \"\", err\n\t}\n\treturn devicePath, nil\n}", "func (a *HetznerVolumes) AttachVolume(volume *volumes.Volume) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tvolumeID, err := strconv.Atoi(volume.ProviderID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert volume id %q to int: %w\", volume.ProviderID, err)\n\t}\n\n\thetznerVolume, _, err := a.hcloudClient.Volume.GetByID(ctx, volumeID)\n\tif err != nil || hetznerVolume == nil {\n\t\treturn fmt.Errorf(\"failed to get info for volume id %q: %w\", volume.ProviderID, err)\n\t}\n\n\tif hetznerVolume.Server != nil {\n\t\tif hetznerVolume.Server.ID != a.server.ID {\n\t\t\treturn fmt.Errorf(\"found volume %s(%d) attached to a different server: %d\", hetznerVolume.Name, hetznerVolume.ID, hetznerVolume.Server.ID)\n\t\t}\n\n\t\tklog.V(2).Infof(\"Attached volume %s(%d) to the running server\", hetznerVolume.Name, hetznerVolume.ID)\n\n\t\tvolume.LocalDevice = fmt.Sprintf(\"%s%d\", localDevicePrefix, hetznerVolume.ID)\n\t\treturn nil\n\t}\n\n\tklog.V(2).Infof(\"Attaching volume %s(%d) to the running server\", hetznerVolume.Name, hetznerVolume.ID)\n\n\taction, _, err := a.hcloudClient.Volume.Attach(ctx, hetznerVolume, a.server)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to attach volume %s(%d): %w\", hetznerVolume.Name, hetznerVolume.ID, err)\n\t}\n\n\t_, errCh := a.hcloudClient.Action.WatchProgress(ctx, action)\n\tif err := <-errCh; err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for volume to %s(%d) be ready: %w\", hetznerVolume.Name, hetznerVolume.ID, err)\n\t}\n\n\treturn nil\n}", "func (ctrl Attachment) List(ctx context.Context, r *request.AttachmentList) (interface{}, error) {\n\tif !auth.GetIdentityFromContext(ctx).Valid() {\n\t\treturn nil, errors.New(\"Unauthorized\")\n\t}\n\n\tf := types.AttachmentFilter{\n\t\tNamespaceID: r.NamespaceID,\n\t\tKind: r.Kind,\n\t\tModuleID: r.ModuleID,\n\t\tRecordID: r.RecordID,\n\t\tFieldName: r.FieldName,\n\t\t// Filter: r.Filter,\n\t\tPerPage: r.PerPage,\n\t\tPage: r.Page,\n\t\t// Sort: r.Sort,\n\t}\n\n\tset, filter, err := ctrl.attachment.With(ctx).Find(f)\n\treturn ctrl.makeFilterPayload(ctx, set, filter, err)\n}", "func (o VpcAttachmentOutput) AttachmentId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VpcAttachment) pulumi.StringOutput { return v.AttachmentId }).(pulumi.StringOutput)\n}", "func (d DobsClient) GetVolume(ctx Context, name string) (*APIVolume, error) {\n\n\tapiVolume, err := d.getVolumeByName(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvol := &APIVolume{\n\t\tName: apiVolume.Name,\n\t\tID: apiVolume.ID,\n\t\t// DropletID: apiVolume.DropletIDs[0],\n\t}\n\n\treturn vol, nil\n}", "func GetDownloadAttachmentData() map[string]string {\n\treturn map[string]string{\n\t\t\"fakeEndpoint\": \"/blueprint/attachments/fakeID1\",\n\t\t\"fakeAttachmentDir\": \"/tmp/fakeFolderID1/attachments\",\n\t}\n}", "func (client *Client) GetVolume(id string) (*api.Volume, error) {\n\tvol, err := volumes.Get(client.Volume, id).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting volume: %s\", ProviderErrorToString(err))\n\t}\n\tav := api.Volume{\n\t\tID: vol.ID,\n\t\tName: vol.Name,\n\t\tSize: vol.Size,\n\t\tSpeed: client.getVolumeSpeed(vol.VolumeType),\n\t\tState: toVolumeState(vol.Status),\n\t}\n\treturn &av, nil\n}", "func (c *Core) DetachVolume(id types.VolumeID, extra map[string]string) (*types.Volume, error) {\n\tc.lock.Lock(id.Name)\n\tdefer c.lock.Unlock(id.Name)\n\n\tv, dv, err := c.getVolumeDriver(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := driver.Contexts()\n\n\t// merge extra to volume spec extra.\n\tfor key, value := range extra {\n\t\tv.Spec.Extra[key] = value\n\t}\n\n\t// if volume has referance, skip to detach volume.\n\tref := v.Option(types.OptionRef)\n\tif d, ok := dv.(driver.AttachDetach); ok && ref == \"\" {\n\t\tif err := d.Detach(ctx, v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// update meta info.\n\tif err := c.store.Put(v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (c *BinaryFileClient) Get(ctx context.Context, id int) (*BinaryFile, error) {\n\treturn c.Query().Where(binaryfile.ID(id)).Only(ctx)\n}", "func (db *DB) GetAttachmentMeta(ctx context.Context, docID, rev, filename string) (*Attachment, error) {\n\tif metaer, ok := db.driverDB.(driver.AttachmentMetaer); ok {\n\t\tcType, md5sum, err := metaer.GetAttachmentMeta(ctx, docID, rev, filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &Attachment{\n\t\t\tFilename: filename,\n\t\t\tContentType: cType,\n\t\t\tMD5: MD5sum(md5sum),\n\t\t}, nil\n\t}\n\tatt, err := db.GetAttachment(ctx, docID, rev, filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_ = att.Close()\n\treturn &Attachment{\n\t\tFilename: att.Filename,\n\t\tContentType: att.ContentType,\n\t\tMD5: att.MD5,\n\t}, nil\n}", "func (s *stencilOverdraw) getDepthAttachment(a arena.Arena,\n\trpInfo RenderPassObjectʳ,\n) (VkAttachmentDescription, uint32, error) {\n\tif rpInfo.SubpassDescriptions().Len() == 0 {\n\t\treturn NilVkAttachmentDescription, 0,\n\t\t\tfmt.Errorf(\"RenderPass %v has no subpasses\",\n\t\t\t\trpInfo.VulkanHandle())\n\t}\n\t// depth attachment: don't support them not all using the same one for now\n\tattachment0 := rpInfo.SubpassDescriptions().Get(0).DepthStencilAttachment()\n\tfor i := uint32(1); i < uint32(rpInfo.SubpassDescriptions().Len()); i++ {\n\t\tattachment := rpInfo.SubpassDescriptions().Get(i).DepthStencilAttachment()\n\t\tvar match bool\n\t\tif attachment0.IsNil() {\n\t\t\tmatch = attachment.IsNil()\n\t\t} else {\n\t\t\tmatch = !attachment.IsNil() &&\n\t\t\t\tattachment0.Attachment() == attachment.Attachment()\n\t\t}\n\t\tif !match {\n\t\t\t// TODO: Handle using separate depth attachments (make\n\t\t\t// a separate image for each one and combine them at\n\t\t\t// the end perhaps?)\n\t\t\treturn NilVkAttachmentDescription, 0, fmt.Errorf(\n\t\t\t\t\"The subpasses don't have matching depth attachments\")\n\t\t}\n\t}\n\tif attachment0.IsNil() ||\n\t\t// VK_ATTACHMENT_UNUSED\n\t\tattachment0.Attachment() == ^uint32(0) {\n\t\treturn NilVkAttachmentDescription, ^uint32(0), nil\n\t}\n\n\tattachmentDesc, ok := rpInfo.AttachmentDescriptions().Lookup(\n\t\tattachment0.Attachment(),\n\t)\n\tif !ok {\n\t\treturn NilVkAttachmentDescription, 0,\n\t\t\tfmt.Errorf(\"Invalid depth attachment\")\n\t}\n\n\treturn attachmentDesc, attachment0.Attachment(), nil\n}", "func (s *Stack) GetVolume(id string) (*resources.Volume, error) {\n\tif s == nil {\n\t\treturn nil, scerr.InvalidInstanceError()\n\t}\n\tif id == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"id\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, fmt.Sprintf(\"(%s)\", id), true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tr := volumesv2.Get(s.VolumeClient, id)\n\tvolume, err := r.Extract()\n\tif err != nil {\n\t\tif _, ok := err.(gc.ErrDefault404); ok {\n\t\t\treturn nil, resources.ResourceNotFoundError(\"volume\", id)\n\t\t}\n\t\treturn nil, scerr.Wrap(err, fmt.Sprintf(\"error getting volume: %s\", ProviderErrorToString(err)))\n\t}\n\n\tav := resources.Volume{\n\t\tID: volume.ID,\n\t\tName: volume.Name,\n\t\tSize: volume.Size,\n\t\tSpeed: s.getVolumeSpeed(volume.VolumeType),\n\t\tState: toVolumeState(volume.Status),\n\t}\n\treturn &av, nil\n}", "func (c *jsiiProxy_CfnVolume) GetAtt(attributeName *string) awscdk.Reference {\n\tvar returns awscdk.Reference\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"getAtt\",\n\t\t[]interface{}{attributeName},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *GetAttachmentParams) WithHTTPClient(client *http.Client) *GetAttachmentParams {\n\to.SetHTTPClient(client)\n\treturn o\n}" ]
[ "0.7880434", "0.66443956", "0.6614202", "0.6504912", "0.63013047", "0.614678", "0.5947405", "0.59435475", "0.5718704", "0.57057714", "0.56838596", "0.5580527", "0.55728596", "0.5570676", "0.55251056", "0.55097926", "0.5505074", "0.54819703", "0.54690534", "0.54568994", "0.54526603", "0.54523957", "0.5430437", "0.5397858", "0.53673077", "0.53616685", "0.53139967", "0.5310031", "0.52842665", "0.5280628", "0.5271861", "0.52703315", "0.52525544", "0.5243973", "0.5235136", "0.5215129", "0.52087325", "0.5199101", "0.5198894", "0.5195137", "0.5171979", "0.5160328", "0.51493055", "0.5142447", "0.51320213", "0.51245075", "0.5123713", "0.5118687", "0.509784", "0.5077426", "0.5063518", "0.50543785", "0.5046896", "0.5037264", "0.5032974", "0.50319135", "0.5027855", "0.50228107", "0.50133204", "0.49917927", "0.49906725", "0.49813932", "0.4979428", "0.4979358", "0.49779734", "0.49762818", "0.49700803", "0.49657282", "0.49655274", "0.49638337", "0.496002", "0.4951279", "0.4950316", "0.4944176", "0.49368596", "0.4935012", "0.49336264", "0.49261317", "0.49218094", "0.4907849", "0.49026483", "0.48954728", "0.48908734", "0.4890293", "0.4887913", "0.4885487", "0.48795217", "0.48638368", "0.48629972", "0.48603508", "0.48593658", "0.4859119", "0.4855813", "0.4854995", "0.48519993", "0.4847185", "0.48450476", "0.48446557", "0.4830222", "0.48260355" ]
0.81479675
0
getVolumeAndAttachmentByVolumeId Get volume and attachment by volumeId
func getVolumeAndAttachmentByVolumeId(volId string) (*model.VolumeSpec, *model.VolumeAttachmentSpec, error) { if r := getReplicationByVolume(volId); r != nil { volId = r.Metadata[KAttachedVolumeId] } vol, err := client.GetVolume(volId) if nil != err || nil == vol { msg := fmt.Sprintf("volume does not exist, %v", err) glog.Error(msg) return nil, nil, status.Error(codes.NotFound, msg) } attachments, err := client.ListVolumeAttachments() if nil != err { msg := fmt.Sprintf("list volume attachments failed, %v", err) glog.Error(msg) return nil, nil, status.Error(codes.NotFound, msg) } var attachment *model.VolumeAttachmentSpec hostName, err := connector.GetHostName() if err != nil { msg := fmt.Sprintf("faild to get host name %v", err) glog.Error(msg) return nil, nil, status.Error(codes.FailedPrecondition, msg) } for _, attach := range attachments { if attach.VolumeId == volId && attach.Host == hostName { attachment = attach break } } if attachment == nil { msg := fmt.Sprintf("attachment is not exist") glog.Error(msg) return nil, nil, status.Error(codes.FailedPrecondition, msg) } return vol, attachment, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getVolumeAndAttachment(volumeId string, attachmentId string) (*model.VolumeSpec, *model.VolumeAttachmentSpec, error) {\n\tvol, err := client.GetVolume(volumeId)\n\tif nil != err || nil == vol {\n\t\tmsg := fmt.Sprintf(\"volume %s does not exist, %v\", volumeId, err)\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.NotFound, msg)\n\t}\n\n\tattachment, err := client.GetVolumeAttachment(attachmentId)\n\tif nil != err || nil == attachment {\n\t\tmsg := fmt.Sprintf(\"the volume attachment %s does not exist, %v\", attachmentId, err)\n\t\tglog.Error(msg)\n\t\treturn nil, nil, status.Error(codes.FailedPrecondition, msg)\n\t}\n\n\treturn vol, attachment, nil\n}", "func (s *StackEbrc) GetVolumeAttachment(serverID, id string) (*abstract.VolumeAttachment, fail.Error) {\n\tlogrus.Debugf(\">>> stacks.ebrc::GetVolumeAttachment(%s)\", id)\n\tdefer logrus.Debugf(\"<<< stacks.ebrc::GetVolumeAttachment(%s)\", id)\n\n\tvats, err := s.ListVolumeAttachments(serverID)\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error getting attachment\"))\n\t}\n\n\tfor _, vat := range vats {\n\t\tif vat.ID == id && vat.ServerID == serverID {\n\t\t\treturn &vat, nil\n\t\t}\n\t}\n\n\treturn nil, fail.Errorf(fmt.Sprintf(\"Attachment [%s] to [%s] not found\", id, serverID), nil)\n}", "func (s *Stack) GetVolumeAttachment(serverID, id string) (*resources.VolumeAttachment, error) {\n\tif s == nil {\n\t\treturn nil, scerr.InvalidInstanceError()\n\t}\n\tif serverID == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"serverID\", \"cannot be empty string\")\n\t}\n\tif id == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"id\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, \"('\"+serverID+\"', '\"+id+\"')\", true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tva, err := volumeattach.Get(s.ComputeClient, serverID, id).Extract()\n\tif err != nil {\n\t\treturn nil, scerr.Wrap(err, fmt.Sprintf(\"error getting volume attachment %s: %s\", id, ProviderErrorToString(err)))\n\t}\n\treturn &resources.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}, nil\n}", "func (client *Client) GetVolumeAttachment(serverID, id string) (*api.VolumeAttachment, error) {\n\tva, err := volumeattach.Get(client.Compute, serverID, id).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\treturn &api.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}, nil\n}", "func GetVolumeAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentState, opts ...pulumi.ResourceOption) (*VolumeAttachment, error) {\n\tvar resource VolumeAttachment\n\terr := ctx.ReadResource(\"digitalocean:index/volumeAttachment:VolumeAttachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func GetVolumeAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentState, opts ...pulumi.ResourceOption) (*VolumeAttachment, error) {\n\tvar resource VolumeAttachment\n\terr := ctx.ReadResource(\"aws:ec2/volumeAttachment:VolumeAttachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *EventItemRequestBuilder) AttachmentsById(id string)(*ia583e36d9ac073d787b4f5e0abb093224bbfbbb0acf8b3a6f1b0f1e7dfd13a55.AttachmentItemRequestBuilder) {\n urlTplParams := make(map[string]string)\n for idx, item := range m.pathParameters {\n urlTplParams[idx] = item\n }\n if id != \"\" {\n urlTplParams[\"attachment%2Did\"] = id\n }\n return ia583e36d9ac073d787b4f5e0abb093224bbfbbb0acf8b3a6f1b0f1e7dfd13a55.NewAttachmentItemRequestBuilderInternal(urlTplParams, m.requestAdapter);\n}", "func (vs *volumeSet) getVolume(id string) *api.Volume {\n\treturn vs.volumes[id].volume\n}", "func GetVolume(id string, name string) (*xmsv3.Volume, error) {\n\tvolume, err := xms.GetVolume(id, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn volume.Content, nil\n}", "func (c *PostAttachmentClient) Get(ctx context.Context, id int) (*PostAttachment, error) {\n\treturn c.Query().Where(postattachment.ID(id)).Only(ctx)\n}", "func (digitalocean DigitalOcean) GetVolume(id string) (*godo.Volume, error) {\n\tdoc, err := DigitalOceanClient()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvolume, _, err := doc.client.Storage.GetVolume(doc.context, id)\n\n\tif err != nil {\n\t\t//log.Fatal(err)\n\t}\n\n\treturn volume, err\n}", "func List(c *golangsdk.ServiceClient, serverId string) ([]VolumeAttachment, error) {\n\tvar rst golangsdk.Result\n\t_, err := c.Get(rootURL(c, serverId), &rst.Body, &golangsdk.RequestOpts{\n\t\tMoreHeaders: requestOpts.MoreHeaders,\n\t})\n\tif err == nil {\n\t\tvar r []VolumeAttachment\n\t\trst.ExtractIntoSlicePtr(&r, \"volumeAttachments\")\n\t\treturn r, nil\n\t}\n\treturn nil, err\n}", "func (c *Core) getVolume(id types.VolumeID) (*types.Volume, error) {\n\tctx := driver.Contexts()\n\n\t// first, try to get volume from local store.\n\tobj, err := c.store.Get(id.Name)\n\tif err == nil {\n\t\tv, ok := obj.(*types.Volume)\n\t\tif !ok {\n\t\t\treturn nil, volerr.ErrVolumeNotFound\n\t\t}\n\n\t\t// get the volume driver.\n\t\tdv, err := driver.Get(v.Spec.Backend)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// if the driver implements Getter interface.\n\t\tif d, ok := dv.(driver.Getter); ok {\n\t\t\tcurV, err := d.Get(ctx, id.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, volerr.ErrVolumeNotFound\n\t\t\t}\n\n\t\t\tv.Status.MountPoint = curV.Status.MountPoint\n\t\t}\n\n\t\treturn v, nil\n\t}\n\n\tif err != metastore.ErrObjectNotFound {\n\t\treturn nil, err\n\t}\n\n\t// scan all drivers\n\tlogrus.Debugf(\"probing all drivers for volume with name(%s)\", id.Name)\n\tdrivers, err := driver.GetAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, dv := range drivers {\n\t\td, ok := dv.(driver.Getter)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tv, err := d.Get(ctx, id.Name)\n\t\tif err != nil {\n\t\t\t// not found, ignore it\n\t\t\tcontinue\n\t\t}\n\n\t\t// store volume meta\n\t\tif err := c.store.Put(v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn v, nil\n\t}\n\n\treturn nil, volerr.ErrVolumeNotFound\n}", "func GetVolumeAttachmentList(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *VolumeAttachmentListState, opts ...pulumi.ResourceOption) (*VolumeAttachmentList, error) {\n\tvar resource VolumeAttachmentList\n\terr := ctx.ReadResource(\"kubernetes:storage.k8s.io/v1beta1:VolumeAttachmentList\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client *Client) GetVolume(id string) (*api.Volume, error) {\n\tvol, err := volumes.Get(client.Volume, id).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error getting volume: %s\", ProviderErrorToString(err))\n\t}\n\tav := api.Volume{\n\t\tID: vol.ID,\n\t\tName: vol.Name,\n\t\tSize: vol.Size,\n\t\tSpeed: client.getVolumeSpeed(vol.VolumeType),\n\t\tState: toVolumeState(vol.Status),\n\t}\n\treturn &av, nil\n}", "func Get(c *golangsdk.ServiceClient, server_id string, volume_id string) (r GetResult) {\n\t_, r.Err = c.Get(getURL(c, server_id, volume_id), &r.Body, nil)\n\treturn\n}", "func (s *Stack) GetVolume(id string) (*resources.Volume, error) {\n\tif s == nil {\n\t\treturn nil, scerr.InvalidInstanceError()\n\t}\n\tif id == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"id\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, fmt.Sprintf(\"(%s)\", id), true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tr := volumesv2.Get(s.VolumeClient, id)\n\tvolume, err := r.Extract()\n\tif err != nil {\n\t\tif _, ok := err.(gc.ErrDefault404); ok {\n\t\t\treturn nil, resources.ResourceNotFoundError(\"volume\", id)\n\t\t}\n\t\treturn nil, scerr.Wrap(err, fmt.Sprintf(\"error getting volume: %s\", ProviderErrorToString(err)))\n\t}\n\n\tav := resources.Volume{\n\t\tID: volume.ID,\n\t\tName: volume.Name,\n\t\tSize: volume.Size,\n\t\tSpeed: s.getVolumeSpeed(volume.VolumeType),\n\t\tState: toVolumeState(volume.Status),\n\t}\n\treturn &av, nil\n}", "func (vpcIks *IksVpcSession) GetVolumeAttachment(volumeAttachmentRequest provider.VolumeAttachmentRequest) (*provider.VolumeAttachmentResponse, error) {\n\tvpcIks.Logger.Debug(\"Entry of IksVpcSession.GetVolumeAttachment method...\")\n\tdefer vpcIks.Logger.Debug(\"Exit from IksVpcSession.GetVolumeAttachment method...\")\n\treturn vpcIks.IksSession.GetVolumeAttachment(volumeAttachmentRequest)\n}", "func (o LookupOpenZfsSnapshotResultOutput) VolumeId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.VolumeId }).(pulumi.StringOutput)\n}", "func (s *DataStore) ListLonghornVolumeAttachmentByVolumeRO(name string) ([]*longhorn.VolumeAttachment, error) {\n\tvolumeSelector, err := getVolumeSelector(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.lhVALister.VolumeAttachments(s.namespace).List(volumeSelector)\n}", "func (p *Poloniex) GetVolume(ctx context.Context) (interface{}, error) {\n\tvar resp interface{}\n\tpath := \"/public?command=return24hVolume\"\n\n\treturn resp, p.SendHTTPRequest(ctx, exchange.RestSpot, path, &resp)\n}", "func (pstFile *File) GetAttachment(message *Message, attachmentNumber int, formatType string, encryptionType string) (Attachment, error) {\n\tif !message.HasAttachments() {\n\t\treturn Attachment{}, nil\n\t}\n\n\tattachmentsTableContext, err := pstFile.GetAttachmentsTableContext(message, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tif attachmentNumber > len(attachmentsTableContext) {\n\t\treturn Attachment{}, errors.New(fmt.Sprintf(\"invalid attachment number, there are only %d attachments\", len(attachmentsTableContext)))\n\t}\n\n\tattachmentTableContextItem := attachmentsTableContext[attachmentNumber]\n\n\tvar attachmentReferenceHNID int\n\n\tfor _, attachmentTableContextItemColumn := range attachmentTableContextItem {\n\t\tif attachmentTableContextItemColumn.PropertyID == 26610 {\n\t\t\tattachmentReferenceHNID = attachmentTableContextItemColumn.ReferenceHNID\n\t\t\tbreak\n\t\t}\n\t}\n\n\tattachmentLocalDescriptor, err := FindLocalDescriptor(message.LocalDescriptors, attachmentReferenceHNID, formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentLocalDescriptorLocalDescriptorsIdentifier, err := attachmentLocalDescriptor.GetLocalDescriptorsIdentifier(formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentLocalDescriptorLocalDescriptors, err := pstFile.GetLocalDescriptorsFromIdentifier(attachmentLocalDescriptorLocalDescriptorsIdentifier, formatType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentHeapOnNode, err := pstFile.NewHeapOnNodeFromLocalDescriptor(attachmentLocalDescriptor, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\tattachmentPropertyContext, err := pstFile.GetPropertyContext(attachmentHeapOnNode, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn Attachment{}, err\n\t}\n\n\treturn Attachment{\n\t\tPropertyContext: attachmentPropertyContext,\n\t\tLocalDescriptors: attachmentLocalDescriptorLocalDescriptors,\n\t}, nil\n}", "func GetVolumeInfo(awsSession *session.Session, targets []string) (info []VolInfo, err error) {\n\tclient := ec2.New(awsSession)\n\tinfo = make([]VolInfo, 0)\n\n\tfilters := make([]*ec2.Filter, 0)\n\n\tparams := &ec2.DescribeVolumesInput{}\n\n\t// process targets and massage them into aws type variables\n\tif targets != nil {\n\t\tawsnames := make([]*string, 0)\n\n\t\tfor _, name := range targets {\n\t\t\tawsnames = append(awsnames, aws.String(name))\n\t\t}\n\n\t\tnameFilter := ec2.Filter{\n\t\t\tName: aws.String(\"attachment.instance-id\"),\n\t\t\tValues: awsnames,\n\t\t}\n\n\t\tfilters = append(filters, &nameFilter)\n\t}\n\n\t// add the filters if they exist\n\tif len(filters) > 0 {\n\t\tparams.Filters = filters\n\t}\n\n\t// actually call aws for volume information\n\tresult, err := client.DescribeVolumes(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, \"error searching volumes\")\n\t\t\t\treturn info, err\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.Wrapf(err, \"error searching volumes\")\n\t\t\treturn info, err\n\t\t}\n\t}\n\n\t// loop through the resulting info, and set up the info we need\n\tfor _, vol := range result.Volumes {\n\t\tinstanceId := *vol.Attachments[0].InstanceId\n\t\tdeviceName := *vol.Attachments[0].Device\n\n\t\ti := VolInfo{\n\t\t\tInstanceId: instanceId,\n\t\t\tDeviceName: deviceName,\n\t\t\tVolumeId: *vol.VolumeId,\n\t\t}\n\n\t\tinfo = append(info, i)\n\t}\n\n\treturn info, err\n}", "func (o CachesIscsiVolumeOutput) VolumeId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CachesIscsiVolume) pulumi.StringOutput { return v.VolumeId }).(pulumi.StringOutput)\n}", "func (d DobsClient) AttachVolume(ctx Context, volumeID string, dropletID string) (error) {\n\tdropletIDI, err := strconv.Atoi(dropletID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvol, _, err := d.GodoClient.Storage.GetVolume(ctx, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(vol.DropletIDs) > 0 {\n\t\totherDropletID := vol.DropletIDs[0]\n\t\tif otherDropletID == dropletIDI {\n\t\t\tlog.Printf(\"Volume %s already attached to this droplet, skipping attach\\n\", volumeID)\n\t\t\treturn nil\n\t\t}\n\t\t\n\t\treturn fmt.Errorf(\"Volume %s already attached to different droplet %d\", volumeID, otherDropletID)\n\t}\n\n\taction, _, err := d.GodoClient.StorageActions.Attach(ctx, volumeID, dropletIDI)\t\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.waitForAction(ctx, volumeID, action)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *BinaryFileClient) Get(ctx context.Context, id int) (*BinaryFile, error) {\n\treturn c.Query().Where(binaryfile.ID(id)).Only(ctx)\n}", "func (c *Core) GetVolume(id types.VolumeID) (*types.Volume, error) {\n\tc.lock.Lock(id.Name)\n\tdefer c.lock.Unlock(id.Name)\n\n\treturn c.getVolume(id)\n}", "func (d *Data) GetVolume(v dvid.VersionID, vox *Labels, supervoxels bool, scale uint8, roiname dvid.InstanceName) ([]byte, error) {\n\tr, err := imageblk.GetROI(v, roiname, vox)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := d.GetLabels(v, supervoxels, scale, vox, r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn vox.Data(), nil\n}", "func (a *HyperflexApiService) GetHyperflexVolumeByMoid(ctx context.Context, moid string) ApiGetHyperflexVolumeByMoidRequest {\n\treturn ApiGetHyperflexVolumeByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (c *BlockVolumeClient) Details(id string) (*BlockVolume, error) {\n\tvar result BlockVolume\n\tparams := BlockVolumeParams{UniqID: id}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/details\", params, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}", "func (a *EmailControllerApiService) GetAttachments(ctx _context.Context, emailId string) ([]AttachmentMetaData, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []AttachmentMetaData\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/emails/{emailId}/attachments\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"emailId\"+\"}\", _neturl.QueryEscape(parameterToString(emailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v []AttachmentMetaData\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (digitalocean DigitalOcean) DetachVolume(volumeID string) error {\n\tdoc, err := DigitalOceanClient()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_, err = doc.client.Storage.DeleteVolume(doc.context, volumeID)\n\n\treturn err\n}", "func (o VpcAttachmentOutput) AttachmentId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *VpcAttachment) pulumi.StringOutput { return v.AttachmentId }).(pulumi.StringOutput)\n}", "func GetVolume(volumeID string) (*apis.ZFSVolume, error) {\n\treturn volbuilder.NewKubeclient().\n\t\tWithNamespace(OpenEBSNamespace).\n\t\tGet(volumeID, metav1.GetOptions{})\n}", "func (r *CachesIscsiVolume) VolumeId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"volumeId\"])\n}", "func (this *Value) GetAttachment(key string) interface{} {\n\tif this.attachments != nil {\n\t\treturn this.attachments[key]\n\t}\n\treturn nil\n}", "func (c *Core) DetachVolume(id types.VolumeID, extra map[string]string) (*types.Volume, error) {\n\tc.lock.Lock(id.Name)\n\tdefer c.lock.Unlock(id.Name)\n\n\tv, dv, err := c.getVolumeDriver(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := driver.Contexts()\n\n\t// merge extra to volume spec extra.\n\tfor key, value := range extra {\n\t\tv.Spec.Extra[key] = value\n\t}\n\n\t// if volume has referance, skip to detach volume.\n\tref := v.Option(types.OptionRef)\n\tif d, ok := dv.(driver.AttachDetach); ok && ref == \"\" {\n\t\tif err := d.Detach(ctx, v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// update meta info.\n\tif err := c.store.Put(v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (s *StackEbrc) ListVolumeAttachments(serverID string) ([]abstract.VolumeAttachment, fail.Error) {\n\tvms, err := s.findVmNames()\n\tif err != nil {\n\t\treturn []abstract.VolumeAttachment{}, err\n\t}\n\n\t_, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn []abstract.VolumeAttachment{}, fail.Wrap(err, fmt.Sprintf(\"Error deleting volume\"))\n\t}\n\n\tvar attachments []abstract.VolumeAttachment\n\n\tfor _, vmname := range vms {\n\t\tvm, err := s.findVMByName(vmname)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ittem := range vm.VM.VirtualHardwareSection.Item {\n\t\t\tif ittem != nil {\n\t\t\t\tif ittem.ResourceType == 17 {\n\t\t\t\t\tdadr := ittem.HostResource[0].Disk\n\t\t\t\t\tthedi, err := vdc.FindDiskByHREF(dadr)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\treid := abstract.VolumeAttachment{\n\t\t\t\t\t\tID: serverID + \":\" + thedi.Disk.Id,\n\t\t\t\t\t\tVolumeID: thedi.Disk.Id,\n\t\t\t\t\t\tServerID: serverID,\n\t\t\t\t\t}\n\n\t\t\t\t\tattachments = append(attachments, reid)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn attachments, nil\n}", "func (c *Core) AttachVolume(id types.VolumeID, extra map[string]string) (*types.Volume, error) {\n\tc.lock.Lock(id.Name)\n\tdefer c.lock.Unlock(id.Name)\n\n\tv, dv, err := c.getVolumeDriver(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := driver.Contexts()\n\n\t// merge extra to volume spec extra.\n\tfor key, value := range extra {\n\t\tv.Spec.Extra[key] = value\n\t}\n\n\tif d, ok := dv.(driver.AttachDetach); ok {\n\t\tif err := d.Attach(ctx, v); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// update meta info.\n\tif err := c.store.Put(v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (o *GetAttachmentParams) WithAttachmentID(attachmentID *string) *GetAttachmentParams {\n\to.SetAttachmentID(attachmentID)\n\treturn o\n}", "func (d DobsClient) GetVolume(ctx Context, name string) (*APIVolume, error) {\n\n\tapiVolume, err := d.getVolumeByName(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvol := &APIVolume{\n\t\tName: apiVolume.Name,\n\t\tID: apiVolume.ID,\n\t\t// DropletID: apiVolume.DropletIDs[0],\n\t}\n\n\treturn vol, nil\n}", "func (cl *Client) VolumeAttach(ctx context.Context, vaa *csp.VolumeAttachArgs) (*csp.Volume, error) {\n\tsvc, vid, _ := VolumeIdentifierParse(vaa.VolumeIdentifier)\n\tswitch svc {\n\tcase ServiceGCE:\n\t\treturn cl.gceVolumeAttach(ctx, vaa, vid)\n\t}\n\treturn nil, fmt.Errorf(\"storage type currently unsupported\")\n}", "func (vpcs *VPCSession) WaitForAttachVolume(volumeAttachmentTemplate provider.VolumeAttachmentRequest) (*provider.VolumeAttachmentResponse, error) {\n\tvpcs.Logger.Debug(\"Entry of WaitForAttachVolume method...\")\n\tdefer vpcs.Logger.Debug(\"Exit from WaitForAttachVolume method...\")\n\tvpcs.Logger.Info(\"Validating basic inputs for WaitForAttachVolume method...\", zap.Reflect(\"volumeAttachmentTemplate\", volumeAttachmentTemplate))\n\terr := vpcs.validateAttachVolumeRequest(volumeAttachmentTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmaxTimeout, maxRetryAttempt, retryGapDuration := vpcs.Config.GetTimeOutParameters()\n\tretryCount := 0\n\tvpcs.Logger.Info(\"Waiting for volume to be attached\", zap.Int(\"maxTimeout\", maxTimeout))\n\tfor retryCount < maxRetryAttempt {\n\t\tcurrentVolAttachment, errAPI := vpcs.GetVolumeAttachment(volumeAttachmentTemplate)\n\t\tif errAPI == nil && currentVolAttachment.Status == StatusAttached {\n\t\t\t// volume is attached return no error\n\t\t\tvpcs.Logger.Info(\"Volume attachment is complete\", zap.Int(\"retry attempt\", retryCount), zap.Int(\"max retry attepmts\", maxRetryAttempt), zap.Reflect(\"currentVolAttachment\", currentVolAttachment))\n\t\t\treturn currentVolAttachment, nil\n\t\t} else if errAPI != nil {\n\t\t\t// do not retry if there is error\n\t\t\tvpcs.Logger.Error(\"Error occured while finding volume attachment\", zap.Error(errAPI))\n\t\t\tuserErr := userError.GetUserError(string(userError.VolumeAttachFailed), errAPI, volumeAttachmentTemplate.VolumeID, volumeAttachmentTemplate.InstanceID)\n\t\t\treturn nil, userErr\n\t\t}\n\t\t// retry if attach status is not \"attached\"\n\t\tretryCount = retryCount + 1\n\t\tvpcs.Logger.Info(\"Volume is still attaching. Retry..\", zap.Int(\"retry attempt\", retryCount), zap.Int(\"max retry attepmts\", maxRetryAttempt), zap.Reflect(\"currentVolAttachment\", currentVolAttachment))\n\t\ttime.Sleep(retryGapDuration)\n\t}\n\tuserErr := userError.GetUserError(string(userError.VolumeAttachTimedOut), nil, volumeAttachmentTemplate.VolumeID, volumeAttachmentTemplate.InstanceID, vpcs.Config.Timeout)\n\tvpcs.Logger.Info(\"Wait for attach timed out\", zap.Error(userErr))\n\n\treturn nil, userErr\n}", "func (a *Client) GetVolume(params *GetVolumeParams) (*GetVolumeOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetVolumeParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetVolume\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/volumes/{volumeId}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetVolumeReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetVolumeOK), nil\n\n}", "func GetAttachment(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *AttachmentState, opts ...pulumi.ResourceOption) (*Attachment, error) {\n\tvar resource Attachment\n\terr := ctx.ReadResource(\"alicloud:slb/attachment:Attachment\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client *Client) CreateVolumeAttachment(request api.VolumeAttachmentRequest) (*api.VolumeAttachment, error) {\n\t// Create the attachment\n\tva, err := volumeattach.Create(client.Compute, request.ServerID, volumeattach.CreateOpts{\n\t\tVolumeID: request.VolumeID,\n\t}).Extract()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating volume attachment between server %s and volume %s: %s\", request.ServerID, request.VolumeID, ProviderErrorToString(err))\n\t}\n\n\tvaapi := &api.VolumeAttachment{\n\t\tID: va.ID,\n\t\tServerID: va.ServerID,\n\t\tVolumeID: va.VolumeID,\n\t\tDevice: va.Device,\n\t}\n\n\t// Update the metadata\n\n\tmtdVol, err := metadata.LoadVolume(providers.FromClient(client), request.VolumeID)\n\tif err != nil {\n\n\t\t// Detach volume\n\t\tdetach_err := volumeattach.Delete(client.Compute, va.ServerID, va.ID).ExtractErr()\n\t\tif detach_err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error deleting volume attachment %s: %s\", va.ID, ProviderErrorToString(err))\n\t\t}\n\n\t\treturn nil, err\n\t}\n\terr = mtdVol.Attach(vaapi)\n\tif err != nil {\n\t\t// Detach volume\n\t\tdetach_err := volumeattach.Delete(client.Compute, va.ServerID, va.ID).ExtractErr()\n\t\tif detach_err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error deleting volume attachment %s: %s\", va.ID, ProviderErrorToString(err))\n\t\t}\n\n\t\treturn vaapi, err\n\t}\n\n\treturn vaapi, nil\n}", "func (o AttachmentAccepterOutput) AttachmentId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AttachmentAccepter) pulumi.StringOutput { return v.AttachmentId }).(pulumi.StringOutput)\n}", "func (client *Client) ListVolumeAttachments(serverID string) ([]api.VolumeAttachment, error) {\n\tvar vs []api.VolumeAttachment\n\terr := volumeattach.List(client.Compute, serverID).EachPage(func(page pagination.Page) (bool, error) {\n\t\tlist, err := volumeattach.ExtractVolumeAttachments(page)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, va := range list {\n\t\t\tava := api.VolumeAttachment{\n\t\t\t\tID: va.ID,\n\t\t\t\tServerID: va.ServerID,\n\t\t\t\tVolumeID: va.VolumeID,\n\t\t\t\tDevice: va.Device,\n\t\t\t}\n\t\t\tvs = append(vs, ava)\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error listing volume types: %s\", ProviderErrorToString(err))\n\t}\n\treturn vs, nil\n}", "func (a *Client) GetAttachmentsID(params *GetAttachmentsIDParams, authInfo runtime.ClientAuthInfoWriter) (*GetAttachmentsIDOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAttachmentsIDParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetAttachmentsID\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/attachments/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetAttachmentsIDReader{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.(*GetAttachmentsIDOK)\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 GetAttachmentsID: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (client VolumesClient) Get(ctx context.Context, location string, storageSubSystem string, storagePool string, volume string) (result Volume, err error) {\n\treq, err := client.GetPreparer(ctx, location, storageSubSystem, storagePool, volume)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func readVolume(devicebytes []byte, keyBlock uint16, debug int) (Volume, error) {\n\tv := Volume{\n\t\tkeyBlock: &VolumeDirectoryKeyBlock{},\n\t\tsubdirsByBlock: make(map[uint16]*Subdirectory),\n\t\tsubdirsByName: make(map[string]*Subdirectory),\n\t\tfirstSubdirBlocks: make(map[uint16]uint16),\n\t}\n\n\tif err := disk.UnmarshalBlock(devicebytes, v.keyBlock, keyBlock); err != nil {\n\t\treturn v, fmt.Errorf(\"cannot read first block of volume directory (block %d): %v\", keyBlock, err)\n\t}\n\t// if debug {\n\t// \tfmt.Fprintf(os.Stderr, \"keyblock: %#v\\n\", v.keyBlock)\n\t// }\n\n\tvbm, err := readVolumeBitMap(devicebytes, v.keyBlock.Header.BitMapPointer)\n\tif err != nil {\n\t\treturn v, err\n\t}\n\n\tv.bitmap = &vbm\n\n\t// if debug {\n\t// \tfmt.Fprintf(os.Stderr, \"volume bitmap: %#v\\n\", v.bitmap)\n\t// }\n\n\tfor block := v.keyBlock.Next; block != 0; block = v.blocks[len(v.blocks)-1].Next {\n\t\tvdb := VolumeDirectoryBlock{}\n\t\tif err := disk.UnmarshalBlock(devicebytes, &vdb, block); err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tv.blocks = append(v.blocks, &vdb)\n\t\tv.firstSubdirBlocks[block] = keyBlock\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \" firstSubdirBlocks[%d] → %d\\n\", block, keyBlock)\n\t\t}\n\t\t// if debug {\n\t\t// \tfmt.Fprintf(os.Stderr, \"block: %#v\\n\", vdb)\n\t\t// }\n\t}\n\n\tsdds := v.subdirDescriptors()\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"got %d top-level subdir descriptors\\n\", len(sdds))\n\t}\n\n\tfor i := 0; i < len(sdds); i++ {\n\t\tsdd := sdds[i]\n\t\tsub, err := readSubdirectory(devicebytes, sdd)\n\t\tif err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tv.subdirsByBlock[sdd.KeyPointer] = &sub\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \" subdirsByBlock[%d] → %q\\n\", sdd.KeyPointer, sub.keyBlock.Header.Name())\n\t\t}\n\t\tsdds = append(sdds, sub.subdirDescriptors()...)\n\t\tfor _, block := range sub.blocks {\n\t\t\tv.firstSubdirBlocks[block.block] = sdd.KeyPointer\n\t\t\tif debug > 1 {\n\t\t\t\tfmt.Fprintf(os.Stderr, \" firstSubdirBlocks[%d] → %d\\n\", block.block, sdd.KeyPointer)\n\t\t\t}\n\t\t}\n\t}\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"got %d total subdir descriptors\\n\", len(sdds))\n\t}\n\n\tfor _, sd := range v.subdirsByBlock {\n\t\tname := sd.keyBlock.Header.Name()\n\t\tif debug > 1 {\n\t\t\tfmt.Fprintf(os.Stderr, \"processing subdir %q\\n\", name)\n\t\t}\n\t\tparentName, err := parentDirName(sd.keyBlock.Header.ParentPointer, keyBlock, v.subdirsByBlock, v.firstSubdirBlocks)\n\t\tif err != nil {\n\t\t\treturn v, err\n\t\t}\n\t\tif parentName != \"\" {\n\t\t\tname = parentName + \"/\" + name\n\t\t}\n\n\t\tv.subdirsByName[name] = sd\n\t}\n\tif debug > 1 {\n\t\tfmt.Fprintf(os.Stderr, \"subdirsByName:\\n\")\n\t\tfor k := range v.subdirsByName {\n\t\t\tfmt.Fprintf(os.Stderr, \" %s\\n\", k)\n\t\t}\n\t}\n\treturn v, nil\n}", "func (o FioSpecVolumeVolumeSourceCinderOutput) VolumeID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceCinder) string { return v.VolumeID }).(pulumi.StringOutput)\n}", "func (d DobsClient) DetachVolume(ctx Context, volumeID string, dropletID string) (error) {\n\tdropletIDI, err := strconv.Atoi(dropletID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taction, _, err := d.GodoClient.StorageActions.DetachByDropletID(ctx, volumeID, dropletIDI)\t\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.waitForAction(ctx, volumeID, action)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func getFileById(id string) (*drive.File, error) {\n\tfor ntries := 0; ; ntries++ {\n\t\tfile, err := drivesvc.Files.Get(id).Do()\n\t\tif err == nil {\n\t\t\treturn file, nil\n\t\t} else if err = tryToHandleDriveAPIError(err, ntries); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n}", "func (n *Client) GetAttachment(siteSlug string, pageSlug string, id int, options *Options) (attachment *Attachment, result *Result) {\n\tu := fmt.Sprintf(\"/sites/%s/pages/%s/attachments/%d\", siteSlug, pageSlug, id)\n\tr := n.getRequest(\"GET\", u, options)\n\ta := &attachmentWrap{}\n\tresult = n.retrieve(r, a)\n\tattachment = a.Attachment\n\n\treturn\n}", "func (srv *VolumeService) Get(ref string) (*api.Volume, error) {\n\tvolumes, err := srv.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, volume := range volumes {\n\t\tif volume.ID == ref || volume.Name == ref {\n\t\t\treturn &volume, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Volume '%s' does not exists\", ref)\n}", "func (d *DefaultDriver) AttachVolume(volumeID string) (string, error) {\n\treturn \"\", &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"CreateVolume()\",\n\t}\n}", "func (o *Volume) GetVolumeId() string {\n\tif o == nil || o.VolumeId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VolumeId\n}", "func (o *Volume) GetVolumeId() string {\n\tif o == nil || o.VolumeId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VolumeId\n}", "func (c *Core) getVolumeDriver(id types.VolumeID) (*types.Volume, driver.Driver, error) {\n\tv, err := c.getVolume(id)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdv, err := driver.Get(v.Spec.Backend)\n\tif err != nil {\n\t\treturn nil, nil, errors.Errorf(\"failed to get backend driver %s: %v\", v.Spec.Backend, err)\n\t}\n\treturn v, dv, nil\n}", "func (s *Stack) ListVolumeAttachments(serverID string) ([]resources.VolumeAttachment, error) {\n\tif s == nil {\n\t\treturn nil, scerr.InvalidInstanceError()\n\t}\n\tif serverID == \"\" {\n\t\treturn nil, scerr.InvalidParameterError(\"serverID\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, \"('\"+serverID+\"')\", true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tvar vs []resources.VolumeAttachment\n\terr := volumeattach.List(s.ComputeClient, serverID).EachPage(func(page pagination.Page) (bool, error) {\n\t\tlist, err := volumeattach.ExtractVolumeAttachments(page)\n\t\tif err != nil {\n\t\t\treturn false, scerr.Wrap(err, \"Error listing volume attachment: extracting attachments\")\n\t\t}\n\t\tfor _, va := range list {\n\t\t\tava := resources.VolumeAttachment{\n\t\t\t\tID: va.ID,\n\t\t\t\tServerID: va.ServerID,\n\t\t\t\tVolumeID: va.VolumeID,\n\t\t\t\tDevice: va.Device,\n\t\t\t}\n\t\t\tvs = append(vs, ava)\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, scerr.Wrap(err, fmt.Sprintf(\"error listing volume types: %s\", ProviderErrorToString(err)))\n\t}\n\treturn vs, nil\n}", "func getSmbVolFromID(id string) (*smbVolume, error) {\n\tsegments := strings.Split(id, separator)\n\tif len(segments) < 2 {\n\t\treturn nil, fmt.Errorf(\"could not split %q into server and subDir\", id)\n\t}\n\tsource := segments[0]\n\tif !strings.HasPrefix(segments[0], \"//\") {\n\t\tsource = \"//\" + source\n\t}\n\tvol := &smbVolume{\n\t\tid: id,\n\t\tsource: source,\n\t\tsubDir: segments[1],\n\t}\n\tif len(segments) >= 3 {\n\t\tvol.uuid = segments[2]\n\t}\n\treturn vol, nil\n}", "func (o IopingSpecVolumeVolumeSourceCinderOutput) VolumeID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceCinder) string { return v.VolumeID }).(pulumi.StringOutput)\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WithContext(ctx context.Context) *ReadStorageV1alpha1VolumeAttachmentParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (o *ReadStorageV1alpha1VolumeAttachmentParams) WithExact(exact *bool) *ReadStorageV1alpha1VolumeAttachmentParams {\n\to.SetExact(exact)\n\treturn o\n}", "func (client *Client) DeleteVolumeAttachment(serverID, id string) error {\n\tva, err := client.GetVolumeAttachment(serverID, id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = volumeattach.Delete(client.Compute, serverID, id).ExtractErr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\tmtdVol, err := metadata.LoadVolume(providers.FromClient(client), id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = mtdVol.Detach(va)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\treturn nil\n}", "func Attach(c *golangsdk.ServiceClient, opts AttachOpts) (*jobs.Job, error) {\n\tb, err := golangsdk.BuildRequestBody(opts, \"volumeAttachment\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r jobs.Job\n\t_, err = c.Post(attachURL(c, opts.ServerId), b, &r, &golangsdk.RequestOpts{\n\t\tMoreHeaders: requestOpts.MoreHeaders,\n\t})\n\treturn &r, err\n}", "func (o *GetBootVolumeAttachmentParams) WithBootVolumeAttachmentID(bootVolumeAttachmentID string) *GetBootVolumeAttachmentParams {\n\to.SetBootVolumeAttachmentID(bootVolumeAttachmentID)\n\treturn o\n}", "func (pstFile *File) GetAttachments(message *Message, formatType string, encryptionType string) ([]Attachment, error) {\n\tif !message.HasAttachments() {\n\t\treturn nil, nil\n\t}\n\n\tattachmentsTableContext, err := pstFile.GetAttachmentsTableContext(message, formatType, encryptionType)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar attachments []Attachment\n\n\tfor i := 0; i < len(attachmentsTableContext); i++ {\n\t\tattachment, err := pstFile.GetAttachment(message, i, formatType, encryptionType)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tattachments = append(attachments, attachment)\n\t}\n\n\treturn attachments, nil\n}", "func (ec *executionContext) _Attachment_id(ctx context.Context, field graphql.CollectedField, obj *Attachment) (ret graphql.Marshaler) {\n\tctx = ec.Tracer.StartFieldExecution(ctx, field)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t\tec.Tracer.EndFieldExecution(ctx)\n\t}()\n\trctx := &graphql.ResolverContext{\n\t\tObject: \"Attachment\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: false,\n\t}\n\tctx = graphql.WithResolverContext(ctx, rctx)\n\tctx = ec.Tracer.StartFieldResolverExecution(ctx, rctx)\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !ec.HasError(rctx) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\trctx.Result = res\n\tctx = ec.Tracer.StartFieldChildExecution(ctx)\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func (d *DefaultDriver) DetachVolume(volumeID string) error {\n\treturn &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"DetachVolume()\",\n\t}\n}", "func (m *MockTenantServiceVolumeDao) GetVolumeByID(id int) (*model.TenantServiceVolume, error) {\n\tret := m.ctrl.Call(m, \"GetVolumeByID\", id)\n\tret0, _ := ret[0].(*model.TenantServiceVolume)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r Notification_Occurrence_Event) GetAttachedFile(attachmentId *int) (resp []byte, err error) {\n\tparams := []interface{}{\n\t\tattachmentId,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Notification_Occurrence_Event\", \"getAttachedFile\", params, &r.Options, &resp)\n\treturn\n}", "func (o *VolumeAttributesType) VolumeIdAttributes() VolumeIdAttributesType {\n\tr := *o.VolumeIdAttributesPtr\n\treturn r\n}", "func Get(client *gophercloud.ServiceClient, id string, bearer map[string]string) (r volumes.GetResult) {\n\t_, r.Err = client.Get(getURL(client, id), &r.Body, &gophercloud.RequestOpts{\n\t\tMoreHeaders: bearer,\n\t})\n\treturn\n}", "func getSqliteFileAttach(c *echo.Context) error {\n\tsf := SqliteFile{DeviceID: c.Param(\"DeviceID\")}\n\thas, err := g_engine.Get(&sf)\n\tif err != nil {\n\t\treturn jsonResp(c, err.Error())\n\t}\n\tif !has {\n\t\treturn jsonResp(c, \"not exists\")\n\t}\n\n\tc.Response().Header().Set(echo.ContentDisposition, \"attachment; filename=\"+sf.Name)\n\n\thttp.ServeContent(c.Response(), c.Request(), sf.Name, sf.Mtime, bytes.NewReader(sf.Context))\n\n\treturn nil\n}", "func (driver *Driver) Path(volumeName, volumeID string) (string, error) {\n\tif volumeName == \"\" && volumeID == \"\" {\n\t\treturn \"\", errors.New(\"Missing volume name or ID\")\n\t}\n\n\tinstances, err := driver.sdm.GetInstance()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase len(instances) == 0:\n\t\treturn \"\", errors.New(\"No instances\")\n\tcase len(instances) > 1:\n\t\treturn \"\", errors.New(\"Too many instances returned, limit the storagedrivers\")\n\t}\n\n\tvolumes, err := driver.sdm.GetVolume(volumeID, volumeName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch {\n\tcase len(volumes) == 0:\n\t\treturn \"\", errors.New(\"No volumes returned by name\")\n\tcase len(volumes) > 1:\n\t\treturn \"\", errors.New(\"Multiple volumes returned by name\")\n\t}\n\n\tvolumeAttachment, err := driver.sdm.GetVolumeAttach(volumes[0].VolumeID, instances[0].InstanceID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(volumeAttachment) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tmounts, err := driver.osdm.GetMounts(volumeAttachment[0].DeviceName, \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(mounts) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\treturn mounts[0].Mountpoint, nil\n}", "func getVolumeDetails(svc *ec2.Client, output *ec2.DescribeVolumesOutput, region string) ([]*resource.Resource, error) {\n\tvar ebsVolumes []*resource.Resource\n\tebsLogger.Debug(\"Fetching Ebs Details\")\n\tfor _, volume := range output.Volumes {\n\t\ttags := make(resource.Tags)\n\t\tfor _, t := range volume.Tags {\n\t\t\ttags[*t.Key] = *t.Value\n\t\t}\n\t\t// We need the creation-date when parsing Tags for relative defintions\n\t\t// Ebs Volumes Launch Time is not the creation date. It's the time it was last launched.\n\t\t// TODO To get the creation date we might want to get the creation date of the EBS attached to the Ebs instead\n\t\ttags[\"creation-date\"] = (*volume.CreateTime).String()\n\t\tebsResource := NewResource(*volume.VolumeId, ec2Name)\n\t\tebsResource.Region = region\n\t\t// Get CreationDate by getting LaunchTime of attached Volume\n\t\tebsResource.CreationDate = *volume.CreateTime\n\t\tebsResource.Tags = tags\n\t\tebsResource.Status = resource.Running\n\t\tif len(volume.Attachments) == 0 {\n\t\t\tebsResource.Status = resource.Unused\n\t\t}\n\t\tebsVolumes = append(ebsVolumes, ebsResource)\n\t}\n\n\treturn ebsVolumes, nil\n}", "func (a *HetznerVolumes) AttachVolume(volume *volumes.Volume) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tvolumeID, err := strconv.Atoi(volume.ProviderID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to convert volume id %q to int: %w\", volume.ProviderID, err)\n\t}\n\n\thetznerVolume, _, err := a.hcloudClient.Volume.GetByID(ctx, volumeID)\n\tif err != nil || hetznerVolume == nil {\n\t\treturn fmt.Errorf(\"failed to get info for volume id %q: %w\", volume.ProviderID, err)\n\t}\n\n\tif hetznerVolume.Server != nil {\n\t\tif hetznerVolume.Server.ID != a.server.ID {\n\t\t\treturn fmt.Errorf(\"found volume %s(%d) attached to a different server: %d\", hetznerVolume.Name, hetznerVolume.ID, hetznerVolume.Server.ID)\n\t\t}\n\n\t\tklog.V(2).Infof(\"Attached volume %s(%d) to the running server\", hetznerVolume.Name, hetznerVolume.ID)\n\n\t\tvolume.LocalDevice = fmt.Sprintf(\"%s%d\", localDevicePrefix, hetznerVolume.ID)\n\t\treturn nil\n\t}\n\n\tklog.V(2).Infof(\"Attaching volume %s(%d) to the running server\", hetznerVolume.Name, hetznerVolume.ID)\n\n\taction, _, err := a.hcloudClient.Volume.Attach(ctx, hetznerVolume, a.server)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to attach volume %s(%d): %w\", hetznerVolume.Name, hetznerVolume.ID, err)\n\t}\n\n\t_, errCh := a.hcloudClient.Action.WatchProgress(ctx, action)\n\tif err := <-errCh; err != nil {\n\t\treturn fmt.Errorf(\"failed to wait for volume to %s(%d) be ready: %w\", hetznerVolume.Name, hetznerVolume.ID, err)\n\t}\n\n\treturn nil\n}", "func (c *UnsavedPostAttachmentClient) Get(ctx context.Context, id int) (*UnsavedPostAttachment, error) {\n\treturn c.Query().Where(unsavedpostattachment.ID(id)).Only(ctx)\n}", "func LookupVpcAttachment(ctx *pulumi.Context, args *GetVpcAttachmentArgs) (*GetVpcAttachmentResult, error) {\n\tinputs := make(map[string]interface{})\n\tif args != nil {\n\t\tinputs[\"filters\"] = args.Filters\n\t\tinputs[\"id\"] = args.Id\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\toutputs, err := ctx.Invoke(\"aws:ec2transitgateway/getVpcAttachment:getVpcAttachment\", inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GetVpcAttachmentResult{\n\t\tDnsSupport: outputs[\"dnsSupport\"],\n\t\tFilters: outputs[\"filters\"],\n\t\tId: outputs[\"id\"],\n\t\tIpv6Support: outputs[\"ipv6Support\"],\n\t\tSubnetIds: outputs[\"subnetIds\"],\n\t\tTags: outputs[\"tags\"],\n\t\tTransitGatewayId: outputs[\"transitGatewayId\"],\n\t\tVpcId: outputs[\"vpcId\"],\n\t\tVpcOwnerId: outputs[\"vpcOwnerId\"],\n\t}, nil\n}", "func (db *DB) GetAttachment(ctx context.Context, docID, rev, filename string) (*Attachment, error) {\n\tcType, md5sum, body, err := db.driverDB.GetAttachment(ctx, docID, rev, filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Attachment{\n\t\tReadCloser: body,\n\t\tFilename: filename,\n\t\tContentType: cType,\n\t\tMD5: MD5sum(md5sum),\n\t}, nil\n}", "func (objectSet *VolumeObjectSet) GetObject(id string) (*model.Volume, error) {\r\n\tresponse, err := objectSet.Client.Get(volumePath, id, model.Volume{})\r\n\tif response == nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn response.(*model.Volume), err\r\n}", "func (cl *Client) VolumeDetach(ctx context.Context, vda *csp.VolumeDetachArgs) (*csp.Volume, error) {\n\tsvc, vid, _ := VolumeIdentifierParse(vda.VolumeIdentifier)\n\tswitch svc {\n\tcase ServiceGCE:\n\t\treturn cl.gceVolumeDetach(ctx, vda, vid)\n\t}\n\treturn nil, fmt.Errorf(\"storage type currently unsupported\")\n}", "func (a *EmailControllerApiService) DownloadAttachment(ctx _context.Context, attachmentId string, emailId string, localVarOptionals *DownloadAttachmentOpts) (string, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue string\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/emails/{emailId}/attachments/{attachmentId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"attachmentId\"+\"}\", _neturl.QueryEscape(parameterToString(attachmentId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"emailId\"+\"}\", _neturl.QueryEscape(parameterToString(emailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.ApiKey.IsSet() {\n\t\tlocalVarQueryParams.Add(\"apiKey\", parameterToString(localVarOptionals.ApiKey.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/octet-stream\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v string\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func isVolumePublished(canAtMultiNode bool, attachReq *model.VolumeAttachmentSpec,\n\tmetadata map[string]string) (*model.VolumeAttachmentSpec, error) {\n\tglog.V(5).Infof(\"start to isVolumePublished, canAtMultiNode = %v, attachReq = %v\",\n\t\tcanAtMultiNode, attachReq)\n\n\tattachments, err := Client.ListVolumeAttachments()\n\tif err != nil {\n\t\tglog.V(5).Info(\"ListVolumeAttachments failed: \" + err.Error())\n\t\treturn nil, status.Error(codes.FailedPrecondition, err.Error())\n\t}\n\n\tfor _, attachSpec := range attachments {\n\t\tif attachSpec.VolumeId == attachReq.VolumeId {\n\t\t\tif attachSpec.Host != attachReq.Host {\n\t\t\t\tif !canAtMultiNode {\n\t\t\t\t\tmsg := fmt.Sprintf(\"the volume %s has been published to another node and does not have MULTI_NODE volume capability\",\n\t\t\t\t\t\tattachReq.VolumeId)\n\t\t\t\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Opensds does not have volume_capability and readonly parameters,\n\t\t\t\t// but needs to check other parameters to determine compatibility?\n\t\t\t\tif attachSpec.Platform == attachReq.Platform &&\n\t\t\t\t\tattachSpec.OsType == attachReq.OsType &&\n\t\t\t\t\tattachSpec.Initiator == attachReq.Initiator &&\n\t\t\t\t\tisStringMapEqual(attachSpec.Metadata, metadata) &&\n\t\t\t\t\tattachSpec.AccessProtocol == attachReq.AccessProtocol {\n\t\t\t\t\tglog.V(5).Info(\"Volume published and is compatible\")\n\n\t\t\t\t\treturn attachSpec, nil\n\t\t\t\t}\n\n\t\t\t\tglog.Error(\"Volume published but is incompatible, incompatible attachement Id = \" + attachSpec.Id)\n\t\t\t\treturn nil, status.Error(codes.AlreadyExists, \"Volume published but is incompatible\")\n\t\t\t}\n\t\t}\n\t}\n\n\tglog.V(5).Info(\"Need to create a new attachment\")\n\treturn nil, nil\n}", "func (o FioSpecVolumeVolumeSourcePortworxVolumeOutput) VolumeID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourcePortworxVolume) string { return v.VolumeID }).(pulumi.StringOutput)\n}", "func (o IopingSpecVolumeVolumeSourcePortworxVolumeOutput) VolumeID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourcePortworxVolume) string { return v.VolumeID }).(pulumi.StringOutput)\n}", "func (o *GetBootVolumeAttachmentParams) WithTimeout(timeout time.Duration) *GetBootVolumeAttachmentParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func GetIssueAttachment(ctx *context.APIContext) {\n\t// swagger:operation GET /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueGetIssueAttachment\n\t// ---\n\t// summary: Get an issue attachment\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: index\n\t// in: path\n\t// description: index of the issue\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// - name: attachment_id\n\t// in: path\n\t// description: id of the attachment to get\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Attachment\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/error\"\n\n\tissue := getIssueFromContext(ctx)\n\tif issue == nil {\n\t\treturn\n\t}\n\n\tattach := getIssueAttachmentSafeRead(ctx, issue)\n\tif attach == nil {\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, convert.ToAPIAttachment(ctx.Repo.Repository, attach))\n}", "func NewReadStorageV1alpha1VolumeAttachmentParams() *ReadStorageV1alpha1VolumeAttachmentParams {\n\tvar ()\n\treturn &ReadStorageV1alpha1VolumeAttachmentParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (s *NetworkInterface) SetAttachmentId(v string) *NetworkInterface {\n\ts.AttachmentId = &v\n\treturn s\n}", "func NewGetBootVolumeAttachmentParams() *GetBootVolumeAttachmentParams {\n\tvar ()\n\treturn &GetBootVolumeAttachmentParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func GetVolume(c common.Client, uri string) (*Volume, error) {\n\tvar volume Volume\n\treturn &volume, volume.Get(c, uri, &volume)\n}", "func (a *Client) GetAttachments(params *GetAttachmentsParams, authInfo runtime.ClientAuthInfoWriter) (*GetAttachmentsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAttachmentsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetAttachments\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/attachments\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetAttachmentsReader{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.(*GetAttachmentsOK)\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 GetAttachments: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *StackEbrc) GetVolume(ref string) (*abstract.Volume, fail.Error) {\n\tlogrus.Debug(\"ebrc.Client.GetVolume() called\")\n\tdefer logrus.Debug(\"ebrc.Client.GetVolume() done\")\n\n\tvar volume abstract.Volume\n\n\t_, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error listing volumes\"))\n\t}\n\n\t// FIXME: Add data\n\tdr, err := vdc.QueryDisk(ref)\n\tif err == nil {\n\t\tthed, err := vdc.FindDiskByHREF(dr.Disk.HREF)\n\t\tif err == nil {\n\t\t\tvolume = abstract.Volume{\n\t\t\t\tName: thed.Disk.Name,\n\t\t\t\tSize: thed.Disk.Size,\n\t\t\t\tID: thed.Disk.Id,\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &volume, nil\n}", "func (m *MockTenantServiceVolumeDao) GetVolumeByServiceIDAndName(serviceID, name string) (*model.TenantServiceVolume, error) {\n\tret := m.ctrl.Call(m, \"GetVolumeByServiceIDAndName\", serviceID, name)\n\tret0, _ := ret[0].(*model.TenantServiceVolume)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s stack) InspectVolumeAttachment(ctx context.Context, hostRef, vaID string) (*abstract.VolumeAttachment, fail.Error) {\n\tif valid.IsNil(s) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\treturn nil, fail.NotImplementedError(\"implement me\")\n}", "func (k *KubeClient) GetVolume(ctx context.Context, nodeName string, driverName string) (map[string]struct{}, error) {\n\tpodList, err := k.getPods(ctx, nodeName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve pod list. %s\", err)\n\t}\n\t// get PVC list\n\tpvcList := make(map[string]struct{}, 0)\n\n\tfor _, pod := range podList.Items {\n\t\t// If a pod is being terminating, skip the pod.\n\t\tlog.AddContext(ctx).Infof(\"Get pod [%s], pod.DeletionTimestamp: [%v].\", pod.Name, pod.DeletionTimestamp)\n\t\tif pod.DeletionTimestamp != nil {\n\t\t\tlog.AddContext(ctx).Infof(\"Pod [%s] is terminating, skip it.\", pod.Name)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, volume := range pod.Spec.Volumes {\n\t\t\tif volume.PersistentVolumeClaim != nil {\n\t\t\t\tpvcList[volume.PersistentVolumeClaim.ClaimName+\"@\"+pod.Namespace] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\tk8sVolumeHandles := make(map[string]struct{})\n\terrChan := make(chan error)\n\tpvChan := make(chan *corev1.PersistentVolume)\n\n\tdefer func() {\n\t\tclose(errChan)\n\t\tclose(pvChan)\n\t}()\n\t// aggregate all volume information\n\tfor claimName := range pvcList {\n\t\tpvcInfo := strings.Split(claimName, \"@\")\n\t\tif len(pvcInfo) <= 1 {\n\t\t\tlog.AddContext(ctx).Errorf(\"The length of pvcInfo: [%d] is less than 2\", len(pvcInfo))\n\t\t\tcontinue\n\t\t}\n\t\tgo func(claimName string, namespace string,\n\t\t\tvolChan chan<- *corev1.PersistentVolume,\n\t\t\terrorChan chan<- error) {\n\t\t\tvol, err := k.getPVByPVCName(ctx, namespace, claimName)\n\t\t\tif err != nil {\n\t\t\t\terrorChan <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvolChan <- vol\n\t\t}(pvcInfo[0], pvcInfo[1], pvChan, errChan)\n\t}\n\tvar volumeError error\n\tfor i := 0; i < len(pvcList); i++ {\n\t\tselect {\n\t\tcase err := <-errChan:\n\t\t\tvolumeError = err\n\t\tcase volume := <-pvChan:\n\t\t\tif volume.Spec.PersistentVolumeSource.CSI != nil &&\n\t\t\t\tdriverName == volume.Spec.PersistentVolumeSource.CSI.Driver {\n\t\t\t\tk8sVolumeHandles[volume.Spec.PersistentVolumeSource.CSI.VolumeHandle] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\tif volumeError != nil {\n\t\treturn nil, volumeError\n\t}\n\tlog.AddContext(ctx).Infof(\"PV list from k8s side for the node %s: %v\", nodeName, k8sVolumeHandles)\n\treturn k8sVolumeHandles, nil\n}", "func WaitForVolumeDeletion(vpcs *VPCSession, volumeID string) (err error) {\n\tvpcs.Logger.Debug(\"Entry of WaitForVolumeDeletion method...\")\n\tdefer vpcs.Logger.Debug(\"Exit from WaitForVolumeDeletion method...\")\n\tvar skip = false\n\n\tvpcs.Logger.Info(\"Getting volume details from VPC provider...\", zap.Reflect(\"VolumeID\", volumeID))\n\n\terr = vpcs.APIRetry.FlexyRetry(vpcs.Logger, func() (error, bool) {\n\t\t_, err = vpcs.Apiclient.VolumeService().GetVolume(volumeID, vpcs.Logger)\n\t\t// Keep retry, until GetVolume returns volume not found\n\t\tif err != nil {\n\t\t\tskip = skipRetry(err.(*models.Error))\n\t\t\treturn nil, skip\n\t\t}\n\t\treturn err, false // continue retry as we are not seeing error which means volume is available\n\t})\n\n\tif err == nil && skip {\n\t\tvpcs.Logger.Info(\"Volume got deleted.\", zap.Reflect(\"volumeID\", volumeID))\n\t}\n\treturn err\n}" ]
[ "0.7703875", "0.66602343", "0.6452562", "0.63696307", "0.6187234", "0.589041", "0.585325", "0.5834788", "0.56788754", "0.55835557", "0.55712897", "0.5488958", "0.54294586", "0.5414699", "0.541424", "0.5377449", "0.53667283", "0.5361751", "0.5325508", "0.5317213", "0.5294674", "0.52919775", "0.52673125", "0.5243566", "0.5232335", "0.52262115", "0.52241004", "0.5206574", "0.5202237", "0.5199337", "0.5137426", "0.51363033", "0.511381", "0.51071227", "0.5098818", "0.50621134", "0.5032078", "0.5030401", "0.5029047", "0.5026863", "0.5009456", "0.50001395", "0.49740562", "0.49689075", "0.49606308", "0.49492854", "0.49391714", "0.49263677", "0.49242264", "0.4923883", "0.49193248", "0.49122694", "0.4911691", "0.49013963", "0.4899488", "0.48990348", "0.48990273", "0.48946375", "0.48946375", "0.48861423", "0.4886047", "0.48737833", "0.48735675", "0.48697695", "0.48687255", "0.48408008", "0.48274562", "0.48268807", "0.48065925", "0.48054186", "0.47993994", "0.47852594", "0.4773295", "0.47650895", "0.47609308", "0.4751224", "0.47348177", "0.47248393", "0.4714932", "0.47136584", "0.47128025", "0.47109288", "0.4710886", "0.46897835", "0.46858948", "0.46809903", "0.4659959", "0.46559113", "0.4646321", "0.4643818", "0.4641152", "0.46332294", "0.46318832", "0.46299085", "0.4628544", "0.46242014", "0.46205977", "0.46192503", "0.4607804", "0.46063873" ]
0.8116978
0
delTargetPathInAttachment Delete a targetPath (stagingTargetPath) from the attachment
func delTargetPathInAttachment(attachment *model.VolumeAttachmentSpec, key string, TargetPath string) error { targetPathList, exist := attachment.Metadata[key] if !exist { return nil } paths := strings.Split(targetPathList, ";") for index, path := range paths { if path == TargetPath { paths = append(paths[:index], paths[index+1:]...) break } } if 0 == len(paths) { glog.V(5).Info("no more " + key) delete(attachment.Metadata, key) } else { attachment.Metadata[key] = strings.Join(paths, ";") } if KStagingTargetPath == key { volConnector := connector.NewConnector(attachment.DriverVolumeType) if volConnector == nil { msg := fmt.Sprintf("unsupport driverVolumeType: %s", attachment.DriverVolumeType) glog.Error(msg) return status.Error(codes.FailedPrecondition, msg) } err := volConnector.Detach(attachment.ConnectionData) if err != nil { msg := fmt.Sprintf("detach failed, %v", err) glog.Error(msg) return status.Errorf(codes.FailedPrecondition, "%s", msg) } attachment.Mountpoint = "-" } _, err := client.UpdateVolumeAttachment(attachment.Id, attachment) if err != nil { msg := "update volume attachment failed" glog.Error(msg) return status.Error(codes.FailedPrecondition, msg) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string) (newRev string, err error) {\n\treturn db.driverDB.DeleteAttachment(ctx, docID, rev, filename)\n}", "func (n *Client) DeleteAttachment(siteSlug string, pageSlug string, id int, options *Options) (result *Result) {\n\tu := fmt.Sprintf(\"/sites/%s/pages/%s/attachments/%d\", siteSlug, pageSlug, id)\n\tr := n.getRequest(\"DELETE\", u, options)\n\tresult = n.delete(r)\n\n\treturn\n}", "func (client DnsClient) deleteSteeringPolicyAttachment(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/steeringPolicyAttachments/{steeringPolicyAttachmentId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteSteeringPolicyAttachmentResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (*ItfparamsSecondary) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/secondary/%s\", ref)\n}", "func (cli *OpsGenieAlertV2Client) DeleteAttachment(req alertsv2.DeleteAlertAttachmentRequest) (*alertsv2.DeleteAlertAttachmentResponse, error) {\n\tvar response alertsv2.DeleteAlertAttachmentResponse\n\n\terr := cli.sendDeleteRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (m *Attachment) Remove() error {\n\treturn core.DeleteFile(m.PATH)\n}", "func (self *ProblemApplicationService) RemoveProblemAttachment(problemId ProblemId, filePath string) error {\n problem, err := self.problems.GetById(problemId)\n if err != nil {\n return err\n }\n\n newAttachments := []*Attachment{}\n\n // Attachment mit dem angegebenen Pfad finden.\n for _, a := range problem.Attachments {\n if a.FilePath != filePath {\n // Kopieren.\n newAttachments = append(newAttachments, a)\n }\n }\n\n problem.Attachments = newAttachments\n err = self.problems.Update(problem)\n if err != nil {\n return err\n }\n\n // Datei löschen.\n os.Remove(filePath)\n\n return nil\n}", "func (*HttpLslTag) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/lsl_tag/%s\", ref)\n}", "func (m *Message) RemoveAttachment(filename string) {\n\tdelete(m.attachments, filename)\n}", "func (m *wasiSnapshotPreview1Impl) pathUnlinkFile(pfd wasiFd, ppath list) (err wasiErrno) {\n\tpath, err := m.loadPath(ppath)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tdir, err := m.files.getDirectory(pfd, wasiRightsPathUnlinkFile)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := dir.UnlinkFile(path); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func (*SnmpTrap) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/trap/%s\", ref)\n}", "func (*CaVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}", "func (*CaHttpVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/http_verification_ca/%s\", ref)\n}", "func DeleteIssueAttachment(ctx *context.APIContext) {\n\t// swagger:operation DELETE /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueDeleteIssueAttachment\n\t// ---\n\t// summary: Delete an issue attachment\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: owner\n\t// in: path\n\t// description: owner of the repo\n\t// type: string\n\t// required: true\n\t// - name: repo\n\t// in: path\n\t// description: name of the repo\n\t// type: string\n\t// required: true\n\t// - name: index\n\t// in: path\n\t// description: index of the issue\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// - name: attachment_id\n\t// in: path\n\t// description: id of the attachment to delete\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// responses:\n\t// \"204\":\n\t// \"$ref\": \"#/responses/empty\"\n\t// \"404\":\n\t// \"$ref\": \"#/responses/error\"\n\n\tattachment := getIssueAttachmentSafeWrite(ctx)\n\tif attachment == nil {\n\t\treturn\n\t}\n\n\tif err := repo_model.DeleteAttachment(attachment, true); err != nil {\n\t\tctx.Error(http.StatusInternalServerError, \"DeleteAttachment\", err)\n\t\treturn\n\t}\n\n\tctx.Status(http.StatusNoContent)\n}", "func (client *Client) DeleteVolumeAttachment(serverID, id string) error {\n\tva, err := client.GetVolumeAttachment(serverID, id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = volumeattach.Delete(client.Compute, serverID, id).ExtractErr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\tmtdVol, err := metadata.LoadVolume(providers.FromClient(client), id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\terr = mtdVol.Detach(va)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting volume attachment %s: %s\", id, ProviderErrorToString(err))\n\t}\n\n\treturn nil\n}", "func (*ItfparamsPrimary) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/primary/%s\", ref)\n}", "func (*HttpCffAction) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/cff_action/%s\", ref)\n}", "func (*SpxTemplate) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/template/%s\", ref)\n}", "func (*ConditionObjref) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/condition/objref/%s\", ref)\n}", "func (c *MockFileStorageClient) DeleteMountTarget(ctx context.Context, id string) error {\n\treturn nil\n}", "func (s *Stack) DeleteVolumeAttachment(serverID, vaID string) error {\n\tif s == nil {\n\t\treturn scerr.InvalidInstanceError()\n\t}\n\tif serverID == \"\" {\n\t\treturn scerr.InvalidParameterError(\"serverID\", \"cannot be empty string\")\n\t}\n\tif vaID == \"\" {\n\t\treturn scerr.InvalidParameterError(\"vaID\", \"cannot be empty string\")\n\t}\n\n\tdefer concurrency.NewTracer(nil, \"('\"+serverID+\"', '\"+vaID+\"')\", true).WithStopwatch().GoingIn().OnExitTrace()()\n\n\tr := volumeattach.Delete(s.ComputeClient, serverID, vaID)\n\terr := r.ExtractErr()\n\tif err != nil {\n\t\treturn scerr.Wrap(err, fmt.Sprintf(\"error deleting volume attachment '%s': %s\", vaID, ProviderErrorToString(err)))\n\t}\n\treturn nil\n}", "func (*InterfaceTunnel) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/tunnel/%s\", ref)\n}", "func clearStagedDeviceInfo(ctx context.Context, stagingTargetPath, volumeId string) error {\n\tfields := LogFields{\"stagingTargetPath\": stagingTargetPath, \"volumeId\": volumeId}\n\tLogc(ctx).WithFields(fields).Trace(\">>>> clearStagedDeviceInfo\")\n\tdefer Logc(ctx).WithFields(fields).Trace(\"<<<< clearStagedDeviceInfo\")\n\n\tstagingFilename := path.Join(stagingTargetPath, volumePublishInfoFilename)\n\n\tif err := osFs.Remove(stagingFilename); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tLogc(ctx).WithFields(fields).Warning(\"Staging file does not exist.\")\n\t\t\treturn nil\n\t\t}\n\n\t\tLogc(ctx).WithFields(fields).WithError(err).Error(\"Removing staging file failed.\")\n\t\treturn err\n\t}\n\n\tLogc(ctx).WithField(\"stagingFilename\", stagingFilename).Debug(\"Removed staging file.\")\n\treturn nil\n}", "func (*HttpLocalSite) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/local_site/%s\", ref)\n}", "func (b *gsDBBackup) deleteTriggerFile(basename string) error {\n\tfilename := path.Join(b.triggerDir, basename)\n\tif err := os.Remove(filename); err != nil {\n\t\treturn fmt.Errorf(\"Unable to remove trigger file %s: %s\", filename, err)\n\t}\n\treturn nil\n}", "func (m *wasiSnapshotPreview1Impl) pathRemoveDirectory(pfd wasiFd, ppath list) (err wasiErrno) {\n\tpath, err := m.loadPath(ppath)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tdir, err := m.files.getDirectory(pfd, wasiRightsPathRemoveDirectory)\n\tif err != wasiErrnoSuccess {\n\t\treturn err\n\t}\n\n\tif ferr := dir.Rmdir(path); ferr != nil {\n\t\treturn fileErrno(ferr)\n\t}\n\treturn wasiErrnoSuccess\n}", "func (*CaHostKeyCert) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_key_cert/%s\", ref)\n}", "func (*HttpPacFile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/pac_file/%s\", ref)\n}", "func (*BgpSystem) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/system/%s\", ref)\n}", "func (d *Dao) DeleteTarget(c context.Context, id int64) (res int64, err error) {\n\tvar (\n\t\tr sql.Result\n\t\tnow = time.Now()\n\t)\n\tif r, err = d.db.Exec(c, _deleteTargetSQL, now, id); err != nil {\n\t\tlog.Error(\"d.UpdateGroup.Exec error(%+v), target(%d)\", err, id)\n\t\treturn\n\t}\n\tif res, err = r.RowsAffected(); err != nil {\n\t\tlog.Error(\"d.UpdateGroup.RowsAffected error(%+v), target(%d)\", err, id)\n\t}\n\treturn\n}", "func (*CaSigningCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/signing_ca/%s\", ref)\n}", "func (*CaHostCert) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/host_cert/%s\", ref)\n}", "func (*HttpException) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/exception/%s\", ref)\n}", "func (*HttpParentProxy) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/parent_proxy/%s\", ref)\n}", "func (client DnsClient) DeleteSteeringPolicyAttachment(ctx context.Context, request DeleteSteeringPolicyAttachmentRequest) (response DeleteSteeringPolicyAttachmentResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteSteeringPolicyAttachment, 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 = DeleteSteeringPolicyAttachmentResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteSteeringPolicyAttachmentResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteSteeringPolicyAttachmentResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteSteeringPolicyAttachmentResponse\")\n\t}\n\treturn\n}", "func (*CaMetaX509) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/meta_x509/%s\", ref)\n}", "func (p *Provisioner) DeleteHostPath(pv *v1.PersistentVolume) (err error) {\n\tdefer func() {\n\t\terr = errors.Wrapf(err, \"failed to delete volume %v\", pv.Name)\n\t}()\n\n\tsaName := getOpenEBSServiceAccountName()\n\t//Determine the path and node of the Local PV.\n\tpvObj := persistentvolume.NewForAPIObject(pv)\n\tpath := pvObj.GetPath()\n\tif path == \"\" {\n\t\treturn errors.Errorf(\"no HostPath set\")\n\t}\n\n\tnodeAffinityKey, nodeAffinityValue := pvObj.GetAffinitedNodeLabelKeyAndValue()\n\tif nodeAffinityValue == \"\" {\n\t\treturn errors.Errorf(\"cannot find affinited node details\")\n\t}\n\talertlog.Logger.Infof(\"Get the Node Object with label %v : %v\", nodeAffinityKey, nodeAffinityValue)\n\n\t//Get the node Object once again to get updated Taints.\n\tnodeObject, err := p.GetNodeObjectFromLabels(nodeAffinityKey, nodeAffinityValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttaints := GetTaints(nodeObject)\n\n\timagePullSecrets := GetImagePullSecrets(getOpenEBSImagePullSecrets())\n\n\t//Initiate clean up only when reclaim policy is not retain.\n\tklog.Infof(\"Deleting volume %v at %v:%v\", pv.Name, GetNodeHostname(nodeObject), path)\n\tcleanupCmdsForPath := []string{\"rm\", \"-rf\"}\n\tpodOpts := &HelperPodOptions{\n\t\tcmdsForPath: cleanupCmdsForPath,\n\t\tname: pv.Name,\n\t\tpath: path,\n\t\tnodeAffinityLabelKey: nodeAffinityKey,\n\t\tnodeAffinityLabelValue: nodeAffinityValue,\n\t\tserviceAccountName: saName,\n\t\tselectedNodeTaints: taints,\n\t\timagePullSecrets: imagePullSecrets,\n\t}\n\n\tif err := p.createCleanupPod(podOpts); err != nil {\n\t\treturn errors.Wrapf(err, \"clean up volume %v failed\", pv.Name)\n\t}\n\treturn nil\n}", "func (r *ResourceHandler) DeleteStageResource(project string, stage string, resourceURI string) error {\n\tr.ensureHandlerIsSet()\n\treturn r.resourceHandler.DeleteResourceByURI(context.TODO(), r.Scheme+\"://\"+r.BaseURL+v1ProjectPath+\"/\"+project+pathToStage+\"/\"+stage+pathToResource+\"/\"+url.QueryEscape(resourceURI))\n}", "func (a *AdminApiService) DeleteTarget(ctx _context.Context, id string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/admin/target/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(id, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func Del(c context.Context, path string) error {\n\treturn FromContext(c).Del(path)\n}", "func (*ItfparamsBridgePort) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/bridge_port/%s\", ref)\n}", "func deleteFile(ctx context.Context, baseDir, hash, extension string) error {\n\t// Verify object exists.\n\tfilepath := getPathByHash(ctx, baseDir, hash, extension)\n\n\treturn os.Remove(filepath)\n}", "func (*InterfaceBridge) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/bridge/%s\", ref)\n}", "func (*ItfparamsLinkAggregationGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/link_aggregation_group/%s\", ref)\n}", "func (*SpxGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/group/%s\", ref)\n}", "func (*ItfparamsGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/itfparams/group/%s\", ref)\n}", "func (*RemoteSyslogServer) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/remote_syslog/server/%s\", ref)\n}", "func (client ArtifactsClient) deleteGenericArtifactByPath(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/generic/repositories/{repositoryId}/artifactPaths/{artifactPath}/versions/{version}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteGenericArtifactByPathResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/registry/20160918/GenericArtifact/DeleteGenericArtifactByPath\"\n\t\terr = common.PostProcessServiceError(err, \"Artifacts\", \"DeleteGenericArtifactByPath\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (*HttpSpSubcat) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/sp_subcat/%s\", ref)\n}", "func (na *cnmNetworkAllocator) DeallocateAttachment(node *api.Node, networkAttachment *api.NetworkAttachment) error {\n\n\tdelete(na.nodes[node.ID], networkAttachment.Network.ID)\n\tif len(na.nodes[node.ID]) == 0 {\n\t\tdelete(na.nodes, node.ID)\n\t}\n\n\treturn na.releaseEndpoints([]*api.NetworkAttachment{networkAttachment})\n}", "func (client BaseClient) DeleteExpectation(ctx context.Context, pathParameter string) (result String, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: pathParameter,\n\t\t\tConstraints: []validation.Constraint{{Target: \"pathParameter\", Name: validation.Pattern, Rule: `.*`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"beacon.BaseClient\", \"DeleteExpectation\", err.Error())\n\t}\n\n\treq, err := client.DeleteExpectationPreparer(ctx, pathParameter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"DeleteExpectation\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteExpectationSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"DeleteExpectation\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteExpectationResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"DeleteExpectation\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (w *Watcher) DeleteTarget(targetName string) (error) {\n\tmutableMutex.Lock()\n\tdefer mutableMutex.Unlock()\n\tif w.TargetMap == nil {\n\t\tw.TargetMap = make(map[string]*Target)\n\t}\n\t_, ok := w.TargetMap[targetName]\n\tif !ok {\n\t\treturn errors.Errorf(\"not exist domain\")\n\t}\n\tdelete(w.TargetMap, targetName)\n\treturn nil\n}", "func (*RemoteSyslogGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/remote_syslog/group/%s\", ref)\n}", "func (*InterfacePppoe) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoe/%s\", ref)\n}", "func Delete(instructionData reflect.Value, finished chan bool) int {\n\tfmt.Println(\"FIBER INFO: Deleting File ...\")\n\n\tpath, err := variable.GetValue(instructionData, \"PathVarName\", \"PathIsVar\", \"Path\")\n\tif err != nil {\n\t\tfinished <- true\n\t\treturn -1\n\t}\n\n\tos.Remove(path.(string))\n\tfinished <- true\n\treturn -1\n}", "func (*InterfacePpp3G) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/ppp3g/%s\", ref)\n}", "func (*CaRsa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/rsa/%s\", ref)\n}", "func (*InterfacePppoa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppoa/%s\", ref)\n}", "func (*HttpProfile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/profile/%s\", ref)\n}", "func deleteVmdk(host string, vmdkPath string) error {\n\tsshCmd := fmt.Sprintf(\"rm -f %s\", vmdkPath)\n\tframework.Logf(\"Invoking command '%v' on ESX host %v\", sshCmd, host)\n\tresult, err := fssh.SSH(sshCmd, host+\":22\", framework.TestContext.Provider)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: '%s' on ESX host: %v\", sshCmd, err)\n\t}\n\treturn nil\n}", "func (*InterfaceEthernet) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/ethernet/%s\", ref)\n}", "func (*HttpCffProfile) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/cff_profile/%s\", ref)\n}", "func (*ConditionGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/condition/group/%s\", ref)\n}", "func (*CaCsr) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/csr/%s\", ref)\n}", "func (m *Client) DeleteTarget(arg0 context.Context, arg1 int64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteTarget\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (*HttpDeviceAuth) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/device_auth/%s\", ref)\n}", "func (d *driver) Delete(ctx context.Context, path string) error {\n\tdefer debugTime()()\n\td.rootlock.Lock()\n\tdefer d.rootlock.Unlock()\n\tlog.Error(\"roothash: \", d.roothash)\n\tnewParentHash, err := d.shell.Patch(d.roothash, \"rm-link\", path[1:])\n\tif err != nil {\n\t\tlog.Error(\"delete err: \", err)\n\t\tif err.Error() == \"merkledag: not found\" {\n\t\t\tfmt.Println(\"PATHNOTFOUND HAPPY HAPPY JOY JOY\")\n\t\t\treturn storagedriver.PathNotFoundError{Path: path}\n\t\t} else {\n\t\t\tfmt.Println(\"GOT A BAD ERROR: \", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\td.roothash = newParentHash\n\td.publishHash(newParentHash)\n\treturn nil\n}", "func (suite *fileTestSuite) TestLinkDeleteReadTarget() {\n\tfileName := suite.testPath + \"/small_write1.txt\"\n\tsymName := suite.testPath + \"/small.lnk\"\n\tf, err := os.Create(fileName)\n\tsuite.Equal(nil, err)\n\tf.Close()\n\terr = os.Symlink(fileName, symName)\n\tsuite.Equal(nil, err)\n\terr = ioutil.WriteFile(fileName, suite.minBuff, 0777)\n\tsuite.Equal(nil, err)\n\n\terr = os.Remove(symName)\n\tsuite.Equal(nil, err)\n\n\tdata, err := ioutil.ReadFile(fileName)\n\tsuite.Equal(nil, err)\n\tsuite.Equal(len(data), len(suite.minBuff))\n\n\terr = os.Symlink(fileName, symName)\n\tsuite.Equal(nil, err)\n\tsuite.fileTestCleanup([]string{fileName})\n\terr = os.Remove(symName)\n\tsuite.Equal(nil, err)\n}", "func (*BgpAmazonVpc) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/amazon_vpc/%s\", ref)\n}", "func (*SnmpGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/group/%s\", ref)\n}", "func (r *kRegister) DeleteTargetByService(svc *register.Service) error {\n\treturn fmt.Errorf(\"not implemented\")\n}", "func (*CaMetaCrl) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/meta_crl/%s\", ref)\n}", "func (*BgpNeighbor) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/neighbor/%s\", ref)\n}", "func (*BgpFilter) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/filter/%s\", ref)\n}", "func (*InterfacePppmodem) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppmodem/%s\", ref)\n}", "func (*CaCrl) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/crl/%s\", ref)\n}", "func (h testHelper) deleteFile(filename string) {\n\terr := os.Remove(filename)\n\tif err != nil {\n\t\th.Error(err)\n\t}\n}", "func DeleteFile(src string) {\n\tdatabase, err := GetDBIns()\n\tif err != nil {\n\t\tprintln(\"error in delete Tag:\", err.Error())\n\t}\n\n\tif deleteFileFromChaStmt == nil {\n\t\tdeleteFileFromChaStmt, err = database.Prepare(deleteFileFromCha)\n\t\tif err != nil {\n\t\t\tprintln(\"error in deleteFile init cha:\", err.Error())\n\t\t}\n\t}\n\n\tif deleteFileFromMapStmt == nil {\n\t\tdeleteFileFromMapStmt, err = database.Prepare(deleteFileFromMap)\n\t\tif err != nil {\n\t\t\tprintln(\"error in deleteFile init map:\", err.Error())\n\t\t}\n\t}\n\n\tdeleteFileFromChaStmt.Exec(src)\n\tdeleteFileFromMapStmt.Exec()\n}", "func (s *DataStore) DeleteLHVolumeAttachment(vaName string) error {\n\treturn s.lhClient.LonghornV1beta2().VolumeAttachments(s.namespace).Delete(context.TODO(), vaName, metav1.DeleteOptions{})\n}", "func (*BgpGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/group/%s\", ref)\n}", "func (*HttpDomainRegex) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/domain_regex/%s\", ref)\n}", "func (r *apiRegister) DeleteTargetByService(svc *register.Service) error {\n\treturn fmt.Errorf(\"Not Implemented\")\n}", "func deleteImage(t *testing.T, projectID string, imageName string) {\n\t// Load the Image ID saved by the earlier build_image stage\n\timage := gcp.FetchImage(t, projectID, imageName)\n\timage.DeleteImage(t)\n}", "func (is *ImageStoreLocal) DeleteBlobUpload(repo, uuid string) error {\n\tblobUploadPath := is.BlobUploadPath(repo, uuid)\n\tif err := os.Remove(blobUploadPath); err != nil {\n\t\tis.log.Error().Err(err).Str(\"blobUploadPath\", blobUploadPath).Msg(\"error deleting blob upload\")\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fsys *FS) Unlink(filePath string) (errc int) {\n\tdefer fs.Trace(filePath, \"\")(\"errc=%d\", &errc)\n\tleaf, parentDir, errc := fsys.lookupParentDir(filePath)\n\tif errc != 0 {\n\t\treturn errc\n\t}\n\treturn translateError(parentDir.Remove(leaf))\n}", "func RemoveTransferPath(id string, bind *types.Bind) error {\n\tmidPath, tarsferPath := getTransferPath(id, bind.HostPath)\n\tif err := releaseMountpoint(midPath); err != nil {\n\t\tlogrus.Errorf(\"RemoveTransferPath failed: %s\", err)\n\t}\n\tif err := releaseMountpoint(tarsferPath); err != nil {\n\t\tlogrus.Errorf(\"RemoveTransferPath failed: %s\", err)\n\t}\n\treturn nil\n}", "func (s *fsSource) processDelete(fileName string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif fileResorceKeys, ok := s.fileResorceKeys[fileName]; ok {\n\t\tfor _, fileResorceKey := range fileResorceKeys {\n\t\t\tif fileResorceKey != nil {\n\t\t\t\tdelete(s.shas, (*fileResorceKey).key)\n\t\t\t\ts.process(resource.Deleted, (*fileResorceKey).key, (*fileResorceKey).kind, nil)\n\t\t\t}\n\t\t}\n\t\tdelete(s.fileResorceKeys, fileName)\n\t}\n}", "func deletePemFile() {\n\terr := os.Remove(FILE)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}", "func (*CaGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/group/%s\", ref)\n}", "func (client StorageTargetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (*HttpGroup) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/group/%s\", ref)\n}", "func (c *Client) DeleteIssueAttachmentContext(ctx context.Context, issueIDOrKey string, attachmentID int) (*Attachment, error) {\n\tu := fmt.Sprintf(\"/api/v2/issues/%v/attachments/%v\", issueIDOrKey, attachmentID)\n\n\treq, err := c.NewRequest(\"DELETE\", u, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tattachment := new(Attachment)\n\tif err := c.Do(ctx, req, &attachment); err != nil {\n\t\treturn nil, err\n\t}\n\treturn attachment, nil\n}", "func (app *application) deleteFile(filePath string) error {\n\terr := os.Remove(filePath[22:])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client StorageTargetsClient) DeleteSender(req *http.Request) (future StorageTargetsDeleteFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (fs *Ipfs) Delete(path string) error {\n\t// Remoe file if on disk and unpinn\n\tif fname, err := fs.makeFilename(path); err == nil {\n\t\tos.Remove(fname)\n\t}\n\n\tipath := ipath.New(path)\n\treturn fs.coreAPI.Pin().Rm(context.Background(), ipath)\n}", "func deleteDevfile(devfile string) {\n\tif util.CheckPathExists(devfile) {\n\t\t_ = os.Remove(devfile)\n\t}\n}", "func DeleteDeviceTargetTemp(c *gin.Context) {\n\tdeviceName := c.Param(\"device_name\")\n\terr := database.DeleteDeviceTargetTemp(c, deviceName)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.Status(http.StatusOK)\n\t}\n}", "func (s *sifBundle) Delete() error {\n\tif s.writable {\n\t\tif err := tools.DeleteOverlay(s.bundlePath); err != nil {\n\t\t\treturn fmt.Errorf(\"delete error: %s\", err)\n\t\t}\n\t}\n\t// Umount rootfs\n\trootFsDir := tools.RootFs(s.bundlePath).Path()\n\tif err := syscall.Unmount(rootFsDir, syscall.MNT_DETACH); err != nil {\n\t\treturn fmt.Errorf(\"failed to unmount %s: %s\", rootFsDir, err)\n\t}\n\t// delete bundle directory\n\treturn tools.DeleteBundle(s.bundlePath)\n}", "func (a *AdminApiService) DeleteTargetSegment(ctx _context.Context, id string) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/admin/target-segment/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(id, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func _file_delete(call otto.FunctionCall) otto.Value {\n\tpath, _ := call.Argument(0).ToString()\n\n\terr := os.RemoveAll(path)\n\tif err != nil {\n\t\tjsThrow(call, err)\n\t}\n\treturn otto.Value{}\n}" ]
[ "0.59857553", "0.58011264", "0.5774773", "0.5725724", "0.5687675", "0.5605064", "0.5574031", "0.55115324", "0.55111235", "0.54902375", "0.54418415", "0.5436998", "0.54329175", "0.5408875", "0.54065794", "0.53955543", "0.53941584", "0.53936076", "0.53913915", "0.53885376", "0.53805184", "0.53624195", "0.53575134", "0.529433", "0.5254091", "0.52526116", "0.52519304", "0.52500844", "0.5241293", "0.5236524", "0.5231785", "0.5215036", "0.5214139", "0.5204336", "0.5201826", "0.52015126", "0.5200786", "0.51996315", "0.51941127", "0.5175074", "0.51659006", "0.5159008", "0.5143377", "0.5127016", "0.512145", "0.51053405", "0.5103246", "0.510109", "0.5094591", "0.5090511", "0.5069559", "0.50652444", "0.5063985", "0.5060219", "0.5005429", "0.5003295", "0.49966347", "0.499305", "0.49908352", "0.4990833", "0.49861515", "0.4984093", "0.49724475", "0.4963587", "0.49633044", "0.4963124", "0.49620908", "0.49616188", "0.49604458", "0.49559873", "0.49489415", "0.49364266", "0.49345008", "0.49304318", "0.49174118", "0.4911333", "0.4909694", "0.49059087", "0.48998606", "0.48996556", "0.48989144", "0.48869574", "0.48763254", "0.4866101", "0.48598465", "0.48586538", "0.48549554", "0.4848859", "0.48455933", "0.48442456", "0.4842275", "0.48421887", "0.48324332", "0.4831219", "0.48279926", "0.48197404", "0.4810251", "0.4808458", "0.4806188", "0.47926104" ]
0.79521245
0
NodeGetInfo gets information on a node
func (p *Plugin) NodeGetInfo( ctx context.Context, req *csi.NodeGetInfoRequest) ( *csi.NodeGetInfoResponse, error) { glog.Info("start to GetNodeInfo") defer glog.Info("end to GetNodeInfo") if client == nil { msg := "client is nil" glog.Error(msg) return nil, status.Error(codes.InvalidArgument, msg) } hostName, err := connector.GetHostName() if err != nil { msg := fmt.Sprintf("failed to get node name %v", err) glog.Error(msg) return nil, status.Error(codes.FailedPrecondition, msg) } var initiators []string volDriverTypes := []string{connector.FcDriver, connector.IscsiDriver} for _, volDriverType := range volDriverTypes { volDriver := connector.NewConnector(volDriverType) if volDriver == nil { glog.Errorf("unsupport volDriver: %s", volDriverType) continue } initiator, err := volDriver.GetInitiatorInfo() if err != nil { glog.Errorf("cannot get initiator for driver volume type %s, err: %v", volDriverType, err) continue } initiators = append(initiators, initiator) } if len(initiators) == 0 { msg := fmt.Sprintf("cannot get any initiator for host %s", hostName) glog.Error(msg) return nil, status.Error(codes.FailedPrecondition, msg) } nodeId := hostName + "," + strings.Join(initiators, ",") glog.Infof("node info is %s", nodeId) return &csi.NodeGetInfoResponse{ NodeId: nodeId, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *Driver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\td.log.WithField(\"method\", \"node_get_info\").Info(\"node get info called\")\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: d.hostID(),\n\t\tMaxVolumesPerNode: maxVolumesPerNode,\n\n\t\t// make sure that the driver works on this particular region only\n\t\tAccessibleTopology: &csi.Topology{\n\t\t\tSegments: map[string]string{\n\t\t\t\t\"region\": d.region,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (d *Driver) NodeGetInfo(ctx context.Context, request *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\td.log.WithField(\"method\", \"node_get_info\").Info(\"node get info called\")\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: d.nodeId,\n\t\tMaxVolumesPerNode: _defaultMaxAzureVolumeLimit,\n\n\t\t// make sure that the driver works on this particular region only\n\t\tAccessibleTopology: &csi.Topology{\n\t\t\tSegments: map[string]string{\n\t\t\t\t\"location\": d.az.Location,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (ns *nodeServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\ttopology := &csi.Topology{\n\t\tSegments: map[string]string{TopologyKeyNode: ns.nodeID},\n\t}\n\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: \tns.nodeID,\n\t\tMaxVolumesPerNode: ns.maxVolumePerNode,\n\t\tAccessibleTopology: topology,\n\t}, nil\n}", "func (ns *NodeServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: ns.Driver.nodeID,\n\t}, nil\n}", "func (d *nodeService) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\tklog.V(6).Infof(\"NodeGetInfo: called with args %+v\", req)\n\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: d.nodeID,\n\t}, nil\n}", "func (c *Client) NodeInfo() (*NodeInfoResponse, error) {\n\tbody := apiRequest{\n\t\tVersion: c.version,\n\t\tMethod: \"node.info\",\n\t}\n\n\tvar reply NodeInfoResponse\n\tif err := c.call(body, &reply); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &reply, nil\n}", "func (d FSSNodeDriver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\tad, err := d.util.LookupNodeAvailableDomain(d.KubeClient, d.nodeID)\n\n\tif err != nil {\n\t\td.logger.With(zap.Error(err)).With(\"nodeId\", d.nodeID, \"availableDomain\", ad).Error(\"Available domain of node missing.\")\n\t}\n\n\td.logger.With(\"nodeId\", d.nodeID, \"availableDomain\", ad).Info(\"Available domain of node identified.\")\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: d.nodeID,\n\t\t// make sure that the driver works on this particular AD only\n\t\tAccessibleTopology: &csi.Topology{\n\t\t\tSegments: map[string]string{\n\t\t\t\tkubeAPI.LabelZoneFailureDomain: ad,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (h *Hsc) getNodeInfo() (NodeInfo, error) {\n\tendpoint := fmt.Sprintf(\"%s/node_info\", h.LcdEndpoint)\n\tresp, err := http.Get(endpoint)\n\tif err != nil {\n\t\treturn NodeInfo{}, err\n\t}\n\n\tvar nodeInfo NodeInfo\n\tjdec := json.NewDecoder(resp.Body)\n\terr = jdec.Decode(&nodeInfo)\n\tif err != nil {\n\t\treturn NodeInfo{}, err\n\t}\n\n\treturn nodeInfo, nil\n}", "func (d *NodeDriver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\tad, err := d.util.lookupNodeAvailableDomain(d.KubeClient, d.nodeID)\n\n\tif err != nil {\n\t\td.logger.With(zap.Error(err)).With(\"nodeId\", d.nodeID, \"availableDomain\", ad).Error(\"Available domain of node missing.\")\n\t}\n\n\td.logger.With(\"nodeId\", d.nodeID, \"availableDomain\", ad).Info(\"Available domain of node identified.\")\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: d.nodeID,\n\t\tMaxVolumesPerNode: maxVolumesPerNode,\n\n\t\t// make sure that the driver works on this particular AD only\n\t\tAccessibleTopology: &csi.Topology{\n\t\t\tSegments: map[string]string{\n\t\t\t\tkubeAPI.LabelZoneFailureDomain: ad,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func GetNodeinfo(cfg *setting.Setting) (*crpc.NodeInfo, error) {\n\tvar ni *crpc.NodeInfo\n\terr := cfg.CallRPC(func(cl setting.RPCIF) error {\n\t\tvar err2 error\n\t\tni, err2 = cl.GetNodeinfo()\n\t\tlog.Println(cl, err2)\n\t\treturn err2\n\t})\n\treturn ni, err\n}", "func (l *Libvirt) NodeGetInfo() (rModel [32]int8, rMemory uint64, rCpus int32, rMhz int32, rNodes int32, rSockets int32, rCores int32, rThreads int32, err error) {\n\tvar buf []byte\n\n\tvar r response\n\tr, err = l.requestStream(6, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Model: [32]int8\n\t_, err = dec.Decode(&rModel)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Memory: uint64\n\t_, err = dec.Decode(&rMemory)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Cpus: int32\n\t_, err = dec.Decode(&rCpus)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Mhz: int32\n\t_, err = dec.Decode(&rMhz)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Nodes: int32\n\t_, err = dec.Decode(&rNodes)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Sockets: int32\n\t_, err = dec.Decode(&rSockets)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Cores: int32\n\t_, err = dec.Decode(&rCores)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Threads: int32\n\t_, err = dec.Decode(&rThreads)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (r *RPCClient) GetNodeInfo() (json.RawMessage, error) {\n\targs := RPCEmptyArguments{}\n\tvar reply json.RawMessage\n\terr := r.Client.Call(\"Node.Info\", &args, &reply)\n\treturn reply, err\n}", "func (n *Node) NodeInfo() *p2p.NodeInfo {\n\treturn n.adapter.NodeInfo()\n}", "func (k *Client) GetNodeInformation() (*NodeInformationResponse, error) {\n\tres, err := k.get(\"/\", nil)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"unable to retrieve server version\")\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode >= 400 {\n\t\terr := errors.New(res.Status)\n\t\tlogrus.WithError(err).Error(\"unable to retrieve server version\")\n\t\treturn nil, err\n\t}\n\n\tvar result NodeInformationResponse\n\terr = json.NewDecoder(res.Body).Decode(&result)\n\treturn &result, err\n}", "func (sn *SimNode) NodeInfo() *p2p.NodeInfo {\n\tserver := sn.Server()\n\tif server == nil {\n\t\treturn &p2p.NodeInfo{\n\t\t\tID: sn.ID.String(),\n\t\t\tEnode: sn.Node().String(),\n\t\t}\n\t}\n\treturn server.NodeInfo()\n}", "func (n *Node) Info(ctx context.Context) (err error) {\n\tinfo, err := n.Engine.Info(ctx)\n\tif err != nil {\n\t\tn.Available = false\n\t\tn.NodeInfo = err.Error()\n\t\treturn errors.WithStack(err)\n\t}\n\tbs, err := json.Marshal(info)\n\tif err != nil {\n\t\tn.NodeInfo = err.Error()\n\t\treturn errors.WithStack(err)\n\t}\n\tn.NodeInfo = string(bs)\n\treturn nil\n}", "func (d *Dice) NodeInfo(nodeRef entity.NodeReference) (types.NodeInfoOutput, error) {\n\tnode, err := d.findNode(nodeRef)\n\n\tif err != nil {\n\t\treturn types.NodeInfoOutput{}, err\n\t} else if node == nil {\n\t\treturn types.NodeInfoOutput{}, ErrNodeNotFound\n\t}\n\n\tnodeInfo := types.NodeInfoOutput{\n\t\tID: node.ID,\n\t\tName: node.Name,\n\t\tIsAttached: node.IsAttached,\n\t\tIsAlive: node.IsAlive,\n\t}\n\n\treturn nodeInfo, nil\n}", "func (ns *nodeSet) nodeInfo(nodeID string) (NodeInfo, error) {\n\tnode, ok := ns.nodes[nodeID]\n\tif ok {\n\t\treturn node, nil\n\t}\n\treturn NodeInfo{}, errNodeNotFound\n}", "func (ns *nodeSet) nodeInfo(nodeID string) (NodeInfo, error) {\n\tnode, ok := ns.nodes[nodeID]\n\tif ok {\n\t\treturn node, nil\n\t}\n\treturn NodeInfo{}, errNodeNotFound\n}", "func (p *peer) NodeInfo() NodeInfo {\r\n\treturn p.nodeInfo\r\n}", "func GetInfo(url string, id string, token string) (BaseNode, error) {\n\tclient := &http.Client{Timeout: time.Second * 30}\n\trequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn BaseNode{}, err\n\t}\n\tif id != \"\" {\n\t\tif token == \"\" {\n\t\t\treturn BaseNode{}, fmt.Errorf(\"missing token for authentication\")\n\t\t}\n\t\trequest.SetBasicAuth(id, token)\n\t}\n\n\tr, err := client.Do(request)\n\tif err != nil {\n\t\treturn BaseNode{}, err\n\t}\n\tdefer r.Body.Close()\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn BaseNode{}, err\n\t}\n\n\tnode := BaseNode{}\n\terr = json.Unmarshal(body, &node)\n\tif err != nil {\n\t\treturn BaseNode{}, err\n\t}\n\n\treturn node, nil\n}", "func (s *slimTrieStringly) NodeInfo(node interface{}) string {\n\tstep, hasStep := s.st.Steps.Get(stNodeID(node))\n\tif hasStep {\n\t\treturn fmt.Sprintf(\"+%d\", step)\n\t}\n\treturn \"\"\n}", "func (l *Libvirt) NodeGetSevInfo(Nparams int32, Flags uint32) (rParams []TypedParam, rNparams int32, err error) {\n\tvar buf []byte\n\n\targs := NodeGetSevInfoArgs {\n\t\tNparams: Nparams,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(395, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Params: []TypedParam\n\t_, err = dec.Decode(&rParams)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Nparams: int32\n\t_, err = dec.Decode(&rNparams)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (n *Node) Info(ctx context.Context) (*enginetypes.Info, error) {\n\tif n.Engine == nil {\n\t\treturn nil, ErrNilEngine\n\t}\n\t// TODO remove it later\n\tinfoCtx, cancel := context.WithTimeout(ctx, 120*time.Second)\n\tdefer cancel()\n\treturn n.Engine.Info(infoCtx)\n}", "func (nr NodeRecord) GetNodeInfo() (RecordInfo, error) {\n\treturn nr.Record, nil\n}", "func (a *Client) GetNodeInfo(params *GetNodeInfoParams) (*GetNodeInfoOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetNodeInfoParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetNodeInfo\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/node_info\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetNodeInfoReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetNodeInfoOK)\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 GetNodeInfo: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (api *PublicBlockChainAPI) GetNodeInfo() (interface{}, error) {\n\tbest := api.node.blockManager.GetChain().BestSnapshot()\n\tnode := api.node.blockManager.GetChain().BlockDAG().GetBlock(&best.Hash)\n\tpowNodes := api.node.blockManager.GetChain().GetCurrentPowDiff(node, pow.MEERXKECCAKV1)\n\tret := &json.InfoNodeResult{\n\t\tID: api.node.node.peerServer.PeerID().String(),\n\t\tVersion: int32(1000000*version.Major + 10000*version.Minor + 100*version.Patch),\n\t\tBuildVersion: version.String(),\n\t\tProtocolVersion: int32(protocol.ProtocolVersion),\n\t\tTotalSubsidy: best.TotalSubsidy,\n\t\tTimeOffset: int64(api.node.blockManager.GetChain().TimeSource().Offset().Seconds()),\n\t\tConnections: int32(len(api.node.node.peerServer.Peers().Connected())),\n\t\tPowDiff: &json.PowDiff{\n\t\t\tCurrentDiff: getDifficultyRatio(powNodes, api.node.node.Params, pow.MEERXKECCAKV1),\n\t\t},\n\t\tNetwork: params.ActiveNetParams.Name,\n\t\tConfirmations: blockdag.StableConfirmations,\n\t\tCoinbaseMaturity: int32(api.node.node.Params.CoinbaseMaturity),\n\t\tModules: []string{cmds.DefaultServiceNameSpace, cmds.MinerNameSpace, cmds.TestNameSpace, cmds.LogNameSpace},\n\t}\n\tret.GraphState = GetGraphStateResult(best.GraphState)\n\thostdns := api.node.node.peerServer.HostDNS()\n\tif hostdns != nil {\n\t\tret.DNS = hostdns.String()\n\t}\n\tif api.node.node.peerServer.Node() != nil {\n\t\tret.QNR = api.node.node.peerServer.Node().String()\n\t}\n\tif len(api.node.node.peerServer.HostAddress()) > 0 {\n\t\tret.Addresss = api.node.node.peerServer.HostAddress()\n\t}\n\n\t// soft forks\n\tret.ConsensusDeployment = make(map[string]*json.ConsensusDeploymentDesc)\n\tfor deployment, deploymentDetails := range params.ActiveNetParams.Deployments {\n\t\t// Map the integer deployment ID into a human readable\n\t\t// fork-name.\n\t\tvar forkName string\n\t\tswitch deployment {\n\t\tcase params.DeploymentTestDummy:\n\t\t\tforkName = \"dummy\"\n\n\t\tcase params.DeploymentToken:\n\t\t\tforkName = \"token\"\n\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Unknown deployment %v detected\\n\", deployment)\n\t\t}\n\n\t\t// Query the chain for the current status of the deployment as\n\t\t// identified by its deployment ID.\n\t\tdeploymentStatus, err := api.node.blockManager.GetChain().ThresholdState(uint32(deployment))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to obtain deployment status\\n\")\n\t\t}\n\n\t\t// Finally, populate the soft-fork description with all the\n\t\t// information gathered above.\n\t\tret.ConsensusDeployment[forkName] = &json.ConsensusDeploymentDesc{\n\t\t\tStatus: deploymentStatus.HumanString(),\n\t\t\tBit: deploymentDetails.BitNumber,\n\t\t\tStartTime: int64(deploymentDetails.StartTime),\n\t\t\tTimeout: int64(deploymentDetails.ExpireTime),\n\t\t}\n\n\t\tif deploymentDetails.PerformTime != 0 {\n\t\t\tret.ConsensusDeployment[forkName].Perform = int64(deploymentDetails.PerformTime)\n\t\t}\n\n\t\tif deploymentDetails.StartTime >= blockchain.CheckerTimeThreshold {\n\t\t\tif time.Unix(int64(deploymentDetails.ExpireTime), 0).After(best.MedianTime) {\n\t\t\t\tstartTime := time.Unix(int64(deploymentDetails.StartTime), 0)\n\t\t\t\tret.ConsensusDeployment[forkName].Since = best.MedianTime.Sub(startTime).String()\n\t\t\t}\n\t\t}\n\n\t}\n\treturn ret, nil\n}", "func (r *Resolver) GetInfo() *model.NodeInfo {\n\tioregOutput := runCommandOrFail(\"ioreg\", \"-rd1\", \"-c\", \"IOPlatformExpertDevice\")\n\thostname, _ := os.Hostname()\n\n\treturn &model.NodeInfo{\n\t\tVersion: r.version,\n\t\tUptime: 0,\n\t\tLabels: r.labels,\n\t\tArch: runtime.GOARCH,\n\t\tOS: runtime.GOOS,\n\t\tHostname: hostname,\n\t\tAddresses: getAddresses(),\n\t\tGrpcPort: r.grpcPort,\n\n\t\tMachineID: parseFieldFromIoregOutput(ioregOutput, \"IOPlatformSerialNumber\"),\n\t\tSystemUUID: parseFieldFromIoregOutput(ioregOutput, \"IOPlatformUUID\"),\n\t\tBootID: runCommandOrFail(\"/usr/bin/uuidgen\"),\n\n\t\tFilesystems: resolveFilesystems(),\n\t}\n}", "func (nd *Node) RequestInfo(name ...string) (map[string]string, error) {\n\tconn, err := nd.GetConnection(_DEFAULT_TIMEOUT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := RequestInfo(conn, name...)\n\tif err != nil {\n\t\tnd.InvalidateConnection(conn)\n\t\treturn nil, err\n\t}\n\tnd.PutConnection(conn)\n\treturn response, nil\n}", "func RequestNodeInfo(node *Node, name ...string) (map[string]string, error) {\n\tconn, err := node.GetConnection(_DEFAULT_TIMEOUT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := RequestInfo(conn, name...)\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn nil, err\n\t}\n\tnode.PutConnection(conn)\n\treturn response, nil\n}", "func (r *Resolver) GetInfo() *model.NodeInfo {\n\thostname, _ := os.Hostname()\n\treturn &model.NodeInfo{\n\t\tVersion: r.version,\n\t\tUptime: resolveUptime(),\n\t\tLabels: r.labels,\n\t\tArch: runtime.GOARCH,\n\t\tOS: runtime.GOOS,\n\t\tHostname: hostname,\n\t\tAddresses: getAddresses(),\n\t\tGrpcPort: r.grpcPort,\n\n\t\tMachineID: resolveFirst(\n\t\t\t\"MachineID\",\n\t\t\tfromEnv(\"MACHINE_ID\"),\n\t\t\tfromFiles([]string{\n\t\t\t\t\"/etc/machine-id\",\n\t\t\t\t\"/var/lib/dbus/machine-id\",\n\t\t\t}),\n\t\t\tstatic(\"unknown\"),\n\t\t),\n\n\t\tSystemUUID: resolveFirst(\n\t\t\t\"SystemUUID\",\n\t\t\tfromFiles([]string{\n\t\t\t\t\"/sys/class/dmi/id/product_uuid\",\n\t\t\t\t\"/proc/device-tree/system-id\",\n\t\t\t\t\"/proc/device-tree/vm,uuid\",\n\t\t\t\t\"/etc/machine-id\",\n\t\t\t}),\n\t\t\tstatic(\"unknown\"),\n\t\t),\n\n\t\tBootID: resolveFirst(\n\t\t\t\"BootID\",\n\t\t\tfromFiles([]string{\n\t\t\t\t\"/proc/sys/kernel/random/boot_id\",\n\t\t\t}),\n\t\t\tstatic(\"unknown\"),\n\t\t),\n\t\tFilesystems: resolveFilesystems(),\n\t}\n}", "func (ec *Client) NodeInfoAt(ctx context.Context) (*p2p.NodeInfo, error) {\n\tvar result p2p.NodeInfo\n\terr := ec.c.CallContext(ctx, &result, \"manage_nodeInfo\")\n\treturn (*p2p.NodeInfo)(&result), err\n}", "func (n *Node) Info() (fi os.FileInfo, fserr *Message) {\n\tvar err error\n\tif n.FileInfo == nil {\n\t\tif n.FileInfo, err = os.Stat(n.Path); err != nil {\n\t\t\tn.Err = ErrorMessage(fmt.Errorf(n.Path + err.Error()))\n\t\t}\n\t}\n\treturn n.FileInfo, n.Err\n}", "func (m SQSMonitor) getNodeInfo(instanceID string) (*NodeInfo, error) {\n\tresult, err := m.EC2.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{\n\t\t\taws.String(instanceID),\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok && aerr.Code() == \"InvalidInstanceID.NotFound\" {\n\t\t\tmsg := fmt.Sprintf(\"No instance found with instance-id %s\", instanceID)\n\t\t\tlog.Warn().Msg(msg)\n\t\t\treturn nil, skip{fmt.Errorf(msg)}\n\t\t}\n\t\treturn nil, err\n\t}\n\tif len(result.Reservations) == 0 || len(result.Reservations[0].Instances) == 0 {\n\t\tmsg := fmt.Sprintf(\"No reservation with instance-id %s\", instanceID)\n\t\tlog.Warn().Msg(msg)\n\t\treturn nil, skip{fmt.Errorf(msg)}\n\t}\n\n\tinstance := result.Reservations[0].Instances[0]\n\tinstanceJSON, _ := json.MarshalIndent(*instance, \" \", \" \")\n\tlog.Debug().Msgf(\"Got instance data from ec2 describe call: %s\", instanceJSON)\n\n\tif *instance.PrivateDnsName == \"\" {\n\t\tstate := \"unknown\"\n\t\t// safe access instance.State potentially being nil\n\t\tif instance.State != nil {\n\t\t\tstate = *instance.State.Name\n\t\t}\n\t\t// anything except running might not contain PrivateDnsName\n\t\tif state != ec2.InstanceStateNameRunning {\n\t\t\treturn nil, skip{fmt.Errorf(\"node: '%s' in state '%s'\", instanceID, state)}\n\t\t}\n\t\treturn nil, fmt.Errorf(\"unable to retrieve PrivateDnsName name for '%s' in state '%s'\", instanceID, state)\n\t}\n\n\tproviderID := \"\"\n\tif *instance.Placement.AvailabilityZone != \"\" {\n\t\tproviderID = fmt.Sprintf(\"aws:///%s/%s\", *instance.Placement.AvailabilityZone, instanceID)\n\t}\n\n\tnodeInfo := &NodeInfo{\n\t\tName: *instance.PrivateDnsName,\n\t\tInstanceID: instanceID,\n\t\tProviderID: providerID,\n\t\tTags: make(map[string]string),\n\t\tIsManaged: true,\n\t}\n\tfor _, t := range (*instance).Tags {\n\t\tnodeInfo.Tags[*t.Key] = *t.Value\n\t\tif *t.Key == ASGTagName {\n\t\t\tnodeInfo.AsgName = *t.Value\n\t\t}\n\t}\n\n\tif m.CheckIfManaged {\n\t\tif _, ok := nodeInfo.Tags[m.ManagedTag]; !ok {\n\t\t\tnodeInfo.IsManaged = false\n\t\t}\n\t}\n\n\tinfoJSON, _ := json.MarshalIndent(nodeInfo, \" \", \" \")\n\tlog.Debug().Msgf(\"Got node info from AWS: %s\", infoJSON)\n\n\treturn nodeInfo, nil\n}", "func (c *client) getNode(name string) (result, error) {\n\tnode, err := c.queryEndpoint(APINodesEndpoint, name+\"?memory=true\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(node) > 1 {\n\t\treturn nil, fmt.Errorf(\"Error: more than one result returned\")\n\t}\n\treturn node[0], nil\n}", "func NodeGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tif &node != nil {\n\t\tw.WriteHeader(200)\n\t\tif err := json.NewEncoder(w).Encode(node); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tparamError := swl.ParamError{\n\t\t\tError: \"Node not found\",\n\t\t}\n\t\tw.WriteHeader(404)\n\t\tif err := json.NewEncoder(w).Encode(paramError); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (node NodeInfo) String() string {\n\treturn \"NodeInfo: {\\n\\tnodeID:\" + strconv.Itoa(node.NodeID) + \", \\n\\tnodeIPAddr:\" + node.NodeIPAddr + \", \\n\\tport:\" + node.Port + \" \\n}\"\n}", "func GetNodeDetails(m serf.Member) (n *NodeDetails, err error) {\n\n\t// Validate server node\n\tok, role, dc := ValidateNode(m)\n\tif !ok {\n\t\treturn nil, errors.New(\"Invalid server node\")\n\t}\n\n\t// Get services\n\t// Services are meant to be encoded in this format: svc-1:port;svc-2:port\n\tservices := make([]NodeService, 0)\n\tif svcs, ok := m.Tags[\"services\"]; ok {\n\t\tfor _, svc := range strings.Split(svcs, \";\") {\n\t\t\tif strings.Contains(svc, \":\") {\n\t\t\t\tattrs := strings.Split(svc, \":\")\n\t\t\t\tif len(attrs) >= 2 {\n\n\t\t\t\t\t// Convert port to int\n\t\t\t\t\tp, e := strconv.Atoi(attrs[1])\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\terr = fmt.Errorf(\"service port cannot be converted to string: '%s'\", p)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tservices = append(services, NodeService{\n\t\t\t\t\t\tName: attrs[0],\n\t\t\t\t\t\tPort: p,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Invalid service attributes: '%s'\", svc)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid service attributes: '%s'\", svc)\n\t\t\t}\n\t\t}\n\t}\n\n\t// All nodes which have this tag are bootstrapped\n\t_, bootstrap := m.Tags[\"bootstrap\"]\n\n\tn = &NodeDetails{\n\t\tBootstrap: bootstrap,\n\t\tID: m.Tags[\"id\"],\n\t\tName: m.Name,\n\t\tRole: role,\n\t\tDataCenter: dc,\n\t\tAddr: m.Addr,\n\t\tServices: services,\n\t\tStatus: m.Status,\n\t\tTags: m.Tags,\n\t}\n\treturn\n}", "func GetNodeInfo() (*apiextensionsv1.CustomResourceDefinition, error) {\n\tnodeInfo := &apiextensionsv1.CustomResourceDefinition{}\n\tif err := yaml.Unmarshal(NodeInfoYAML, &nodeInfo); err != nil {\n\t\treturn nil, errors.Wrap(err, \"error unmarshalling embedded nodeInfo\")\n\t}\n\treturn nodeInfo, nil\n}", "func getNetworkInfo(ip string) (*nodeInfo, error) {\n\tiface, mask, err := interfaceByIP(ip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &nodeInfo{\n\t\tiface: iface,\n\t\tip: ip,\n\t\tnetmask: mask,\n\t}, nil\n}", "func (obj *GenericVariable) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func (rfm *ReadFileMgr) GetReadFileNodeInfo(fileHashStr string) (string, string) {\n\trfm.lock.Lock()\n\tdefer rfm.lock.Unlock()\n\tfi := rfm.readFileInfos[fileHashStr]\n\tif fi == nil || len(fi.Blocks) == 0 {\n\t\treturn \"\", \"\"\n\t}\n\treturn fi.Blocks[0].NodeAddr, fi.Blocks[0].NodeWalletAddr\n}", "func (jdn jobDirectoryNode) Info() os.FileInfo {\n\treturn jdn.info\n}", "func (p *Peer) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) {\n\tc, err := digestconv.DigestToCid(dgst)\n\tif err != nil {\n\t\treturn content.Info{}, errors.Wrapf(err, \"failed to convert digest %q to cid\", dgst)\n\t}\n\n\tfile, err := p.GetFile(ctx, c.String())\n\tif err != nil {\n\t\treturn content.Info{}, errors.Wrapf(err, \"failed to get node %q\", c)\n\t}\n\n\tsize, err := file.Size()\n\tif err != nil {\n\t\treturn content.Info{}, errors.Wrapf(err, \"failed to get size of %q\", c)\n\t}\n\n\tnow := time.Now()\n\treturn content.Info{\n\t\tDigest: dgst,\n\t\tSize: size,\n\t\tCreatedAt: now,\n\t\tUpdatedAt: now,\n\t}, nil\n}", "func getNode(nd *wssdcloud.Node) *cloud.Node {\n\treturn &cloud.Node{\n\t\tName: &nd.Name,\n\t\tLocation: &nd.LocationName,\n\t\tNodeProperties: &cloud.NodeProperties{\n\t\t\tFQDN: &nd.Fqdn,\n\t\t\tPort: &nd.Port,\n\t\t\tAuthorizerPort: &nd.AuthorizerPort,\n\t\t\tCertificate: &nd.Certificate,\n\t\t\tStatuses: getNodeStatuses(nd),\n\t\t},\n\t\tVersion: &nd.Status.Version.Number,\n\t}\n}", "func (obj *GenericObject) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func (s *Server) GetNode(w http.ResponseWriter, req *http.Request) {\n\tnode := req.Context().Value(\"node\").(*peer.Node)\n\n\ts.JSON(w, http.StatusOK, node.ID)\n}", "func (s *server) GetNode(context.Context, *goblinpb.GetNodeRequest) (*goblinpb.GetNodeResponse, error) {\n\treturn &goblinpb.GetNodeResponse{\n\t\tName: s.pool.GetName(),\n\t\tAddr: s.pool.GetMemberlistAddress(),\n\t}, nil\n}", "func (d donut) Info() (nodeDiskMap map[string][]string, err error) {\n\tnodeDiskMap = make(map[string][]string)\n\tfor nodeName, node := range d.nodes {\n\t\tdisks, err := node.ListDisks()\n\t\tif err != nil {\n\t\t\treturn nil, iodine.New(err, nil)\n\t\t}\n\t\tdiskList := make([]string, len(disks))\n\t\tfor diskOrder, disk := range disks {\n\t\t\tdiskList[diskOrder] = disk.GetPath()\n\t\t}\n\t\tnodeDiskMap[nodeName] = diskList\n\t}\n\treturn nodeDiskMap, nil\n}", "func GetInfo() (*Info, error) {\n\tvar result Info\n\terr := result.discover()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}", "func (c *Conn) GetNode(path ...NodeName) (Node, error) {\n\tvar node Node\n\terr := c.Request(\"get\", &node, pathToArgs(path)...)\n\treturn node, err\n}", "func (n *NodeInfo) Node() *v1.Node {\n\tif n == nil {\n\t\treturn nil\n\t}\n\treturn n.node\n}", "func (sc *SnowthClient) GetGossipInfo(node *SnowthNode) (gossip *Gossip, err error) {\n\tgossip = new(Gossip)\n\terr = sc.do(node, \"GET\", \"/gossip/json\", nil, gossip, decodeJSONFromResponse)\n\treturn\n}", "func (jfn jobFileNode) Info() os.FileInfo {\n\treturn jfn.info\n}", "func (obj *GenericDimension) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func (a API) GetAddedNodeInfo(cmd *btcjson.GetAddedNodeInfoCmd) (e error) {\n\tRPCHandlers[\"getaddednodeinfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (a *Client) NodeInspect(params *NodeInspectParams) (*NodeInspectOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewNodeInspectParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"NodeInspect\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/nodes/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &NodeInspectReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*NodeInspectOK), nil\n\n}", "func (c *NodeInfoCommand) Help() string {\n\treturn `Usage: wallet api nodeinfo\n`\n}", "func (y *YggdrasilAdminAPI) GetSelf() (nodeinfo NodeInfo, err error) {\n\n\tresp, err := y.execReq(`{\"keepalive\":true, \"request\":\"getSelf\"}`)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata := struct {\n\t\tSelf map[string]NodeInfo `json:\"self\"`\n\t}{}\n\tif err = json.Unmarshal(resp.Response, &data); err != nil {\n\t\treturn\n\t}\n\n\tfor k := range data.Self {\n\t\tnodeinfo = data.Self[k]\n\t\tnodeinfo.IPv6Addr = k\n\t\tbreak\n\t}\n\n\treturn nodeinfo, nil\n}", "func FetchNodeStats(http *helper.HTTP, host *url.URL) (interface{}, error) {\n\turi := strings.TrimSuffix(host.String(), \"/\") + NODES_LOCAL_STATS_PATH\n\tnodeBody := NodeStatsBody{}\n\n\tbody, err := http.FetchContent(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &nodeBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar nodeInfo NodeStatsInfo\n\tfor _, node := range nodeBody.Nodes {\n\t\tnodeInfo = node\n\t\tnodeInfo.ClusterName = nodeBody.ClusterName\n\t\tbreak\n\t}\n\n\treturn &nodeInfo, nil\n}", "func (r *RedisCli) ShortlinkInfo(eid string) (interface{}, error) {\n\td, err := r.Cli.Get(fmt.Sprintf(ShortlinkDetailKey, eid)).Result()\n\tif err == redis.Nil {\n\t\treturn \"\", errors.New(\"unknown short URL\")\n\t} else if err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn d, nil\n\t}\n}", "func (y *YarnMetrics) getNodeStatus() *NMNodeInfo {\n\tnmNodeStatus := &NMNodeStatus{}\n\terr := y.requestUrl(statusSuffix, nmNodeStatus)\n\tif err != nil {\n\t\tklog.Errorf(\"request nodemanager status err: %v\", err)\n\t\t// node is in lost state\n\t\tnmNodeStatus.NodeInfo = &NMNodeInfo{\n\t\t\tNodeHealthy: false,\n\t\t}\n\t}\n\tif nmNodeStatus.NodeInfo.NodeHealthy {\n\t\tnmNodeStatus.NodeInfo.NodeHealthyFloat = 1\n\t} else {\n\t\tnmNodeStatus.NodeInfo.NodeHealthyFloat = 0\n\t}\n\treturn nmNodeStatus.NodeInfo\n}", "func GetInfo(t *kernel.Task, stack *stack.Stack, outPtr hostarch.Addr, ipv6 bool) (linux.IPTGetinfo, *syserr.Error) {\n\t// Read in the struct and table name.\n\tvar info linux.IPTGetinfo\n\tif _, err := info.CopyIn(t, outPtr); err != nil {\n\t\treturn linux.IPTGetinfo{}, syserr.FromError(err)\n\t}\n\n\tvar err error\n\tif ipv6 {\n\t\t_, info, err = convertNetstackToBinary6(stack, info.Name)\n\t} else {\n\t\t_, info, err = convertNetstackToBinary4(stack, info.Name)\n\t}\n\tif err != nil {\n\t\tnflog(\"couldn't convert iptables: %v\", err)\n\t\treturn linux.IPTGetinfo{}, syserr.ErrInvalidArgument\n\t}\n\n\tnflog(\"returning info: %+v\", info)\n\treturn info, nil\n}", "func (c *nodeInfoClientKubernetes) GetNodeInfo() ([]*NodeInfo, error) {\n\ts, err := c.nodeInfoURL()\n\tif err != nil {\n\t\tlog.Debugf(\"SWARM: failed to build request url for %s %s=%s: %s\", c.namespace, c.labelKey, c.labelVal, err)\n\t\treturn nil, err\n\t}\n\n\trsp, err := c.client.Get(s)\n\tif err != nil {\n\t\tlog.Debugf(\"SWARM: request to %s %s=%s failed: %v\", c.namespace, c.labelKey, c.labelVal, err)\n\t\treturn nil, err\n\t}\n\n\tdefer rsp.Body.Close()\n\n\tif rsp.StatusCode > http.StatusBadRequest {\n\t\tlog.Debugf(\"SWARM: request failed, status: %d, %s\", rsp.StatusCode, rsp.Status)\n\t\treturn nil, fmt.Errorf(\"request failed, status: %d, %s\", rsp.StatusCode, rsp.Status)\n\t}\n\n\tb := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(b, rsp.Body); err != nil {\n\t\tlog.Debugf(\"SWARM: reading response body failed: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar il itemList\n\terr = json.Unmarshal(b.Bytes(), &il)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnodes := make([]*NodeInfo, 0)\n\tfor _, i := range il.Items {\n\t\taddr := net.ParseIP(i.Status.PodIP)\n\t\tif addr == nil {\n\t\t\tlog.Errorf(\"SWARM: failed to parse the ip %s\", i.Status.PodIP)\n\t\t\tcontinue\n\t\t}\n\t\tnodes = append(nodes, &NodeInfo{Name: i.Metadata.Name, Addr: addr, Port: c.port})\n\t}\n\tlog.Debugf(\"SWARM: got nodeinfo %d\", len(nodes))\n\treturn nodes, nil\n}", "func (i Info) String() string {\n\treturn \"NodeInfo:{IP:\" + i.IP + \", Port:\" + i.Port + \" }\"\n}", "func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error) {\n\tr := c.c.newRequest(\"GET\", \"/v1/catalog/node/\"+node)\n\tr.setQueryOptions(q)\n\trtt, resp, err := c.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer closeResponseBody(resp)\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tqm := &QueryMeta{}\n\tparseQueryMeta(resp, qm)\n\tqm.RequestTime = rtt\n\n\tvar out *CatalogNode\n\tif err := decodeBody(resp, &out); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn out, qm, nil\n}", "func (u *User) GetNode(nodeID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET NODE ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"nodes\"], nodeID)\n\n\tres, err := u.do(\"GET\", url, \"\", nil)\n\n\treturn res, err\n}", "func (hacker *Hacker) Info() string {\n\tvar result string\n\n\tif hacker.curNode != nil {\n\t\tresult = hacker.curNode.Info()\n\t} else {\n\t\tresult = hacker.style.Error()(`No data loaded. Use the [load \"path1\" \"path2\"] command.`)\n\t}\n\n\treturn result\n}", "func (p Plugin) Info(ctx context.Context, module string, vsn string) ([]byte, error) {\n\tresp, err := p.c.GetInfo(ctx, &stpb.GetModuleRequest{Module: module, Version: vsn})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.GetData(), nil\n}", "func GetNode(id int) NodeResponse {\n\tvar node NodeResponse\n\tresponse := network.Get(fmt.Sprintf(\"admin/nodes/%d\", id))\n\tjson.Unmarshal(response, &node)\n\n\treturn node\n}", "func getNodeVersion(def *cbgt.NodeDef) (*ComparableVersion, error) {\n\tif len(def.Extras) == 0 {\n\t\treturn nil, nil\n\t}\n\tvar extras nodeExtras\n\tif err := JSONUnmarshal([]byte(def.Extras), &extras); err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing node extras: %w\", err)\n\t}\n\treturn extras.Version, nil\n}", "func (c *Client) NodeStats(ctx context.Context, n *NodeInfo) (NodeStats, error) {\n\tvar start = time.Now()\n\tvar l = c.l.With(\"node\", n)\n\n\t// retrieve details from stats API\n\ts, err := c.d.ContainerStats(ctx, n.DockerID, false)\n\tif err != nil {\n\t\tl.Errorw(\"failed to get container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tdefer s.Body.Close()\n\tb, err := ioutil.ReadAll(s.Body)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tvar stats rawContainerStats\n\tif err = json.Unmarshal(b, &stats); err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// retrieve details from container inspection\n\tinfo, err := c.d.ContainerInspect(ctx, n.DockerID)\n\tif err != nil {\n\t\tl.Errorw(\"failed to inspect container\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tcreated, err := time.Parse(time.RFC3339, info.Created)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container detail\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// check disk usage\n\tusage, err := dirSize(n.DataDir)\n\tif err != nil {\n\t\tl.Errorw(\"failed to calculate disk usage\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to calculate disk usage\")\n\t}\n\n\t// get peer ID\n\tvar cfgPath = filepath.Join(n.DataDir, \"config\")\n\tpeer, err := getConfig(cfgPath)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read node configuration\", \"error\", err, \"path\", cfgPath)\n\t\treturn NodeStats{}, fmt.Errorf(\"failed to get network node configuration\")\n\t}\n\n\tc.l.Debugw(\"retrieved node container data\",\n\t\t\"network_id\", n.NetworkID,\n\t\t\"docker_id\", n.DockerID,\n\t\t\"stat.duration\", time.Since(start))\n\n\treturn NodeStats{\n\t\tPeerID: peer.Identity.PeerID,\n\t\tPeerKey: peer.Identity.PrivKey,\n\t\tUptime: time.Since(created),\n\t\tStats: stats,\n\t\tDiskUsage: usage,\n\t}, nil\n}", "func NodeStatus(runenv *runtime.RunEnv, btcAddr string, seq int64) (result float64, err error) {\n\tclient := http.Client{}\n\trequest, err := http.NewRequest(\"GET\", \"http://localhost:20443/v2/info\", nil)\n\tbtcPort := []string{\"28443\"}\n\tif (len(btcAddr) > 0 && seq != 1) {\n\t\tbtcConn := btcConnect(runenv, btcAddr, btcPort)\n\t\tif !btcConn {\n\t\t\tfakeHeight := (runenv.IntParam(\"stacks_tip_height\")+10) // ensure we'll cross the threshold\n\t\t\trunenv.RecordMessage(\"BTC Connection is closed -> Stopping this instance\")\n\t\t\trunenv.RecordMessage(\"Setting an artificial stacks_tip_height to: %v\", fakeHeight)\n\t\t\treturn float64(fakeHeight), nil\n\t\t}\n\t}\n\tif err != nil {\n\t\trunenv.RecordMessage(fmt.Sprintf(\"%s\", err))\n\t\treturn\n\t}\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\trunenv.RecordMessage(fmt.Sprintf(\"Waiting for node: [%s]\", err))\n\t\treturn\n\t}\n\tvar item map[string]interface{}\n\tjson.NewDecoder(resp.Body).Decode(&item)\n\trunenv.RecordMessage(fmt.Sprintf(\"Stacks block height => %.0f :: Burn block height => %.0f\", item[\"stacks_tip_height\"], item[\"burn_block_height\"]))\n\t// Extra info to tell us how many neighbors each instance has.\n\t// NodeNeighbors(runenv)\n\treturn item[\"stacks_tip_height\"].(float64), nil\n}", "func (info *BaseEndpointInfo) GetNodeName() string {\n\treturn info.NodeName\n}", "func (fm *FingerprintManager) getNode() *structs.Node {\n\tfm.nodeLock.Lock()\n\tdefer fm.nodeLock.Unlock()\n\treturn fm.node\n}", "func (d *DefaultDriver) GetNodeStatus(n node.Node) (*api.Status, error) {\n\treturn nil, &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"GetNodeStatus()\",\n\t}\n\n}", "func (h *Handler) GetNodeIP(object interface{}) (string, error) {\n\tswitch val := object.(type) {\n\tcase string:\n\t\tpod, err := h.Get(val)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn pod.Status.HostIP, nil\n\tcase *corev1.Pod:\n\t\treturn val.Status.HostIP, nil\n\tcase corev1.Pod:\n\t\treturn val.Status.HostIP, nil\n\tdefault:\n\t\treturn \"\", ErrInvalidToolsType\n\t}\n}", "func (vns *VirtualNetworkService) RetrieveInfo(ctx context.Context, vnID int) (*resources.VirtualNetwork, error) {\n\tdoc, err := vns.retrieveInfo(ctx, \"one.vn.info\", vnID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resources.CreateVirtualNetworkFromXML(doc.Root()), nil\n}", "func (n *NameService) RequestNodeStatus(nodeID fred.NodeID) (kgs []fred.Item) {\n\n}", "func (s *OsdCsiServer) NodeGetId(\n\tctx context.Context,\n\treq *csi.NodeGetIdRequest,\n) (*csi.NodeGetIdResponse, error) {\n\tclus, err := s.cluster.Enumerate()\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"Unable to Enumerate cluster: %s\", err)\n\t}\n\n\tresult := &csi.NodeGetIdResponse{\n\t\tNodeId: clus.NodeId,\n\t}\n\n\tlogrus.Infof(\"NodeId is %s\", result.NodeId)\n\n\treturn result, nil\n}", "func (s *NodeService) Status(ctx context.Context) (*GetNodeStatus, *http.Response, error) {\n\tvar responseStruct *GetNodeStatus\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"node/status\", nil, nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func netWkstaGetInfo() (wKSTAInfo102, uint32, error) {\n\tvar lpwi *wKSTAInfo102\n\tpLevel := uintptr(102)\n\n\tr1, _, _ := procNetWkstaGetInfo.Call(0, pLevel, uintptr(unsafe.Pointer(&lpwi)))\n\tdefer netApiBufferFree(lpwi)\n\n\tif ret := *(*uint32)(unsafe.Pointer(&r1)); ret != 0 {\n\t\treturn wKSTAInfo102{}, ret, errors.New(NetApiStatus[ret])\n\t}\n\n\tderef := *lpwi\n\treturn deref, 0, nil\n}", "func (ctx Context) GetNode(name string) (UniCloudNode, error) {\n\tvar result UniCloudNode\n\turl := fmt.Sprintf(\"https://%s:8443/v1/nodes/%s\", ctx.Address, name)\n\tdata, err := ctx.ucGetDelete(\"GET\", url)\n\tif err == nil {\n\t\terr = json.Unmarshal(data, &result)\n\t}\n\treturn result, err\n}", "func (c *Client) Info() (*boxutil.Info, error) {\n\tvar info boxutil.Info\n\tu, err := url.Parse(c.addr + \"/info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !u.IsAbs() {\n\t\treturn nil, errors.New(\"box address must be absolute\")\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Accept\", \"application/json; charset=utf-8\")\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\tif err := json.NewDecoder(resp.Body).Decode(&info); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &info, nil\n}", "func (a API) NodeGetRes() (out *None, e error) {\n\tout, _ = a.Result.(*None)\n\te, _ = a.Result.(error)\n\treturn \n}", "func print_node(node *Node) {\n fmt.Printf(\"%v\\n\", node)\n}", "func (pub *Publisher) GetNodeStatus(nodeHWID string, attrName types.NodeStatus) (value string, exists bool) {\n\tnode := pub.registeredNodes.GetNodeByHWID(nodeHWID)\n\tif node == nil {\n\t\treturn \"\", false\n\t}\n\tvalue, exists = node.Status[attrName]\n\treturn value, exists\n}", "func (obj *GenericMeasure) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func OvsDumpInfo(node stu.TestbedNode) {\n\tcmdStr := \"sudo ovs-vsctl show\"\n\toutput, _ := node.RunCommandWithOutput(cmdStr)\n\tlog.Debugf(\"ovs-vsctl on node %s: \\n%s\\n\", node.GetName(), output)\n}", "func (v *nodes) show(){\r\n\tfmt.Println(v.n)\r\n}", "func RequestNodeStats(node *Node) (map[string]string, error) {\n\tinfoMap, err := RequestNodeInfo(node, \"statistics\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := map[string]string{}\n\n\tv, exists := infoMap[\"statistics\"]\n\tif !exists {\n\t\treturn res, nil\n\t}\n\n\tvalues := strings.Split(v, \";\")\n\tfor i := range values {\n\t\tkv := strings.Split(values[i], \"=\")\n\t\tif len(kv) > 1 {\n\t\t\tres[kv[0]] = kv[1]\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (n *Node) GetAddr() string{\n return n.peer.GetAddr()\n}", "func (d *portworx) GetNodeStats(n node.Node) (map[string]map[string]int, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\n\tpxctlPath := d.getPxctlPath(n)\n\n\t// Create context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context create admin --token=%s\", pxctlPath, d.token), opts)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\tout, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s sv dump --nodestats -j\", pxctlPath), opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pxctl status. cause: %v\", err)\n\t}\n\n\tvar data interface{}\n\terr = json.Unmarshal([]byte(out), &data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal pxctl status. cause: %v\", err)\n\t}\n\n\t// Delete context\n\tif len(d.token) > 0 {\n\t\t_, err := d.nodeDriver.RunCommand(n, fmt.Sprintf(\"%s context delete admin\", pxctlPath), opts)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to delete pxctl context. cause: %v\", err)\n\t\t}\n\t}\n\n\tnodeStats := data.(map[string]interface{})\n\tdeleted := 0\n\tpending := 0\n\tskipped := 0\n\n\tif value, ok := nodeStats[\"relaxed_reclaim_stats\"].(map[string]interface{}); ok {\n\n\t\tif p, ok := value[\"pending\"]; ok {\n\t\t\tpending = int(p.(float64))\n\t\t}\n\n\t\tif d, ok := value[\"deleted\"]; ok {\n\t\t\tdeleted = int(d.(float64))\n\t\t}\n\n\t\tif s, ok := value[\"skipped\"]; ok {\n\t\t\tskipped = int(s.(float64))\n\t\t}\n\n\t}\n\n\tvar nodeStatsMap = map[string]map[string]int{}\n\tnodeStatsMap[n.Name] = map[string]int{}\n\tnodeStatsMap[n.Name][\"deleted\"] = deleted\n\tnodeStatsMap[n.Name][\"pending\"] = pending\n\tnodeStatsMap[n.Name][\"skipped\"] = skipped\n\n\treturn nodeStatsMap, nil\n}", "func getNode(ex SessionExecutor, msg CommonMessage) (rep CommonReply) {\n\tnodeMsg := msg.(nodeMessage)\n\n\tselectNodeTmpl := ex.getQuery(selectNodeOp)\n\tcn := newNode()\n\trows, err := ex.Query(fmt.Sprintf(selectNodeTmpl, nodeMsg.GetNodeTable()))\n\tif err != nil {\n\t\tdbLogger.Errorf(\"getNode query error:%s\", err)\n\t\treturn newNodeReply(nil, err)\n\t}\n\tdefer closeRowsAndLog(rows)\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&cn.name, &cn.ip, &cn.isCollector, &cn.duration, &cn.description, &cn.coords, &cn.address)\n\t\tif err != nil {\n\t\t\tdbLogger.Errorf(\"getNode fetch node row:%s\", err)\n\t\t\treturn newNodeReply(nil, err)\n\t\t}\n\t\t// Try to match the node.\n\t\tdbLogger.Infof(\"trying node matching with name:%s ip:%s\", cn.name, cn.ip)\n\t\tname, ip := nodeMsg.getNodeName(), nodeMsg.getNodeIP()\n\t\tif (name == cn.name && name != \"\") || (ip == cn.ip && ip != \"\") {\n\t\t\treturn newNodeReply(cn, nil)\n\t\t}\n\t}\n\n\treturn newNodeReply(nil, errNoNode)\n}", "func GetInfo(hostURL string, hostPort int) *bytes.Buffer {\n\treturn makeGetRequest(\"getinfo\", hostURL, hostPort)\n}", "func (group *NodeGroup) TemplateNodeInfo() (*nodeinfo.NodeInfo, error) {\n\ttemplate, err := group.getNodeTemplate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode, err := group.buildNodeFromTemplate(template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodeInfo := nodeinfo.NewNodeInfo()\n\terr = nodeInfo.SetNode(node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn nodeInfo, nil\n}", "func (ns *nodeServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {\n\tvolumePath := req.GetVolumePath()\n\tif volumePath == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"volumePath %v is empty\", volumePath)\n\t}\n\n\texists, err := utilpath.Exists(utilpath.CheckFollowSymlink, volumePath)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to check whether volumePath exists: %s\", err)\n\t}\n\tif !exists {\n\t\treturn nil, status.Errorf(codes.NotFound, \"target: %s not found\", volumePath)\n\t}\n\n\tstats, err := util.GetDeviceStats(volumePath)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to get stats by path: %s\", err)\n\t}\n\n\tklog.V(5).Infof(util.Log(ctx, \"get volumePath %q stats: %+v\"), volumePath, stats)\n\n\tif stats.Block {\n\t\treturn &csi.NodeGetVolumeStatsResponse{\n\t\t\tUsage: []*csi.VolumeUsage{\n\t\t\t\t{\n\t\t\t\t\tTotal: stats.TotalBytes,\n\t\t\t\t\tUnit: csi.VolumeUsage_BYTES,\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &csi.NodeGetVolumeStatsResponse{\n\t\tUsage: []*csi.VolumeUsage{\n\t\t\t{\n\t\t\t\tTotal: stats.TotalBytes,\n\t\t\t\tAvailable: stats.AvailableBytes,\n\t\t\t\tUsed: stats.UsedBytes,\n\t\t\t\tUnit: csi.VolumeUsage_BYTES,\n\t\t\t}, {\n\t\t\t\tTotal: stats.TotalInodes,\n\t\t\t\tAvailable: stats.AvailableInodes,\n\t\t\t\tUsed: stats.UsedInodes,\n\t\t\t\tUnit: csi.VolumeUsage_INODES,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (ng *NodeGroup) TemplateNodeInfo() (*schedulerframework.NodeInfo, error) {\n\t// Forge node template in a node group\n\tnode := &apiv1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%s-node-%d\", ng.Id(), rand.Int63()),\n\t\t\tLabels: ng.Template.Metadata.Labels,\n\t\t\tAnnotations: ng.Template.Metadata.Annotations,\n\t\t\tFinalizers: ng.Template.Metadata.Finalizers,\n\t\t},\n\t\tSpec: apiv1.NodeSpec{\n\t\t\tTaints: ng.Template.Spec.Taints,\n\t\t},\n\t\tStatus: apiv1.NodeStatus{\n\t\t\tCapacity: apiv1.ResourceList{},\n\t\t\tConditions: cloudprovider.BuildReadyConditions(),\n\t\t},\n\t}\n\n\t// Add the nodepool label\n\tif node.ObjectMeta.Labels == nil {\n\t\tnode.ObjectMeta.Labels = make(map[string]string)\n\t}\n\tnode.ObjectMeta.Labels[NodePoolLabel] = ng.Id()\n\n\tflavor, err := ng.Manager.getFlavorByName(ng.Flavor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get specs for flavor %q: %w\", ng.Flavor, err)\n\t}\n\n\tnode.Status.Capacity[apiv1.ResourcePods] = *resource.NewQuantity(110, resource.DecimalSI)\n\tnode.Status.Capacity[apiv1.ResourceCPU] = *resource.NewQuantity(int64(flavor.VCPUs), resource.DecimalSI)\n\tnode.Status.Capacity[gpu.ResourceNvidiaGPU] = *resource.NewQuantity(int64(flavor.GPUs), resource.DecimalSI)\n\tnode.Status.Capacity[apiv1.ResourceMemory] = *resource.NewQuantity(int64(flavor.RAM)*int64(math.Pow(1024, 3)), resource.DecimalSI)\n\n\tnode.Status.Allocatable = node.Status.Capacity\n\n\t// Setup node info template\n\tnodeInfo := schedulerframework.NewNodeInfo(cloudprovider.BuildKubeProxy(ng.Id()))\n\tnodeInfo.SetNode(node)\n\n\treturn nodeInfo, nil\n}", "func (c *nodes) Get(name string) (*api.Node, error) {\n\tresult := &api.Node{}\n\terr := c.r.Get().Resource(c.resourceName()).Name(name).Do().Into(result)\n\treturn result, err\n}", "func (uci *UCIAdapter) Info(info Info) {\n\tnps := int64(float64(info.nodeCount) / info.t.Seconds())\n\tuci.Send(fmt.Sprintf(\"info score cp %d depth %d nodes %d nps %d time %d pv %s\\n\", info.score,\n\t\tinfo.depth, info.nodeCount, nps, int(info.t/time.Millisecond), info.stk[0].pv.ToUCI()))\n}" ]
[ "0.8083621", "0.80416393", "0.8032256", "0.79784805", "0.79734296", "0.77872694", "0.7724819", "0.7664431", "0.7637843", "0.7607896", "0.75270414", "0.75109637", "0.7292019", "0.72062474", "0.7190351", "0.71745825", "0.7144341", "0.7059089", "0.7059089", "0.7025085", "0.6960411", "0.6945143", "0.671598", "0.6672938", "0.6596466", "0.6467701", "0.64659667", "0.6448776", "0.642573", "0.6381721", "0.6260805", "0.6250881", "0.6246235", "0.62209594", "0.6155864", "0.6127863", "0.6082304", "0.6058688", "0.6021088", "0.59481007", "0.58411777", "0.58401394", "0.58179873", "0.5811741", "0.58114004", "0.5795755", "0.579182", "0.5760894", "0.57578784", "0.57517666", "0.5730464", "0.56893843", "0.5680782", "0.5674201", "0.5661019", "0.56499445", "0.56347686", "0.5632572", "0.5627574", "0.5627186", "0.56120247", "0.56066936", "0.56003094", "0.5588225", "0.5586796", "0.55783236", "0.5570079", "0.5565399", "0.5543041", "0.5523757", "0.55120033", "0.5509064", "0.5490889", "0.5485428", "0.5479765", "0.5465656", "0.5459624", "0.5444282", "0.5442354", "0.5441951", "0.543966", "0.54390836", "0.54318327", "0.5428809", "0.54191065", "0.54146934", "0.5413916", "0.5409097", "0.5396243", "0.5396021", "0.53890747", "0.53800064", "0.53773403", "0.53669715", "0.53579295", "0.5347225", "0.53456223", "0.5335576", "0.53262573", "0.53255516" ]
0.8027612
3
Validate validates this Models multiple event level
func (m *ModelsMultipleEventLevel) Validate(formats strfmt.Registry) error { var res []error if err := m.validateEventLevel(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Event) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCommandPatch(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e VulnEvent) Validate() error {\n\tif e.SourceName == \"\" {\n\t\treturn fmt.Errorf(\"must set SourceName in event\")\n\t}\n\tif e.Asset.IPAddress == \"\" && e.Asset.Hostname == \"\" {\n\t\treturn fmt.Errorf(\"must set IPAddress or Hostname in event\")\n\t}\n\treturn nil\n}", "func (event Event) Validate() (err error) {\n\treturn\n}", "func (b *Event) Validate() []error {\n\terrorsList := []error{}\n\tif b.VisitorID == \"\" {\n\t\terrorsList = append(errorsList, errors.New(\"Visitor ID should not by empty\"))\n\t}\n\tif b.Type != \"CONTEXT\" {\n\t\terrorsList = append(errorsList, fmt.Errorf(\"Type %s, is not handled\", b.Type))\n\t}\n\n\tcontextErrs := b.Data.Validate()\n\tfor _, e := range contextErrs {\n\t\terrorsList = append(errorsList, e)\n\t}\n\treturn errorsList\n}", "func (m *Event) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEventType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMedium(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTimestamp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateEvents(aggregateID eventsourcing.AggregateRootID, currentVersion eventsourcing.Version, events []eventsourcing.Event) error {\n\taggregateType := events[0].AggregateType\n\n\tfor _, event := range events {\n\t\tif event.AggregateRootID != aggregateID {\n\t\t\treturn ErrEventMultipleAggregates\n\t\t}\n\n\t\tif event.AggregateType != aggregateType {\n\t\t\treturn ErrEventMultipleAggregateTypes\n\t\t}\n\n\t\tif currentVersion+1 != event.Version {\n\t\t\treturn ErrConcurrency\n\t\t}\n\n\t\tif event.Reason == \"\" {\n\t\t\treturn ErrReasonMissing\n\t\t}\n\n\t\tcurrentVersion = event.Version\n\t}\n\treturn nil\n}", "func (e Event) Validate() error {\n\tif e.Title == \"\" {\n\t\treturn errors.New(\"title cannot be empty\")\n\t}\n\tif e.Description == \"\" {\n\t\treturn errors.New(\"description cannot be empty\")\n\t}\n\treturn nil\n}", "func (a AddEventRequest) Validate() error {\n\tif err := contracts.Validate(a); err != nil {\n\t\treturn err\n\t}\n\n\t// BaseReading has the skip(\"-\") validation annotation for BinaryReading and SimpleReading\n\t// Otherwise error will occur as only one of them exists\n\t// Therefore, need to validate the nested BinaryReading and SimpleReading struct here\n\tfor _, r := range a.Event.Readings {\n\t\tif err := r.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a AddEventRequest) Validate() error {\n\tif err := v2.Validate(a); err != nil {\n\t\treturn err\n\t}\n\n\t// BaseReading has the skip(\"-\") validation annotation for BinaryReading and SimpleReading\n\t// Otherwise error will occur as only one of them exists\n\t// Therefore, need to validate the nested BinaryReading and SimpleReading struct here\n\tfor _, r := range a.Event.Readings {\n\t\tif err := r.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ut *EventPayload) Validate() (err error) {\n\tif ut.SportID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"sportId\"))\n\t}\n\tif ut.EventID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"eventId\"))\n\t}\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.SubTitle == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"subTitle\"))\n\t}\n\tif ut.StartDtTm == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"startDtTm\"))\n\t}\n\tif ut.EndDtTm == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"endDtTm\"))\n\t}\n\tif ut.LocationID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"locationId\"))\n\t}\n\tif ut.TeamAdvanceMethod == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"teamAdvanceMethod\"))\n\t}\n\treturn\n}", "func (ec EventContextV03) Validate() ValidationError {\n\terrors := map[string]error{}\n\n\t// type\n\t// Type: String\n\t// Constraints:\n\t// REQUIRED\n\t// MUST be a non-empty string\n\t// SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type.\n\teventType := strings.TrimSpace(ec.Type)\n\tif eventType == \"\" {\n\t\terrors[\"type\"] = fmt.Errorf(\"MUST be a non-empty string\")\n\t}\n\n\t// source\n\t// Type: URI-reference\n\t// Constraints:\n\t// REQUIRED\n\tsource := strings.TrimSpace(ec.Source.String())\n\tif source == \"\" {\n\t\terrors[\"source\"] = fmt.Errorf(\"REQUIRED\")\n\t}\n\n\t// subject\n\t// Type: String\n\t// Constraints:\n\t// OPTIONAL\n\t// MUST be a non-empty string\n\tif ec.Subject != nil {\n\t\tsubject := strings.TrimSpace(*ec.Subject)\n\t\tif subject == \"\" {\n\t\t\terrors[\"subject\"] = fmt.Errorf(\"if present, MUST be a non-empty string\")\n\t\t}\n\t}\n\n\t// id\n\t// Type: String\n\t// Constraints:\n\t// REQUIRED\n\t// MUST be a non-empty string\n\t// MUST be unique within the scope of the producer\n\tid := strings.TrimSpace(ec.ID)\n\tif id == \"\" {\n\t\terrors[\"id\"] = fmt.Errorf(\"MUST be a non-empty string\")\n\n\t\t// no way to test \"MUST be unique within the scope of the producer\"\n\t}\n\n\t// time\n\t// Type: Timestamp\n\t// Constraints:\n\t// OPTIONAL\n\t// If present, MUST adhere to the format specified in RFC 3339\n\t// --> no need to test this, no way to set the time without it being valid.\n\n\t// schemaurl\n\t// Type: URI\n\t// Constraints:\n\t// OPTIONAL\n\t// If present, MUST adhere to the format specified in RFC 3986\n\tif ec.SchemaURL != nil {\n\t\tschemaURL := strings.TrimSpace(ec.SchemaURL.String())\n\t\t// empty string is not RFC 3986 compatible.\n\t\tif schemaURL == \"\" {\n\t\t\terrors[\"schemaurl\"] = fmt.Errorf(\"if present, MUST adhere to the format specified in RFC 3986\")\n\t\t}\n\t}\n\n\t// datacontenttype\n\t// Type: String per RFC 2046\n\t// Constraints:\n\t// OPTIONAL\n\t// If present, MUST adhere to the format specified in RFC 2046\n\tif ec.DataContentType != nil {\n\t\tdataContentType := strings.TrimSpace(*ec.DataContentType)\n\t\tif dataContentType == \"\" {\n\t\t\terrors[\"datacontenttype\"] = fmt.Errorf(\"if present, MUST adhere to the format specified in RFC 2046\")\n\t\t} else {\n\t\t\t_, _, err := mime.ParseMediaType(dataContentType)\n\t\t\tif err != nil {\n\t\t\t\terrors[\"datacontenttype\"] = fmt.Errorf(\"if present, MUST adhere to the format specified in RFC 2046\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// datacontentencoding\n\t// Type: String per RFC 2045 Section 6.1\n\t// Constraints:\n\t// The attribute MUST be set if the data attribute contains string-encoded binary data.\n\t// Otherwise the attribute MUST NOT be set.\n\t// If present, MUST adhere to RFC 2045 Section 6.1\n\tif ec.DataContentEncoding != nil {\n\t\tdataContentEncoding := strings.ToLower(strings.TrimSpace(*ec.DataContentEncoding))\n\t\tif dataContentEncoding != Base64 {\n\t\t\terrors[\"datacontentencoding\"] = fmt.Errorf(\"if present, MUST adhere to RFC 2045 Section 6.1\")\n\t\t}\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\treturn nil\n}", "func (o *PostAPIV2EventsBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateAttributes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEntityID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEvent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *eventPayload) Validate() (err error) {\n\tif ut.SportID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"sportId\"))\n\t}\n\tif ut.EventID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"eventId\"))\n\t}\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.SubTitle == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"subTitle\"))\n\t}\n\tif ut.StartDtTm == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"startDtTm\"))\n\t}\n\tif ut.EndDtTm == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"endDtTm\"))\n\t}\n\tif ut.LocationID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"locationId\"))\n\t}\n\tif ut.TeamAdvanceMethod == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"teamAdvanceMethod\"))\n\t}\n\treturn\n}", "func (e *Event) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: e.Title, Name: \"Title\"},\n\t), nil\n}", "func (payload *PutEventPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (payload *putEventPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (m *DeviceStateChangedEvent) Validate() error {\n\tif err := m.Device.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif m.Device == nil {\n\t\treturn oops.BadRequest(\"field 'device' is required\")\n\t}\n\treturn nil\n}", "func (m *ChangeEventSlimEntity) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAuthors(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEndsAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironments(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateServices(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartsAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateUpdatedAt(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *AlertableEventType) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCategory(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScope(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (et EventType) Valid() bool {\n\tswitch et {\n\tcase Reopened, Closed, Renamed, Labeled, Unlabeled, CommentDeleted:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (m *MaventaEventDataDTO) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDestination(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvoiceNumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNetwork(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProfiles(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRecipientBid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRecipientName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *AuditLogEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRequestContext(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResults(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *LolPlayerLevelUpPlayerLevelUpEvent) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostAPIV2EventsParamsBodyAttributes) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCallback(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateHeaders(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *UpsertEventRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\tif utf8.RuneCountInString(m.GetName()) < 1 {\n\t\treturn UpsertEventRequestValidationError{\n\t\t\tfield: \"Name\",\n\t\t\treason: \"value length must be at least 1 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetParticipants()) < 4 {\n\t\treturn UpsertEventRequestValidationError{\n\t\t\tfield: \"Participants\",\n\t\t\treason: \"value length must be at least 4 runes\",\n\t\t}\n\t}\n\n\tfor idx, item := range m.GetSections() {\n\t\t_, _ = idx, item\n\n\t\tif v, ok := interface{}(item).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn UpsertEventRequestValidationError{\n\t\t\t\t\tfield: fmt.Sprintf(\"Sections[%v]\", idx),\n\t\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\t\tcause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (e *Event) Validate() error {\n\tif e.Message == \"\" || e.MessageOffset == \"\" || e.Time == nil || e.Type == \"\" {\n\t\treturn errs.ErrMissingParameters\n\t}\n\treturn nil\n}", "func (b *EventHit) Validate() []error {\n\terrorsList := b.validateBase()\n\tif b.Action == \"\" {\n\t\terrorsList = append(errorsList, errors.New(\"Event Action should not by empty\"))\n\t}\n\treturn errorsList\n}", "func (m *DeviceEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAction(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDevice(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateEvent(e interface{}) error {\n\tswitch v := e.(type) {\n\tcase *Event:\n\tcase *File:\n\tcase *Message:\n\tcase *RichMessage:\n\tcase *SystemMessage:\n\tcase Event:\n\tcase File:\n\tcase Message:\n\tcase RichMessage:\n\tcase SystemMessage:\n\tdefault:\n\t\treturn fmt.Errorf(\"event type %T not supported\", v)\n\t}\n\n\treturn nil\n}", "func ValidateEvent(e interface{}) error {\n\tswitch v := e.(type) {\n\tcase *Event:\n\tcase *File:\n\tcase *Message:\n\tcase *RichMessage:\n\tcase *SystemMessage:\n\tcase Event:\n\tcase File:\n\tcase Message:\n\tcase RichMessage:\n\tcase SystemMessage:\n\tdefault:\n\t\treturn fmt.Errorf(\"event type %T not supported\", v)\n\t}\n\n\treturn nil\n}", "func (m *SecurityArmStateEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateArmState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOptionalArguments(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *postEventPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (m *ConsoleLogEvent) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with RealtimeBuildEvent\n\tif err := m.RealtimeBuildEvent.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStepRecordID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTimelineID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTimelineRecordID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e EEventType) Validate() error {\n switch e {\n case EV_UNKNOWN,EV_BASE,EV_SCRIPT,EV_PERL,EV_BIN,EV_URL,EV_RESULT,EV_WORKER_DONE,EV_COMMAND,EV_REPLY,EV_ERROR:\n return nil\n default:\n return e // error condition - Error() can be invoked on it\n } // switch\n}", "func (m *MaxEarfcn) Validate() error {\n\treturn m.validate(false)\n}", "func (gs GenesisState) Validate() error {\n\tfor i, e := range gs.Evidence {\n\t\tif e == nil {\n\t\t\treturn fmt.Errorf(\"evidence %d cannot be nil\", i)\n\t\t}\n\t\tif err := e.ValidateBasic(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *GetEventsOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateEvents(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *Elevations1) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateElevations(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEndOuterElevations(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStartOuterElevations(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *PostEventPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (sel SelElitism) Validate() error {\n\treturn nil\n}", "func (sel SelTournament) Validate() error {\n\tif sel.NParticipants < 1 {\n\t\treturn errors.New(\"NParticipants should be higher than 0\")\n\t}\n\treturn nil\n}", "func (m *ErrorModel) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDetails(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTitle(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *IoK8sAPICoreV1Event) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEventTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFirstTimestamp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateInvolvedObject(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastTimestamp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMetadata(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRelated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSeries(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSource(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Aaa_Accounting_Events_Event) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Aaa_Accounting_Events_Event\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mt RoomCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m *ChangeEventSlimEntity) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAuthors(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEnvironments(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateServices(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *HookItems0) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateConfig(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEvents(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (videoClicks *VideoClicks) Validate(version Version) error {\n\terrors := make([]error, 0)\n\n\t// TODO(@DevKai): VAST3.0 require ClickThroughs not be empty.\n\n\tfor _, click := range videoClicks.ClickThroughs {\n\t\tif err := click.Validate(version); err != nil {\n\t\t\tve, ok := err.(ValidationError)\n\t\t\tif ok {\n\t\t\t\terrors = append(errors, ve.Errs...)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, click := range videoClicks.ClickTrackings {\n\t\tif err := click.Validate(version); err != nil {\n\t\t\tve, ok := err.(ValidationError)\n\t\t\tif ok {\n\t\t\t\terrors = append(errors, ve.Errs...)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, click := range videoClicks.CustomClicks {\n\t\tif err := click.Validate(version); err != nil {\n\t\t\tve, ok := err.(ValidationError)\n\t\t\tif ok {\n\t\t\t\terrors = append(errors, ve.Errs...)\n\t\t\t}\n\t\t}\n\t}\n\tif len(errors) > 0 {\n\t\treturn ValidationError{Errs: errors}\n\t}\n\treturn nil\n}", "func (m *EventsListResponse) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateEvents(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateModel(fields []string, model *Model) *handler.ProgressEvent {\n\treturn validator.ValidateModel(fields, model)\n}", "func (b EmployeeUpdatedEvent) ValidateEmployeeUpdatedEvent() error {\n\tvar validate *validator.Validate\n\tvalidate = validator.New()\n\terr := validate.Struct(b)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (t *OpenconfigSystem_System_Aaa_Authorization_Events_Event) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Aaa_Authorization_Events_Event\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *EventDescription) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (e NetEvent) Validate() (bool, error) {\n\tif !e.isValidated {\n\t\tif e.NetDevice == \"\" {\n\t\t\treturn false, fmt.Errorf(\"source device for event not specified\")\n\t\t}\n\t}\n\treturn true, nil\n}", "func (c *EventsCommand) Validate() error {\n\tif len(c.ChaincodeName) == 0 {\n\t\treturn errors.New(\"chaincode name not specified\")\n\t}\n\n\treturn nil\n}", "func (m NewModel) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tfor i := 0; i < len(m); i++ {\n\t\tif swag.IsZero(m[i]) { // not required\n\t\t\tcontinue\n\t\t}\n\n\t\tif m[i] != nil {\n\t\t\tif err := m[i].Validate(formats); err != nil {\n\t\t\t\tif ve, ok := err.(*errors.Validation); ok {\n\t\t\t\t\treturn ve.ValidateName(strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *TwoValidOneofs) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tswitch m.Message1.(type) {\n\n\tcase *TwoValidOneofs_M11:\n\t\t// no validation rules for M11\n\n\tcase *TwoValidOneofs_M12:\n\t\t// no validation rules for M12\n\n\t}\n\n\tswitch m.Message2.(type) {\n\n\tcase *TwoValidOneofs_M21:\n\t\t// no validation rules for M21\n\n\tcase *TwoValidOneofs_M22:\n\t\t// no validation rules for M22\n\n\t}\n\n\treturn nil\n}", "func (s StructInCustom) Validate() []string {\n\tvar errs []string\n\tif s.Name == \"\" {\n\t\terrs = append(errs, \"name::is_required\")\n\t}\n\n\treturn errs\n}", "func (ut *JSONDataMetaModule) Validate() (err error) {\n\tif ut.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"id\"))\n\t}\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\n\tfor _, e := range ut.Sensors {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m *IoK8sAPIEventsV1EventSeries) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastObservedTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r Record) validate(now time.Time) error {\n\tvar err error\n\n\t// Validate that certain fields are set.\n\tif r.Organization == \"\" {\n\t\terr = errorset.Append(err, errors.New(\"missing Organization\"))\n\t}\n\tif r.Environment == \"\" {\n\t\terr = errorset.Append(err, errors.New(\"missing Environment\"))\n\t}\n\tif r.GatewayFlowID == \"\" {\n\t\terr = errorset.Append(err, errors.New(\"missing GatewayFlowID\"))\n\t}\n\tif r.ClientReceivedStartTimestamp == 0 {\n\t\terr = errorset.Append(err, errors.New(\"missing ClientReceivedStartTimestamp\"))\n\t}\n\tif r.ClientReceivedEndTimestamp == 0 {\n\t\terr = errorset.Append(err, errors.New(\"missing ClientReceivedEndTimestamp\"))\n\t}\n\tif r.ClientReceivedStartTimestamp > r.ClientReceivedEndTimestamp {\n\t\terr = errorset.Append(err, errors.New(\"ClientReceivedStartTimestamp > ClientReceivedEndTimestamp\"))\n\t}\n\n\t// Validate that timestamps make sense.\n\tts := time.Unix(r.ClientReceivedStartTimestamp/1000, 0)\n\tif ts.After(now.Add(time.Minute)) { // allow a minute of tolerance\n\t\terr = errorset.Append(err, errors.New(\"ClientReceivedStartTimestamp cannot be in the future\"))\n\t}\n\tif ts.Before(now.Add(-90 * 24 * time.Hour)) {\n\t\terr = errorset.Append(err, errors.New(\"ClientReceivedStartTimestamp cannot be more than 90 days old\"))\n\t}\n\n\tfor _, attr := range r.Attributes {\n\t\tif validateErr := validateAttribute(attr); validateErr != nil {\n\t\t\terr = errorset.Append(err, validateErr)\n\t\t}\n\t}\n\n\treturn err\n}", "func (payload *updateListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (m Hook) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tfor i := 0; i < len(m); i++ {\n\n\t\tif swag.IsZero(m[i]) { // not required\n\t\t\tcontinue\n\t\t}\n\n\t\tif m[i] != nil {\n\n\t\t\tif err := m[i].Validate(formats); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *SE) Validate() error {\n\t// See tag \"require\"\n\tfor idx := range s.Reserved0 {\n\t\tif s.Reserved0[idx] != 0 {\n\t\t\treturn fmt.Errorf(\"'Reserved0[%d]' is expected to be 0, but it is %v\", idx, s.Reserved0[idx])\n\t\t}\n\t}\n\t// See tag \"require\"\n\tfor idx := range s.Reserved1 {\n\t\tif s.Reserved1[idx] != 0 {\n\t\t\treturn fmt.Errorf(\"'Reserved1[%d]' is expected to be 0, but it is %v\", idx, s.Reserved1[idx])\n\t\t}\n\t}\n\t// Recursively validating a child structure:\n\tif err := s.PostIBBHash.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"error on field 'PostIBBHash': %w\", err)\n\t}\n\t// Recursively validating a child structure:\n\tif err := s.Digest.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"error on field 'Digest': %w\", err)\n\t}\n\n\treturn nil\n}", "func (o *GetLogsByEventIDOKBodyItems0) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateTimestamp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *JSONDataMetaSensor) Validate() (err error) {\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.Key == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"key\"))\n\t}\n\tif ut.UnitOfMeasure == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"unitOfMeasure\"))\n\t}\n\tif ut.Ranges == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"ranges\"))\n\t}\n\tfor _, e := range ut.Ranges {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (r *Room) Validate() []error {\n\tvar errs []error\n\tfor i := range r.Towers {\n\t\tfor _, target := range r.Towers[i].Targets {\n\t\t\tfound := false\n\t\t\tfor _, source := range r.Towers[target].Targets {\n\t\t\t\tif source == i {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"Tower %d targets %d, but not vice-versa\", i, target))\n\t\t\t}\n\t\t}\n\t}\n\treturn errs\n}", "func (f *EmployeeFilters) Validate() error {\n\treturn v.ValidateStruct(f,\n\t\tv.Field(&f.IsForeman, v.Skip.When(f.IsForeman == \"\"), v.By(common.IsBool)),\n\t)\n}", "func (s *OpenconfigOfficeAp_System_Aaa_Authorization_Events_Event) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Aaa_Authorization_Events_Event\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ValidateCreateEvent(payload *model.CreateEventReq) error {\n\tif payload == nil {\n\t\terr := errors.New(\"invalid payload\")\n\t\treturn err\n\t}\n\n\tif strings.TrimSpace(payload.Title) == \"\" {\n\t\terr := errors.New(\"invalid title\")\n\t\treturn err\n\t}\n\n\tif payload.LocationID == 0 {\n\t\terr := errors.New(\"invalid location id\")\n\t\treturn err\n\t}\n\n\tif payload.StartDate.UTC().IsZero() {\n\t\terr := errors.New(\"invalid time. time format is YYYY:MM:dd HH:mm:ss\")\n\t\treturn err\n\t}\n\n\tif payload.EndDate.UTC().IsZero() {\n\t\terr := errors.New(\"invalid time. time format is YYYY:MM:dd HH:mm:ss\")\n\t\treturn err\n\t}\n\n\tif len(payload.TicketID) == 0 {\n\t\terr := errors.New(\"invalid ticket id\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mod ModSteadyState) Validate() error {\n\t// Check the selection method presence\n\tif mod.Selector == nil {\n\t\treturn errors.New(\"'Selector' cannot be nil\")\n\t}\n\t// Check the crossover method presence\n\tif mod.Crossover == nil {\n\t\treturn errors.New(\"'Crossover' cannot be nil\")\n\t}\n\t// Check the mutation rate in the presence of a mutator\n\tif mod.Mutator != nil && (mod.MutRate < 0 || mod.MutRate > 1) {\n\t\treturn errors.New(\"'MutRate' should belong to the [0, 1] interval\")\n\t}\n\treturn nil\n}", "func (_ *BaseAggregate) Validate() []error {\n\treturn nil\n}", "func (b EmployeeCreatedEvent) ValidateEmployeeCreatedEvent() error {\n\tvar validate *validator.Validate\n\tvalidate = validator.New()\n\terr := validate.Struct(b)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (chat *InitialChat) Validate() error {\n\tif chat.Thread != nil {\n\t\tfor _, e := range chat.Thread.Events {\n\t\t\tif err := ValidateEvent(e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Earfcn) Validate() error {\n\treturn m.validate(false)\n}", "func (s service) Validate(ctx context.Context, model documents.Model, old documents.Model) error {\n\treturn nil\n}", "func (x *MultipleCommand) Validate(args []string) error {\n\tif x.ConfigFileName == config.InputFileName {\n\t\treturn errors.New(\"cannot receive config file and input file from same source\")\n\t}\n\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Eutracgi) Validate() error {\n\treturn m.validate(false)\n}", "func (time CueTime) Validate() bool {\n\tret := true\n\tif ret == true && time.up != (Time{}) {\n\t\tret = time.up.Validate()\n\t}\n\n\tif ret == true && time.down != (Time{}) {\n\t\tret = time.down.Validate()\n\t}\n\n\tif ret == true && time.delay != (Delay{}) {\n\t\tret = time.delay.Validate()\n\t}\n\n\tif ret == true && time.follow != (Follow{}) {\n\t\tret = time.follow.Validate()\n\t}\n\n\tif ret != true {\n\t\tlog.Println(\"Failed to validate time '\" + time.value + \"'\")\n\t}\n\treturn ret\n}", "func (ut *jSONDataMetaSensor) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Key == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"key\"))\n\t}\n\tif ut.UnitOfMeasure == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"unitOfMeasure\"))\n\t}\n\tif ut.Ranges == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"ranges\"))\n\t}\n\tfor _, e := range ut.Ranges {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (e *Event) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (v BlockEventType) Validate() error {\n\tif !(v == \"block_added\" || v == \"block_removed\") {\n\t\treturn fmt.Errorf(\"api: invalid BlockEventType value: %q\", v)\n\t}\n\treturn nil\n}", "func (BeeStrategy) Validate(ctx request.Context, obj runtime.Object) field.ErrorList {\n\to := obj.(*insect.Bee)\n\tlog.Printf(\"Validating fields for Bee %s\\n\", o.Name)\n\terrors := field.ErrorList{}\n\t// perform validation here and add to errors using field.Invalid\n\treturn errors\n}", "func (t *Thali) Validate(v ...interface{}) error {\n\n\tif len(v) == 0 { // CREATE\n\t\tname := t.Name\n\t\tif len(name) < 3 {\n\t\t\treturn DSErr{When: time.Now(), What: \"validate venue invalid name \"}\n\t\t}\n\t\tif t.VenueId == int64(0) || t.UserId == int64(0) {\n\t\t\treturn DSErr{When: time.Now(), What: \"validate thali missing venue id \"}\n\t\t}\n\t\treturn nil\n\t} else { // UPDATE\n\t\tv0 := v[0]\n\t\tif reflect.TypeOf(v0).Kind() != reflect.Ptr {\n\t\t\treturn DSErr{When: time.Now(), What: \"validate thali pointer reqd\"}\n\t\t}\n\t\ts := reflect.TypeOf(v0).Elem()\n\t\tif _, ok := entities[s.Name()]; !ok {\n\t\t\treturn DSErr{When: time.Now(), What: \"validate want thali got \" + s.Name()}\n\t\t}\n\t\tswitch s.Name() {\n\t\tcase \"Thali\":\n\t\t\tv0v := reflect.ValueOf(v0).Elem()\n\t\t\tif v0v.Kind() != reflect.Struct {\n\t\t\t\treturn DSErr{When: time.Now(), What: \"validate needs struct arg got \" + v0v.Kind().String()}\n\t\t\t}\n\t\t\tif t.Id == int64(-999) {\n\t\t\t\tif t.Name == v0v.FieldByName(\"Name\").String() {\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\treturn DSErr{When: time.Now(), What: \"delete validate name \" + t.Name}\n\t\t\t\t}\n\t\t\t}\n\t\t\tset := 0\n\t\t\tfor i := 0; i < v0v.NumField(); i++ {\n\t\t\t\tuu := reflect.ValueOf(t).Elem()\n\t\t\t\tfi := uu.Field(i)\n\t\t\t\tvi := v0v.Field(i)\n\t\t\t\tif reflect.DeepEqual(fi.Interface(), reflect.Zero(fi.Type()).Interface()) {\n\t\t\t\t\tif vi.IsValid() {\n\t\t\t\t\t\tfi.Set(vi)\n\t\t\t\t\t\tset++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tname := t.Name\n\t\t\tif len(name) < 3 {\n\t\t\t\treturn DSErr{When: time.Now(), What: \"validate venue invalid name \"}\n\t\t\t}\n\t\t\tif t.VenueId == int64(0) || t.UserId == int64(0) {\n\t\t\t\treturn DSErr{When: time.Now(), What: \"validate thali missing venue id \"}\n\t\t\t}\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn DSErr{When: time.Now(), What: \"validate want thali got : \" + s.Name()}\n\t\t}\n\t\treturn nil\n\t}\n\n}", "func (m *UpsertEventResponse) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\treturn nil\n}", "func (m *TaskAllOf1) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateReason(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (mt *Vironpage) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"name\"))\n\t}\n\tif mt.Section == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"section\"))\n\t}\n\tif mt.Group == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"group\"))\n\t}\n\tif mt.Components == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"components\"))\n\t}\n\tfor _, e := range mt.Components {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (t *TaskHandlers) Validate() error {\n\t// Each\n\tfor name, handler := range *t {\n\t\tif err := ValidateHandler(handler); err != nil {\n\t\t\treturn &TaskError{err.Error(), &name, t.Tasks()}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *EventStatusMessage) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *MsgVpn) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAuthenticationBasicType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthenticationClientCertRevocationCheckMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthenticationClientCertUsernameSource(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuthorizationType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEgressFlowCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEgressMsgRateThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventEndpointCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventIngressFlowCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventIngressMsgRateThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventMsgSpoolUsageThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventPublishSubscriptionMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceAmqpConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceMqttConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceRestIncomingConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceSmfConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventServiceWebConnectionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventSubscriptionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventTransactedSessionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEventTransactionCountThreshold(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferIPVersion(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationBridgeAuthenticationScheme(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationEnabledQueueBehavior(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationRole(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReplicationTransactionMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateServiceRestMode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (gs GenesisState) Validate() error {\n\tseenDelegations := make(map[string]bool)\n\tseenMissCounters := make(map[string]bool)\n\tseenAggregates := make(map[string]bool)\n\n\tfor i, feederDelegation := range gs.FeederDelegations {\n\t\tif seenDelegations[feederDelegation.Validator] {\n\t\t\treturn fmt.Errorf(\"duplicated feeder delegation for validator %s at index %d\", feederDelegation.Validator, i)\n\t\t}\n\n\t\tdelegateAddr, err := sdk.AccAddressFromBech32(feederDelegation.Delegate)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid feeder delegate at index %d: %w\", i, err)\n\t\t}\n\n\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(feederDelegation.Validator)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid feeder validator at index %d: %w\", i, err)\n\t\t}\n\n\t\tif delegateAddr.Equals(validatorAddr) {\n\t\t\treturn fmt.Errorf(\"delegate address %s cannot be equal to validator address %s\", feederDelegation.Delegate, feederDelegation.Validator)\n\t\t}\n\t\tseenDelegations[feederDelegation.Validator] = true\n\t}\n\n\tfor i, missCounter := range gs.MissCounters {\n\t\tif seenMissCounters[missCounter.Validator] {\n\t\t\treturn fmt.Errorf(\"duplicated miss counter for validator %s at index %d\", missCounter.Validator, i)\n\t\t}\n\n\t\tif missCounter.Misses < 0 {\n\t\t\treturn fmt.Errorf(\"miss counter for validator %s cannot be negative: %d\", missCounter.Validator, missCounter.Misses)\n\t\t}\n\n\t\tif _, err := sdk.ValAddressFromBech32(missCounter.Validator); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid feeder at index %d: %w\", i, err)\n\t\t}\n\n\t\tseenMissCounters[missCounter.Validator] = true\n\t}\n\n\tif err := gs.Params.ValidateBasic(); err != nil {\n\t\treturn err\n\t}\n\n\tsupportedTypes := make(map[string]bool)\n\n\tfor _, dataType := range gs.Params.DataTypes {\n\t\tsupportedTypes[dataType] = true\n\t}\n\n\tfor _, aggregate := range gs.Aggregates {\n\t\tif aggregate.Height < 1 {\n\t\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidHeight, \"height (%d) cannot be zero or negative\", aggregate.Height)\n\t\t}\n\n\t\toracleData := aggregate.Data\n\t\tdataID := oracleData.GetID()\n\n\t\tif seenAggregates[dataID] {\n\t\t\treturn sdkerrors.Wrap(ErrDuplicatedOracleData, dataID)\n\t\t}\n\n\t\tif !supportedTypes[oracleData.Type()] {\n\t\t\treturn sdkerrors.Wrap(ErrUnsupportedDataType, oracleData.Type())\n\t\t}\n\n\t\tif err := oracleData.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tseenAggregates[dataID] = true\n\t}\n\n\treturn nil\n}", "func (payload *UpdateListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (e *Exhibition) Validate() (err ValidationError) {\n\tif len(e.Id) == 0 {\n\t\terr = err.Append(\"Invalid id: \" + e.Id + \" should not empty\")\n\t}\n\tif !IsUUID(e.GalleryId) {\n\t\terr = err.Append(\"Invalid gallery_id: \" + e.GalleryId + \" should be UUID\")\n\t}\n\treturn\n}", "func (m *TwoOneofs) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tswitch m.Message1.(type) {\n\n\tcase *TwoOneofs_M11:\n\t\t// no validation rules for M11\n\n\tcase *TwoOneofs_M12:\n\t\t// no validation rules for M12\n\n\t}\n\n\tswitch m.Message2.(type) {\n\n\tcase *TwoOneofs_M21:\n\t\t// no validation rules for M21\n\n\tcase *TwoOneofs_M22:\n\t\t// no validation rules for M22\n\n\t}\n\n\treturn nil\n}", "func (m *PartyProductEventAttributes) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateProviderStatusItems(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *StreamEventsRequest) Validate() error {\n\treturn m.validate(false)\n}", "func (f *EventFilter) Validate() error {\n\tif err := ValidateName(f.Name); err != nil {\n\t\treturn errors.New(\"filter name \" + err.Error())\n\t}\n\n\tif found := utilstrings.InArray(f.Action, EventFilterAllActions); !found {\n\t\treturn fmt.Errorf(\"action '%s' is not valid\", f.Action)\n\t}\n\n\tif len(f.Expressions) == 0 {\n\t\treturn errors.New(\"filter must have one or more expressions\")\n\t}\n\n\tif err := js.ParseExpressions(f.Expressions); err != nil {\n\t\treturn err\n\t}\n\n\tif f.Namespace == \"\" {\n\t\treturn errors.New(\"namespace must be set\")\n\t}\n\n\treturn nil\n}", "func (c *carHandler) validate(data []usecase.CarInput) error {\n\tfor _, e := range data {\n\t\tif e.ID <= 0 || e.Seats <= 0 {\n\t\t\treturn fmt.Errorf(\"Data is not valid\")\n\t\t}\n\t}\n\treturn nil\n}", "func (gs GenesisState) Validate() error {\n\t// Check for duplicated index in proposedUpgrade\n\tproposedUpgradeIndexMap := make(map[string]struct{})\n\n\tfor _, elem := range gs.ProposedUpgradeList {\n\t\tindex := string(ProposedUpgradeKey(elem.Plan.Name))\n\t\tif _, ok := proposedUpgradeIndexMap[index]; ok {\n\t\t\treturn fmt.Errorf(\"duplicated index for proposedUpgrade\")\n\t\t}\n\n\t\tproposedUpgradeIndexMap[index] = struct{}{}\n\t}\n\t// Check for duplicated index in approvedUpgrade\n\tapprovedUpgradeIndexMap := make(map[string]struct{})\n\n\tfor _, elem := range gs.ApprovedUpgradeList {\n\t\tindex := string(ApprovedUpgradeKey(elem.Plan.Name))\n\t\tif _, ok := approvedUpgradeIndexMap[index]; ok {\n\t\t\treturn fmt.Errorf(\"duplicated index for approvedUpgrade\")\n\t\t}\n\n\t\tapprovedUpgradeIndexMap[index] = struct{}{}\n\t}\n\t// Check for duplicated index in rejectedUpgrade\n\trejectedUpgradeIndexMap := make(map[string]struct{})\n\n\tfor _, elem := range gs.RejectedUpgradeList {\n\t\tindex := string(RejectedUpgradeKey(elem.Plan.Name))\n\t\tif _, ok := rejectedUpgradeIndexMap[index]; ok {\n\t\t\treturn fmt.Errorf(\"duplicated index for rejectedUpgrade\")\n\t\t}\n\t\trejectedUpgradeIndexMap[index] = struct{}{}\n\t}\n\t// this line is used by starport scaffolding # genesis/types/validate\n\n\treturn nil\n}" ]
[ "0.6573445", "0.64908814", "0.64641404", "0.6340679", "0.61598116", "0.6059661", "0.60326385", "0.6016257", "0.60144234", "0.60059893", "0.5987929", "0.59388363", "0.5934206", "0.5875102", "0.57630366", "0.5724798", "0.5706741", "0.5703617", "0.56843156", "0.5675789", "0.5666698", "0.56578416", "0.5642643", "0.5634975", "0.5617633", "0.5612325", "0.5606941", "0.5581038", "0.55698514", "0.55698514", "0.55534476", "0.5522921", "0.5490393", "0.54872394", "0.544407", "0.54421246", "0.5427835", "0.5426775", "0.5425049", "0.5423475", "0.54209954", "0.5403193", "0.5396085", "0.53959906", "0.5395673", "0.53927654", "0.5386732", "0.53857785", "0.5384772", "0.5371493", "0.5367419", "0.5364712", "0.5340575", "0.5340515", "0.53379136", "0.53367907", "0.5329913", "0.53266287", "0.5311841", "0.5304396", "0.5296805", "0.52932394", "0.5291228", "0.5285783", "0.5285325", "0.528085", "0.5279163", "0.52743244", "0.5266751", "0.5258335", "0.52538705", "0.5251885", "0.52490354", "0.52462995", "0.5241995", "0.5238899", "0.5233178", "0.5232646", "0.5225622", "0.52252185", "0.52243936", "0.52242947", "0.52181655", "0.52151287", "0.52042955", "0.5203011", "0.5202639", "0.52016556", "0.5200484", "0.5192973", "0.51928914", "0.5189035", "0.5188807", "0.5175558", "0.51753587", "0.517317", "0.5171651", "0.51700234", "0.51688707", "0.515292" ]
0.7368423
0
NewHealthController is constructer for HealthController
func NewHealthController() *HealthController { return new(HealthController) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewHealthController(router *mux.Router, r *render.Render) *HealthController {\n\tctrl := &HealthController{router, r}\n\tctrl.Register()\n\treturn ctrl\n}", "func NewHealthController(service *goa.Service, zapi_list ZAPIStructure) *HealthController {\n\treturn &HealthController{\n\t\tController: service.NewController(\"HealthController\"),\n\t\tzapi_list: zapi_list,\n\t}\n}", "func NewHealthController(service *goa.Service) *HealthController {\n\treturn &HealthController{Controller: service.NewController(\"HealthController\")}\n}", "func NewHealthController() *HealthController {\n\treturn &HealthController{}\n}", "func NewHealth(logger *log.Logger) health.Service {\n\treturn &healthsrvc{logger}\n}", "func NewHealth(r router) *Health {\n\treturn &Health{\n\t\trouter: r,\n\t}\n}", "func newHealthServiceHandler(db *sqlx.DB) (http.Handler, *healthz.StatusChecker) {\n\tstatus := healthz.NewStatusChecker(healthz.Healthy)\n\thealthMux := healthz.NewHealthServiceHandler(healthz.NewCheckers(), healthz.NewCheckers(status, healthz.NewPingChecker(db)))\n\n\treturn healthMux, status\n}", "func NewDeviceHealth()(*DeviceHealth) {\n m := &DeviceHealth{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func newHealthHandler(s *server) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"GET\" {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.TODO()\n\t\tif r.URL.Path == \"/local\" || r.URL.Path == \"/local/\" {\n\t\t\thandleLocalStatus(ctx, s, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tif r.URL.Path == \"/history\" || r.URL.Path == \"/history/\" {\n\t\t\thandleHistory(ctx, s, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tstatus, err := s.Status(ctx, nil)\n\t\tif err != nil {\n\t\t\troundtrip.ReplyJSON(w, http.StatusServiceUnavailable, map[string]string{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\n\t\thttpStatus := http.StatusOK\n\t\tif isDegraded(*status.GetStatus()) {\n\t\t\thttpStatus = http.StatusServiceUnavailable\n\t\t}\n\n\t\troundtrip.ReplyJSON(w, httpStatus, status.GetStatus())\n\t}\n}", "func NewHealth() Health {\n\treturn &health{\n\t\tlogger: logging.NewLogger(),\n\t}\n}", "func NewHealth(\n\tstate Status,\n\tmessage string,\n) Health {\n\treturn Health{\n\t\tStatus: state,\n\t\tUrgency: UNKNOWN, // set by the owning Monitor\n\t\tTime: time.Now(),\n\t\tMessage: Message(message),\n\t\tDuration: 0,\n\t}\n}", "func NewHealth() *Health {\n\treturn &Health{\n\t\tcomponents: map[interface{}]*HealthComponentStatus{},\n\t}\n}", "func NewHealthCheckController(\n\tlogger logging.LoggerInterface,\n\tappMonitor application.MonitorIterface,\n\tdependenciesMonitor services.MonitorIterface,\n) *HealthCheckController {\n\treturn &HealthCheckController{\n\t\tlogger: logger,\n\t\tappMonitor: appMonitor,\n\t\tdependenciesMonitor: dependenciesMonitor,\n\t}\n}", "func newHCDummy(logPrefix string, json JSONMap) *HCDummy {\n\thc := new(HCDummy)\n\thc.HCBase = &HCBase{}\n\thc.hcType = json[\"type\"].(string)\n\n\tif result, ok := json[\"result\"].(HCResult); ok {\n\t\thc.result = result\n\t}\n\n\thc.logPrefix = logPrefix + fmt.Sprintf(\"healthcheck: %s response: %s \", hc.hcType, hc.result)\n\n\tlogger.Info.Printf(hc.logPrefix + \"created\")\n\treturn hc\n}", "func New() *Health {\n\treturn &Health{\n\t\tStatus: StatusUnknown,\n\t\tDetails: make(map[string]interface{}),\n\t}\n}", "func NewController() *Controller {\n controller := Controller{}\n\n return &controller\n}", "func NewHealth() *Health {\n\treturn NewHealthOnPort(healthPort)\n}", "func newHelloController(helloService HelloService) *helloController {\n\treturn &helloController{\n\t\thelloService: helloService,\n\t}\n}", "func (c *MockController) Health() error {\n\tc.HealthFuncCalled++\n\n\treturn c.HealthFunc()\n}", "func (c *HealthController) Health(ctx *app.HealthHealthContext) error {\n\t// HealthController_Health: start_implement\n\tver := \"unknown\"\n\tsemVer, err := semver.Make(MajorMinorPatch + \"-\" + ReleaseType + \"+git.sha.\" + GitCommit)\n\tif err == nil {\n\t\tver = semVer.String()\n\t}\n\treturn ctx.OK([]byte(\"Health OK: \" + time.Now().String() + \", semVer: \" + ver + \"\\n\"))\n\t// HealthController_Health: end_implement\n}", "func (a *API) health(c *gin.Context) (*Health, error) {\n\treturn &Health{\n\t\tStatus: \"OK\",\n\t}, nil\n}", "func New(opts ...Option) (*Health, error) {\n\th := &Health{\n\t\tchecks: make(map[string]Config),\n\t\ttp: trace.NewNoopTracerProvider(),\n\t\tmaxConcurrent: runtime.NumCPU(),\n\t}\n\n\tfor _, o := range opts {\n\t\tif err := o(h); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn h, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"podhealth-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource PodHealth\n\terr = c.Watch(&source.Kind{Type: &trainingv1alpha1.PodHealth{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenqueueAllPodHealthsInNamespace := &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(obj handler.MapObject) (requests []reconcile.Request) {\n\t\t\tctx := context.Background()\n\n\t\t\t// List all PodHealth objects in the same Namespace\n\t\t\tpodHealthList := &trainingv1alpha1.PodHealthList{}\n\t\t\tif err := mgr.GetClient().List(ctx, podHealthList, client.InNamespace(obj.Meta.GetNamespace())); err != nil {\n\t\t\t\tutilruntime.HandleError(err)\n\t\t\t\treturn requests\n\t\t\t}\n\n\t\t\t// Add all PodHealth objects to the workqueue\n\t\t\tfor _, podHealth := range podHealthList.Items {\n\t\t\t\trequests = append(requests, reconcile.Request{\n\t\t\t\t\tNamespacedName: types.NamespacedName{\n\t\t\t\t\t\tName: podHealth.Name,\n\t\t\t\t\t\tNamespace: podHealth.Namespace,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn requests\n\t\t}),\n\t}\n\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, enqueueAllPodHealthsInNamespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *controller) health(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(\"health check\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func NewController(client kubernetes.Interface) *Controller {\n\tshared := informers.NewSharedInformerFactory(client, time.Second*30)\n\tinform := shared.Apps().V1().Deployments()\n\tcontrl := &Controller{\n\t\tclient: client,\n\t\tinformer: inform.Informer(),\n\t\tlister: inform.Lister(),\n\t\tlogger: logrus.New(),\n\t\tqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"regitseel\"),\n\t}\n\n\tinform.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: contrl.enqueue,\n\t\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\t\tcontrl.enqueue(new)\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\td := obj.(*appsv1.Deployment)\n\t\t\t\tif err := contrl.delete(d); err != nil {\n\t\t\t\t\tcontrl.logger.Errorf(\"failed to delete from api: %v\", d.Name)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t)\n\n\treturn contrl\n}", "func health(c echo.Context) error {\n\th := &Health{\"Fluffy Radio Api\", \"1.0.0\", \"Just Keep Fluffing!\"}\n\treturn c.JSON(http.StatusOK, h)\n}", "func newResourceHealthClient(subscriptionID string, baseURI string, authorizer autorest.Authorizer) resourcehealth.AvailabilityStatusesClient {\n\thealthClient := resourcehealth.NewAvailabilityStatusesClientWithBaseURI(baseURI, subscriptionID)\n\tazure.SetAutoRestClientDefaults(&healthClient.Client, authorizer)\n\treturn healthClient\n}", "func New(transport runtime.ClientTransport, formats strfmt.Registry) *CiliumHealthAPI {\n\t// ensure nullable parameters have default\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\n\tcli := new(CiliumHealthAPI)\n\tcli.Transport = transport\n\tcli.Connectivity = connectivity.New(transport, formats)\n\tcli.Restapi = restapi.New(transport, formats)\n\treturn cli\n}", "func NewController(\n\tctx context.Context,\n\tcmw configmap.Watcher,\n) *controller.Impl {\n\tlogger := logging.FromContext(ctx)\n\n\tbrokercellInformer := brokercell.Get(ctx)\n\tbrokerLister := brokerinformer.Get(ctx).Lister()\n\tdeploymentLister := deploymentinformer.Get(ctx).Lister()\n\tsvcLister := serviceinformer.Get(ctx).Lister()\n\tepLister := endpointsinformer.Get(ctx).Lister()\n\thpaLister := hpainformer.Get(ctx).Lister()\n\n\tbase := reconciler.NewBase(ctx, controllerAgentName, cmw)\n\tr, err := NewReconciler(base, brokerLister, svcLister, epLister, deploymentLister)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed to create BrokerCell reconciler\", zap.Error(err))\n\t}\n\tr.hpaLister = hpaLister\n\timpl := v1alpha1brokercell.NewImpl(ctx, r)\n\n\tlogger.Info(\"Setting up event handlers.\")\n\n\t// TODO(https://github.com/google/knative-gcp/issues/912) Change period back to 5 min once controller\n\t// watches for data plane components.\n\tbrokercellInformer.Informer().AddEventHandlerWithResyncPeriod(controller.HandleAll(impl.Enqueue), 30*time.Second)\n\n\t// Watch data plane components created by brokercell so we can update brokercell status immediately.\n\t// 1. Watch deployments for ingress, fanout and retry\n\tdeploymentinformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\t// 2. Watch ingress endpoints\n\tendpointsinformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\t// 3. Watch hpa for ingress, fanout and retry deployments\n\thpainformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\n\treturn impl\n}", "func New(svc healthcheck.Service, groups ...*echo.Group) {\n\th := HTTP{svc}\n\tv1 := groups[0].Group(\"/healthcheck\")\n\tv2 := groups[1].Group(\"/healthcheck\")\n\n\t//define /V1/healtcheck methods\n\tv1.GET(\"/:value\", h.get)\n\tv1.POST(\"/paginationtest\", h.getPagedList)\n\tv1.POST(\"\", h.post)\n\n\t//define /V2/healtcheck methods\n\tv2.GET(\"/:value\", h.getV2)\n}", "func newReconciler(mgr manager.Manager) reconcile.Reconciler {\n\treturn &ReconcilePodHealth{client: mgr.GetClient(), scheme: mgr.GetScheme()}\n}", "func newLoadBalancerController(c *client.Client, namespace string,\n\tdomain string, nodes []string) *loadBalancerController {\n\tmgr := &haproxy.HAProxyManager{\n\t\tExec: exec.New(),\n\t\tConfigFile: \"haproxy.cfg\",\n\t\tDomainName: domain,\n\t}\n\n\tlbc := loadBalancerController{\n\t\tclient: c,\n\t\tqueue: workqueue.New(),\n\t\treloadRateLimiter: util.NewTokenBucketRateLimiter(reloadQPS, int(reloadQPS)),\n\t\thaproxy: mgr,\n\t\tdomain: domain,\n\t\tclusterNodes: nodes,\n\t}\n\n\tenqueue := func(obj interface{}) {\n\t\tkey, err := keyFunc(obj)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"Couldn't get key for object %+v: %v\", obj, err)\n\t\t\treturn\n\t\t}\n\t\tlbc.queue.Add(key)\n\t}\n\n\teventHandlers := framework.ResourceEventHandlerFuncs{\n\t\tAddFunc: enqueue,\n\t\tDeleteFunc: enqueue,\n\t\tUpdateFunc: func(old, cur interface{}) {\n\t\t\tif !reflect.DeepEqual(old, cur) {\n\t\t\t\tenqueue(cur)\n\t\t\t}\n\t\t},\n\t}\n\n\tlbc.svcLister.Store, lbc.svcController = framework.NewInformer(\n\t\tcache.NewListWatchFromClient(\n\t\t\tlbc.client, \"services\", namespace, fields.Everything()),\n\t\t&api.Service{}, resyncPeriod, eventHandlers)\n\n\tlbc.epLister.Store, lbc.epController = framework.NewInformer(\n\t\tcache.NewListWatchFromClient(\n\t\t\tlbc.client, \"endpoints\", namespace, fields.Everything()),\n\t\t&api.Endpoints{}, resyncPeriod, eventHandlers)\n\n\treturn &lbc\n}", "func NewController() *Controller {\n\treturn &Controller{\n\t\tClouds: make(map[string]CloudProvider),\n\t\t// WorkerOptions: NewWorkerOptions(),\n\t\tprovisionErr: NewErrCloudProvision(),\n\t}\n}", "func (arb *Arbiter) registerControllerAlive(w http.ResponseWriter, r *http.Request) {\n\tvar ci controllerInfo\n\t_ = json.NewDecoder(r.Body).Decode(&ci)\n\n\tif len(ci.Id) == 0 {\n\t\tlog.Printf(\"Got junk on registerControllerAlive API: %s\\n\", r.Body)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tcd, ok := arb.controllerDaemons[ci.Id]\n\tif !ok {\n\t\t// add the controller daemon\n\t\tlog.Printf(\"Adding new controller for %s with %d workers\", ci.Id, ci.WorkerCount)\n\t\tcd = newControllerDaemon(ci.Id, ci.WorkerCount)\n\t\tarb.controllerDaemons[ci.Id] = cd\n\t}\n\n\tcd.Heartbeat()\n\n\tw.WriteHeader(http.StatusCreated)\n\n}", "func newKuberhealthyChecks(c *KHCheckV1Client, namespace string) *kuberhealthyChecks {\n\treturn &kuberhealthyChecks{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func newController(clusterCfg clusterConfig) (Controller, error) {\n\tcfg := &rest.Config{\n\t\tHost: clusterCfg.Host,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: false,\n\t\t\tCAData: []byte(clusterCfg.CACert),\n\t\t\tCertData: []byte(clusterCfg.ClientCert),\n\t\t\tKeyData: []byte(clusterCfg.ClientKey),\n\t\t},\n\t}\n\n\t// Init the knative serving client\n\tknsClientSet, err := knservingclientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Init the k8s clientset\n\tk8sClientset, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tistioClientSet, err := networkingv1alpha3.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsparkClient, err := sparkclient.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &controller{\n\t\tknServingClient: knsClientSet.ServingV1(),\n\t\tk8sCoreClient: k8sClientset.CoreV1(),\n\t\tk8sAppsClient: k8sClientset.AppsV1(),\n\t\tk8sBatchClient: k8sClientset.BatchV1(),\n\t\tk8sRBACClient: k8sClientset.RbacV1(),\n\t\tk8sSparkOperator: sparkClient.SparkoperatorV1beta2(),\n\t\tistioClient: istioClientSet,\n\t}, nil\n}", "func MountHealthController(service *goa.Service, ctrl HealthController) {\n\tinitService(service)\n\tvar h goa.Handler\n\tservice.Mux.Handle(\"OPTIONS\", \"/cellar/_ah/health\", ctrl.MuxHandler(\"preflight\", handleHealthOrigin(cors.HandlePreflight()), nil))\n\n\th = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\t// Check if there was an error loading the request\n\t\tif err := goa.ContextError(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Build the context\n\t\trctx, err := NewHealthHealthContext(ctx, service)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn ctrl.Health(rctx)\n\t}\n\th = handleHealthOrigin(h)\n\tservice.Mux.Handle(\"GET\", \"/cellar/_ah/health\", ctrl.MuxHandler(\"Health\", h, nil))\n\tservice.LogInfo(\"mount\", \"ctrl\", \"Health\", \"action\", \"Health\", \"route\", \"GET /cellar/_ah/health\")\n}", "func NewHealthHandler(appCtx appcontext.AppContext, redisPool *redis.Pool, gitBranch string, gitCommit string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tdata := map[string]interface{}{\n\t\t\t\"gitBranch\": gitBranch,\n\t\t\t\"gitCommit\": gitCommit,\n\t\t}\n\t\t// Check and see if we should disable DB query with '?database=false'\n\t\t// Disabling the DB is useful for Route53 health checks which require the TLS\n\t\t// handshake be less than 4 seconds and the status code return in less than\n\t\t// two seconds. https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html\n\t\tshowDB, ok := r.URL.Query()[\"database\"]\n\n\t\tvar dbID string\n\t\tvar dbURL string\n\t\t// Always show DB unless key set to \"false\"\n\t\tif !ok || (ok && showDB[0] != \"false\") {\n\t\t\tappCtx.Logger().Info(\"Health check connecting to the DB\")\n\t\t\t// include the request context for helpful tracing\n\t\t\tdb := appCtx.DB().WithContext(r.Context())\n\t\t\tdbID = db.ID\n\t\t\tdbURL = db.Dialect.Details().URL\n\t\t\tdbErr := db.RawQuery(\"SELECT 1;\").Exec()\n\t\t\tif dbErr != nil {\n\t\t\t\tappCtx.Logger().Error(\"Failed database health check\",\n\t\t\t\t\tzap.String(\"dbID\", dbID),\n\t\t\t\t\tzap.String(\"dbURL\", dbURL),\n\t\t\t\t\tzap.Error(dbErr))\n\t\t\t\tdata[\"database\"] = false\n\t\t\t\thealthCheckError(appCtx, w, data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata[\"database\"] = true\n\t\t\tif redisPool != nil {\n\t\t\t\tredisErr := redisHealthCheck(redisPool, appCtx.Logger())\n\t\t\t\tif redisErr != nil {\n\t\t\t\t\tdata[\"redis\"] = false\n\t\t\t\t\thealthCheckError(appCtx, w, data)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdata[\"redis\"] = true\n\t\t\t}\n\t\t}\n\n\t\tnewEncoderErr := json.NewEncoder(w).Encode(data)\n\t\tif newEncoderErr != nil {\n\t\t\tappCtx.Logger().Error(\"Failed encoding health check response\", zap.Error(newEncoderErr))\n\t\t\thttp.Error(w, \"failed health check\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tappCtx.Logger().Info(\"Request health ok\",\n\t\t\tzap.String(\"dbID\", dbID),\n\t\t\tzap.String(\"dbURL\", dbURL))\n\t}\n}", "func HealthCheckerMain(ctx context.Context, addr, component string, ctors ...injection.ControllerConstructor) {\n\tvar wrappers []injection.ControllerConstructor\n\thcs := sync.Map{}\n\n\t// We need to wait for each controller to be constructed and checked\n\t// before the health endpoint will be ready.\n\tctorsWg := sync.WaitGroup{}\n\tctorsWg.Add(len(ctors))\n\n\t// Find all the HealthCheckers\n\tfor i := range ctors {\n\t\tctor := ctors[i]\n\n\t\t// Wrap the given ControllerConstructor so that the resulting\n\t\t// controller can be check to see if it implements HealthChecker. If\n\t\t// it does, then keep track of it so that its health can be polled.\n\t\twrappers = append(wrappers, func(ctx context.Context, cmw configmap.Watcher) *controller.Impl {\n\t\t\tctorsWg.Done()\n\t\t\tctrl := ctor(ctx, cmw)\n\t\t\tif hc, ok := ctrl.Reconciler.(HealthChecker); ok {\n\t\t\t\thcs.Store(hc, ctx)\n\t\t\t}\n\t\t\treturn ctrl\n\t\t})\n\t}\n\n\t// Poll the HealthCheckers. If there is an empty list of HealthCheckers,\n\t// then default to healthy. Otherwise default to unhealthy so that the\n\t// status starts out as not ready.\n\thealthyInt := int32(0)\n\tgo func() {\n\t\tctorsWg.Wait()\n\n\t\t// Poll HealthCheckers\n\t\tfor range time.Tick(5 * time.Second) {\n\t\t\t// Check health\n\t\t\thealthy := int32(1)\n\t\t\thcs.Range(func(key, value interface{}) bool {\n\t\t\t\t// Don't type check because we want this to panic if this gets\n\t\t\t\t// messed up from earlier in the function.\n\t\t\t\thc := key.(HealthChecker)\n\t\t\t\tctx, cancel := context.WithTimeout(value.(context.Context), 30*time.Second)\n\t\t\t\tdefer cancel()\n\n\t\t\t\tif err := hc.Healthy(ctx); err != nil {\n\t\t\t\t\tlogging.FromContext(ctx).Warnf(\"health check failed: %v\", err)\n\t\t\t\t\thealthy = 0\n\t\t\t\t}\n\n\t\t\t\t// Only continue if we're still healthy\n\t\t\t\treturn healthy == 1\n\t\t\t})\n\n\t\t\t// Update status\n\t\t\tatomic.StoreInt32(&healthyInt, healthy)\n\t\t}\n\t}()\n\n\t// Start the health check endpoint on the given address.\n\tgo func() {\n\t\tctorsWg.Wait()\n\n\t\tlog.Fatal(http.ListenAndServe(addr, http.HandlerFunc(\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif atomic.LoadInt32(&healthyInt) != 1 {\n\t\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\t},\n\t\t)))\n\t}()\n\n\tsharedmain.MainWithContext(ctx, component, wrappers...)\n}", "func New(mux *http.ServeMux, opts ...func(*Healthz)) (*Healthz, error) {\n\tif mux == nil {\n\t\treturn nil, errors.New(\"you must provide a http.ServeMux\")\n\t}\n\n\th := &Healthz{\n\t\talive: unhealthy,\n\t\tready: unhealthy,\n\t\tStatus: unhealthy,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(h)\n\t}\n\n\t// path.Join didn't work for the indexHandler here so...\n\tmux.HandleFunc(rootPrefix+\"/\", indexHandler())\n\tmux.HandleFunc(path.Join(rootPrefix, \"ready\"), h.readyHandler())\n\tmux.HandleFunc(path.Join(rootPrefix, \"alive\"), h.livelinessHandler())\n\tmux.HandleFunc(path.Join(rootPrefix, \"stats\"), h.statsHandler())\n\n\tmux.HandleFunc(path.Join(rootPrefix, \"diediedie\"), h.dieDieDieHandler())\n\tmux.HandleFunc(path.Join(rootPrefix, \"abortabortabort\"), h.abortAbortAbortHandler())\n\n\t// Add pprof outside of the default HTTP ServeMux\n\t//\n\t// path.Join doesn't work here and causes bad path to be created on the resulting\n\t// index page from the net/http/pprof package\n\tmux.HandleFunc(rootPrefix+\"/pprof/\", fakePProfIndexHandler())\n\tmux.HandleFunc(path.Join(rootPrefix, \"pprof/cmdline\"), pprof.Cmdline)\n\tmux.HandleFunc(path.Join(rootPrefix, \"pprof/profile\"), pprof.Profile)\n\tmux.HandleFunc(path.Join(rootPrefix, \"pprof/symbol\"), pprof.Symbol)\n\tmux.HandleFunc(path.Join(rootPrefix, \"pprof/trace\"), pprof.Trace)\n\n\treturn h, nil\n}", "func NewHealthService(checker usecase.CheckHealth) *HealthService {\n\treturn &HealthService{checker: checker}\n}", "func newClient(auth azure.Authorizer) *azureClient {\n\tc := newResourceHealthClient(auth.SubscriptionID(), auth.BaseURI(), auth.Authorizer())\n\treturn &azureClient{c}\n}", "func NewHealthOnPort(port int) *Health {\n\thealthMux := http.NewServeMux()\n\thealthMux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, \"OK\") })\n\tserver := &http.Server{Addr: \":\" + strconv.Itoa(port), Handler: healthMux}\n\tinterrupts.ListenAndServe(server, 5*time.Second)\n\treturn &Health{\n\t\thealthMux: healthMux,\n\t}\n}", "func MountHealthController(service *goa.Service, ctrl HealthController) {\n\tinitService(service)\n\tvar h goa.Handler\n\tservice.Mux.Handle(\"OPTIONS\", \"/api/_ah/health\", ctrl.MuxHandler(\"preflight\", handleHealthOrigin(cors.HandlePreflight()), nil))\n\n\th = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\t// Check if there was an error loading the request\n\t\tif err := goa.ContextError(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Build the context\n\t\trctx, err := NewHealthHealthContext(ctx, req, service)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn ctrl.Health(rctx)\n\t}\n\th = handleHealthOrigin(h)\n\tservice.Mux.Handle(\"GET\", \"/api/_ah/health\", ctrl.MuxHandler(\"health\", h, nil))\n\tservice.LogInfo(\"mount\", \"ctrl\", \"Health\", \"action\", \"Health\", \"route\", \"GET /api/_ah/health\")\n}", "func newCephStatusChecker(context *clusterd.Context, namespace, resourceName string) *cephStatusChecker {\n\tc := &cephStatusChecker{\n\t\tcontext: context,\n\t\tnamespace: namespace,\n\t\tresourceName: resourceName,\n\t\tinterval: defaultStatusCheckInterval,\n\t}\n\n\t// allow overriding the check interval with an env var on the operator\n\tcheckInterval := os.Getenv(\"ROOK_CEPH_STATUS_CHECK_INTERVAL\")\n\tif checkInterval != \"\" {\n\t\tif duration, err := time.ParseDuration(checkInterval); err == nil {\n\t\t\tlogger.Infof(\"ceph status check interval is %s\", checkInterval)\n\t\t\tc.interval = duration\n\t\t}\n\t}\n\treturn c\n}", "func health() func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\treturn func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(\"Why, hello!\")\n\t}\n}", "func newIngressController(name, defaultCertificateSecretName, domain string) operatorv1.IngressController {\n\tingresscontroller := operatorv1.IngressController{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tStatus: operatorv1.IngressControllerStatus{\n\t\t\tDomain: domain,\n\t\t},\n\t}\n\tif len(defaultCertificateSecretName) != 0 {\n\t\tingresscontroller.Spec.DefaultCertificate = &corev1.LocalObjectReference{Name: defaultCertificateSecretName}\n\t}\n\treturn ingresscontroller\n}", "func NewHealthchecker(log *logrus.Logger, hostname string) Healthchecker {\n\treturn &healthchecker{\n\t\tlog: log.WithField(\"service\", \"lookup\"),\n\t\thostname: hostname,\n\t}\n}", "func newLoadBalancerController(t *testing.T, cm *fakeClusterManager) *LoadBalancerController {\n\tkubeClient := fake.NewSimpleClientset()\n\tstopCh := make(chan struct{})\n\tctx := context.NewControllerContext(kubeClient, api_v1.NamespaceAll, 1*time.Second, true)\n\tlb, err := NewLoadBalancerController(kubeClient, stopCh, ctx, cm.ClusterManager, true)\n\tif err != nil {\n\t\tt.Fatalf(\"%v\", err)\n\t}\n\tlb.hasSynced = func() bool { return true }\n\treturn lb\n}", "func NewController() (*Controller, error) {\n\tconfig, err := getKubeConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbucketClient, err := bucketclientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new queue. When the informer gets a resource, we add an\n\t// identifying key to the queue so that it can be handled in the handler.\n\tqueue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())\n\n\t// Get the Bucket resource informer.\n\tinformer := bucketinformer_v1.NewBucketInformer(\n\t\tbucketClient,\n\t\tmeta_v1.NamespaceAll,\n\t\t0,\n\t\tcache.Indexers{},\n\t)\n\n\tvar event Event\n\tinformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tevent.key, err = cache.MetaNamespaceKeyFunc(obj)\n\t\t\tevent.action = \"create\"\n\t\t\tevent.newObj = obj\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"creating resource error: %v\", err)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"creating resource: %s\", event.key)\n\t\t\t\tqueue.Add(event)\n\t\t\t}\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tevent.key, err = cache.MetaNamespaceKeyFunc(obj)\n\t\t\tevent.action = \"delete\"\n\t\t\tevent.oldObj = obj\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"deleting resource error: %v\", err)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"deleting resource: %s\", event.key)\n\t\t\t\tqueue.Add(event)\n\t\t\t}\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\tevent.key, err = cache.MetaNamespaceKeyFunc(newObj)\n\t\t\tevent.action = \"update\"\n\t\t\tevent.oldObj = oldObj\n\t\t\tevent.newObj = newObj\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"updating resource error: %v\", err)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"updating resource: %s\", event.key)\n\t\t\t\tqueue.Add(event)\n\t\t\t}\n\t\t},\n\t})\n\n\tawsSession, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the controller\n\tcontroller := &Controller{\n\t\tlogger: log.NewEntry(log.New()),\n\t\tclientset: client,\n\t\tinformer: informer,\n\t\tqueue: queue,\n\t\thandler: &BucketHandler{s3.New(awsSession)},\n\t}\n\n\treturn controller, nil\n}", "func newResourceController(client kubernetes.Interface, informer cache.SharedIndexInformer, config config.Configuration) *Controller {\n\tqueue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())\n\n\tinformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tkey, err := cache.MetaNamespaceKeyFunc(old)\n\t\t\tif err == nil {\n\t\t\t\tlogrus.Info(\"Adding to Queue\")\n\t\t\t\tqueue.Add(key)\n\t\t\t}\n\t\t},\n\t})\n\n\thandler := handler.NewMailHandler(config.SMTP.Host, config.SMTP.Port, \"\", \"\")\n\n\treturn &Controller{\n\t\tclientset: client,\n\t\tinformer: informer,\n\t\tqueue: queue,\n\t\thandler: handler,\n\t\tconfig: config,\n\t}\n}", "func NewController() *Controller {\n\treturn &Controller{Logger: logger.NewLogger()}\n}", "func (c *ReadinessController) New(base interface{}) {\n\tc.Base = base.(*Base)\n\n\tlog.Println(\"Scanning for Readiness files.\")\n\tc.FileExtension = \".xlsx\"\n}", "func newHealthcheckManager(e *Engine) *healthcheckManager {\n\treturn &healthcheckManager{\n\t\tengine: e,\n\t\tmarks: make(map[markKey]uint32),\n\t\tmarkAlloc: newMarkAllocator(dsrMarkBase, dsrMarkSize),\n\t\tncc: e.ncc,\n\t\tnext: healthcheck.Id((uint64(os.Getpid()) & 0xFFFF) << 48),\n\t\tvserverChecks: make(map[string]map[CheckKey]*check),\n\t\tquit: make(chan bool),\n\t\tstopped: make(chan bool),\n\t\tvcc: make(chan vserverChecks, 1000),\n\t\tenabled: true,\n\t}\n}", "func (h *handler) health(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"OK\")\n}", "func NewHealthCheck() jrpc2.Handler {\n\treturn handler.New(func(context.Context) HealthCheckResult {\n\t\treturn HealthCheckResult{Status: \"healthy\"}\n\t})\n}", "func NewController(\n\tchopClient chopClientSet.Interface,\n\textClient apiExtensions.Interface,\n\tkubeClient kube.Interface,\n\tchopInformerFactory chopInformers.SharedInformerFactory,\n\tkubeInformerFactory kubeInformers.SharedInformerFactory,\n) *Controller {\n\n\t// Initializations\n\t_ = chopClientSetScheme.AddToScheme(scheme.Scheme)\n\n\t// Setup events\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(log.Info)\n\teventBroadcaster.StartRecordingToSink(\n\t\t&typedCoreV1.EventSinkImpl{\n\t\t\tInterface: kubeClient.CoreV1().Events(\"\"),\n\t\t},\n\t)\n\trecorder := eventBroadcaster.NewRecorder(\n\t\tscheme.Scheme,\n\t\tcoreV1.EventSource{\n\t\t\tComponent: componentName,\n\t\t},\n\t)\n\n\t// Create Controller instance\n\tcontroller := &Controller{\n\t\tkubeClient: kubeClient,\n\t\textClient: extClient,\n\t\tchopClient: chopClient,\n\t\tchiLister: chopInformerFactory.Clickhouse().V1().ClickHouseInstallations().Lister(),\n\t\tchiListerSynced: chopInformerFactory.Clickhouse().V1().ClickHouseInstallations().Informer().HasSynced,\n\t\tchitLister: chopInformerFactory.Clickhouse().V1().ClickHouseInstallationTemplates().Lister(),\n\t\tchitListerSynced: chopInformerFactory.Clickhouse().V1().ClickHouseInstallationTemplates().Informer().HasSynced,\n\t\tserviceLister: kubeInformerFactory.Core().V1().Services().Lister(),\n\t\tserviceListerSynced: kubeInformerFactory.Core().V1().Services().Informer().HasSynced,\n\t\tendpointsLister: kubeInformerFactory.Core().V1().Endpoints().Lister(),\n\t\tendpointsListerSynced: kubeInformerFactory.Core().V1().Endpoints().Informer().HasSynced,\n\t\tconfigMapLister: kubeInformerFactory.Core().V1().ConfigMaps().Lister(),\n\t\tconfigMapListerSynced: kubeInformerFactory.Core().V1().ConfigMaps().Informer().HasSynced,\n\t\tstatefulSetLister: kubeInformerFactory.Apps().V1().StatefulSets().Lister(),\n\t\tstatefulSetListerSynced: kubeInformerFactory.Apps().V1().StatefulSets().Informer().HasSynced,\n\t\tpodLister: kubeInformerFactory.Core().V1().Pods().Lister(),\n\t\tpodListerSynced: kubeInformerFactory.Core().V1().Pods().Informer().HasSynced,\n\t\trecorder: recorder,\n\t}\n\tcontroller.initQueues()\n\tcontroller.addEventHandlers(chopInformerFactory, kubeInformerFactory)\n\n\treturn controller\n}", "func Health(c *gin.Context) {\n\tfmt.Println(\"Service healthy\")\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": \"Loan service is healthy!\"})\n}", "func NewTeamworkSoftwareUpdateHealth()(*TeamworkSoftwareUpdateHealth) {\n m := &TeamworkSoftwareUpdateHealth{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewHealth() *Health {\n\tconst vertexShader = `\n\t\t#version 410\n\n\t\tin vec4 coord;\n\t\tout vec2 tcoord;\n\n\t\tvoid main(void) {\n\t\t\tgl_Position = vec4(coord.xy, 0, 1);\n\t\t\ttcoord = coord.zw;\n\t\t}\n\t`\n\n\tconst fragmentShader = `\n\t\t#version 410\n\n\t\tin vec2 tcoord;\n\t\tuniform sampler2D tex;\n\t\tout vec4 frag_color;\n\n\t\tvoid main(void) {\n\t\t\tvec4 texel = texture(tex, tcoord);\n\t\t\tfrag_color = texel;\n\t\t}\n\t`\n\n\th := Health{}\n\n\th.program = createProgram(vertexShader, fragmentShader)\n\tbindAttribute(h.program, 0, \"coord\")\n\n\th.textureUniform = uniformLocation(h.program, \"tex\")\n\th.pointsVBO = newVBO()\n\th.drawableVAO = newPointsVAO(h.pointsVBO, 4)\n\n\trgba, _ := LoadImages([]string{\"textures/health.png\", \"textures/health-empty.png\"}, 16)\n\th.textureUnit = 4\n\tgl.ActiveTexture(uint32(gl.TEXTURE0 + h.textureUnit))\n\tgl.GenTextures(1, &h.texture)\n\tgl.BindTexture(gl.TEXTURE_2D, h.texture)\n\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n\n\tgl.TexImage2D(\n\t\tgl.TEXTURE_2D,\n\t\t0,\n\t\tgl.RGBA,\n\t\tint32(rgba.Rect.Size().X),\n\t\tint32(rgba.Rect.Size().Y),\n\t\t0,\n\t\tgl.RGBA,\n\t\tgl.UNSIGNED_BYTE,\n\t\tgl.Ptr(rgba.Pix),\n\t)\n\n\tgl.GenerateMipmap(gl.TEXTURE_2D)\n\treturn &h\n}", "func NewHealthService() *Service {\n\treturn &Service{}\n}", "func newDiskHealthTracker() *diskHealthTracker {\n\td := diskHealthTracker{\n\t\tlastSuccess: time.Now().UnixNano(),\n\t\tlastStarted: time.Now().UnixNano(),\n\t\tstatus: diskHealthOK,\n\t\ttokens: make(chan struct{}, diskMaxConcurrent),\n\t}\n\tfor i := 0; i < diskMaxConcurrent; i++ {\n\t\td.tokens <- struct{}{}\n\t}\n\treturn &d\n}", "func NewController() Controller {\n\treturn &controller{}\n}", "func (c *ControllerImpl) HealthCheck(ctx context.Context) error {\n\treturn nil\n}", "func NewController(\n\topt controller.Options,\n\tnotifications chan struct{},\n\tserviceInformer servinginformers.ServiceInformer,\n) *Controller {\n\tlogger, _ := zap.NewProduction()\n\topt.Logger = logger.Sugar()\n\tc := &Controller{\n\t\tBase: controller.NewBase(opt, controllerAgentName, \"Services\"),\n\t}\n\n\tc.Logger.Info(\"Setting up event handlers\")\n\tserviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.Enqueue,\n\t\tUpdateFunc: controller.PassNew(c.Enqueue),\n\t\tDeleteFunc: c.Enqueue,\n\t})\n\n\treturn c\n}", "func New(ctx context.Context, s *Session, health healthcheck.Handler) Controller {\n\ttemp := controller{\n\t\tcmd: make(chan int),\n\t\tsong: make(chan string),\n\t\tplaylist: make(chan string),\n\t\tready: make(chan struct{}),\n\t\tcurrentToken: make(chan oauth2.Token),\n\t\thealth: health,\n\t}\n\n\tgo run(ctx, s, temp)\n\treturn temp\n}", "func Healthy(name string) ClusterController {\n\tco := Running(name)\n\n\tas, err := kverify.APIServerStatus(co.CP.Runner, co.CP.Hostname, co.CP.Port)\n\tif err != nil {\n\t\tout.FailureT(`Unable to get control plane status: {{.error}}`, out.V{\"error\": err})\n\t\texitTip(\"delete\", name, reason.ExSvcError)\n\t}\n\n\tif as == state.Paused {\n\t\tout.Styled(style.Shrug, `The control plane for \"{{.name}}\" is paused!`, out.V{\"name\": name})\n\t\texitTip(\"unpause\", name, reason.ExSvcConfig)\n\t}\n\n\tif as != state.Running {\n\t\tout.Styled(style.Shrug, `This control plane is not running! (state={{.state}})`, out.V{\"state\": as.String()})\n\t\tout.WarningT(`This is unusual - you may want to investigate using \"{{.command}}\"`, out.V{\"command\": ExampleCmd(name, \"logs\")})\n\t\texitTip(\"start\", name, reason.ExSvcUnavailable)\n\t}\n\treturn co\n}", "func Health(w http.ResponseWriter, r *http.Request) {\n\twriteJSON(w, http.StatusOK, healthResponse{\"alive\"})\n}", "func NewHealthCheck(rt *app.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func New() *Controller {\n\treturn &Controller{}\n}", "func newHealthyDirClient(rulesDir string) *mocks.DirectoryClient {\n\tclient := &mocks.DirectoryClient{}\n\tclient.On(\"Stat\", mock.AnythingOfType(\"string\")).Return(nil, nil)\n\tclient.On(\"Mkdir\", mock.AnythingOfType(\"os.FileMode\")).Return(nil)\n\tclient.On(\"ReadDir\").Return(nil, nil)\n\tclient.On(\"Dir\").Return(rulesDir)\n\n\treturn client\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tblobMgr: blob.Mgr,\n\t\tblobSizeExpiration: time.Hour * 24, // keep the size of blob in redis with 24 hours\n\t}\n}", "func (c *HealthController) Health(ctx *app.HealthHealthContext) error {\n\t// HealthController_Health: start_implement\n\n\tfmt.Printf(\"DC: [%s]\\n\", ctx.Dc)\n\tfmt.Printf(\"Host Group: [%s]\\n\", ctx.Hgroup)\n\tfmt.Printf(\"Host Name: [%s]\\n\", ctx.Hostname)\n\n\tfor index, element := range c.zapi_list {\n\t\tfmt.Printf(\"zapi_alias: [%s]\\n\", index)\n\t\tfmt.Printf(\"zapi_url: [%s]\\n\", element.zapi_url)\n\t\tfmt.Printf(\"zapi_username: [%s]\\n\", element.zapi_username)\n\t\tfmt.Printf(\"zapi_password: [%s]\\n\", element.zapi_password)\n\t\tfmt.Printf(\"zapi_version: [%s]\\n\\n\", element.zapi_version)\n\t}\n\n\tresult, err := GetDCStatus(c.zapi_list[ctx.Dc])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Erro communicating with ZAPI: %v\\n\", err)\n\t}\n\tretval, err := json.Marshal(result)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to UnMarshall JSON object\\n\", err)\n\t}\n\n\t// HealthController_Health: end_implement\n\treturn ctx.OK(retval)\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tiManager: instance.Mgr,\n\t\tpManager: policy.Mgr,\n\t\tscheduler: scheduler.Sched,\n\t\texecutionMgr: task.NewExecutionManager(),\n\t}\n}", "func NewHealthGetDefault(code int) *HealthGetDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &HealthGetDefault{\n\t\t_statusCode: code,\n\t}\n}", "func NewHealthCheck(rt *permissions.Runtime) operations.HealthCheckHandler {\n\treturn &healthCheck{}\n}", "func HealthHandler(res http.ResponseWriter, req *http.Request) {\n\thc := Healthcheck{Status: \"OK\"}\n\tif err := json.NewEncoder(res).Encode(hc); err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func HealthHandler(res http.ResponseWriter, req *http.Request) {\n\thc := Healthcheck{Status: \"OK\"}\n\tif err := json.NewEncoder(res).Encode(hc); err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func NewController(\n\tctx context.Context,\n\tcmw configmap.Watcher,\n) *controller.Impl {\n\tbrokerCellInformer := brokercellinformer.Get(ctx)\n\n\tlogger := logging.FromContext(ctx)\n\n\tls := listers{\n\t\tbrokerLister: brokerinformer.Get(ctx).Lister(),\n\t\tchannelLister: channelinformer.Get(ctx).Lister(),\n\t\thpaLister: hpainformer.Get(ctx).Lister(),\n\t\ttriggerLister: triggerinformer.Get(ctx).Lister(),\n\t\tconfigMapLister: configmapinformer.Get(ctx).Lister(),\n\t\tsecretLister: systemnamespacesecretinformer.Get(ctx).Lister(),\n\t\tserviceAccountLister: serviceaccountinformer.Get(ctx).Lister(),\n\t\tserviceLister: serviceinformer.Get(ctx).Lister(),\n\t\tendpointsLister: endpointsinformer.Get(ctx).Lister(),\n\t\tdeploymentLister: deploymentinformer.Get(ctx).Lister(),\n\t\tpodLister: podinformer.Get(ctx).Lister(),\n\t}\n\n\tbase := reconciler.NewBase(ctx, controllerAgentName, cmw)\n\tr, err := NewReconciler(base, ls)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed to create BrokerCell reconciler\", zap.Error(err))\n\t}\n\timpl := v1alpha1brokercell.NewImpl(ctx, r)\n\n\tvar latencyReporter *metrics.BrokerCellLatencyReporter\n\tif r.env.InternalMetricsEnabled {\n\t\tlatencyReporter, err = metrics.NewBrokerCellLatencyReporter()\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to create latency reporter\", zap.Error(err))\n\t\t}\n\t}\n\n\tlogger.Info(\"Setting up event handlers.\")\n\n\tbrokerCellInformer.Informer().AddEventHandlerWithResyncPeriod(controller.HandleAll(impl.Enqueue), reconciler.DefaultResyncPeriod)\n\tbrokerCellLister := brokerCellInformer.Lister()\n\n\t// Watch brokers and triggers to invoke configmap update immediately.\n\tbrokerinformer.Get(ctx).Informer().AddEventHandler(controller.HandleAll(\n\t\tfunc(obj interface{}) {\n\t\t\tif b, ok := obj.(*brokerv1.Broker); ok {\n\t\t\t\t// TODO(#866) Select the brokercell that's associated with the given broker.\n\t\t\t\timpl.EnqueueKey(types.NamespacedName{Namespace: system.Namespace(), Name: brokerresources.DefaultBrokerCellName})\n\t\t\t\treportLatency(ctx, b, latencyReporter, \"Broker\", b.Name, b.Namespace)\n\t\t\t}\n\t\t},\n\t))\n\ttriggerinformer.Get(ctx).Informer().AddEventHandler(controller.HandleAll(\n\t\tfunc(obj interface{}) {\n\t\t\tif t, ok := obj.(*brokerv1.Trigger); ok {\n\t\t\t\t// TODO(#866) Select the brokercell that's associated with the given broker.\n\t\t\t\timpl.EnqueueKey(types.NamespacedName{Namespace: system.Namespace(), Name: brokerresources.DefaultBrokerCellName})\n\t\t\t\treportLatency(ctx, t, latencyReporter, \"Trigger\", t.Name, t.Namespace)\n\t\t\t}\n\t\t},\n\t))\n\n\t// Watch GCP Channels and subscriptions on those channels to invoke configmap update immediately.\n\tchannelinformer.Get(ctx).Informer().AddEventHandler(controller.HandleAll(\n\t\tfunc(obj interface{}) {\n\t\t\tif c, ok := obj.(*v1beta1.Channel); ok {\n\t\t\t\t// TODO(#866) Select the brokercell that's associated with the given broker.\n\t\t\t\timpl.EnqueueKey(types.NamespacedName{Namespace: system.Namespace(), Name: brokerresources.DefaultBrokerCellName})\n\t\t\t\treportLatency(ctx, c, latencyReporter, \"Channel\", c.Name, c.Namespace)\n\t\t\t}\n\t\t},\n\t))\n\n\t// Watch data plane components created by brokercell so we can update brokercell status immediately.\n\t// 1. Watch deployments for ingress, fanout and retry\n\tdeploymentinformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\t// 2. Watch ingress endpoints\n\tendpointsinformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\t// 3. Watch hpa for ingress, fanout and retry deployments\n\thpainformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\t// 4. Watch the broker targets configmap.\n\tconfigmapinformer.Get(ctx).Informer().AddEventHandler(handleResourceUpdate(impl))\n\n\t// Watch componets which are not created by brokercell, but affect broker data plane.\n\t// 1. Watch broker data plane's secret,\n\t// if the filtered secret resource changes, enqueue brokercells from the same namespace.\n\tsystemnamespacesecretinformer.Get(ctx).Informer().AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: filterWithNamespace(authcheck.ControlPlaneNamespace),\n\t\tHandler: authcheck.EnqueueBrokerCell(impl, brokerCellLister),\n\t})\n\t// 2. Watch broker data plane's k8s service account,\n\t// if the filtered k8s service account resource changes, enqueue brokercells from the same namespace.\n\tserviceaccountinformer.Get(ctx).Informer().AddEventHandler(cache.FilteringResourceEventHandler{\n\t\tFilterFunc: filterWithNamespace(authcheck.ControlPlaneNamespace),\n\t\tHandler: authcheck.EnqueueBrokerCell(impl, brokerCellLister),\n\t})\n\treturn impl\n}", "func New(strategy string, cfg config.HealthcheckConfig) *Healthcheck {\n\n\tcheck := registry[strategy]\n\n\t/* Create healthcheck */\n\n\th := Healthcheck{\n\t\tcheck: check,\n\t\tcfg: cfg,\n\t\tIn: make(chan []core.Target),\n\t\tOut: make(chan CheckResult),\n\t\tworkers: []*Worker{},\n\t\tstop: make(chan bool),\n\t}\n\n\treturn &h\n}", "func HealthHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Health called\")\n\tlog.Println(\"Request:\", r)\n\n\tw.WriteHeader(http.StatusOK)\n\n}", "func health(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\tw.WriteHeader(http.StatusOK)\n}", "func NewController(clientset kubernetes.Interface,\n\tmapper apimeta.RESTMapper,\n\tscalesGetter scale.ScalesGetter,\n\tsharedInformerFactory informers.SharedInformerFactory,\n\tgardenerInformerFactory gardenerinformers.SharedInformerFactory,\n\tprobeDependantsList *ProbeDependantsList,\n\tstopCh <-chan struct{}) *Controller {\n\n\tc := &Controller{\n\t\tclient: clientset,\n\t\tmapper: mapper,\n\t\tscalesGetter: scalesGetter,\n\t\tinformerFactory: sharedInformerFactory,\n\t\tsecretsInformer: sharedInformerFactory.Core().V1().Secrets().Informer(),\n\t\tsecretsLister: sharedInformerFactory.Core().V1().Secrets().Lister(),\n\t\tclusterInformerFactory: gardenerInformerFactory,\n\t\tclusterInformer: gardenerInformerFactory.Extensions().V1alpha1().Clusters().Informer(),\n\t\tclusterLister: gardenerInformerFactory.Extensions().V1alpha1().Clusters().Lister(),\n\t\tdeploymentsInformer: sharedInformerFactory.Apps().V1().Deployments().Informer(),\n\t\tdeploymentsLister: sharedInformerFactory.Apps().V1().Deployments().Lister(),\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"Namespaces\"),\n\t\tstopCh: stopCh,\n\t\tprobeDependantsList: probeDependantsList,\n\t\tMulticontext: multicontext.New(),\n\t}\n\tcomponentbaseconfigv1alpha1.RecommendedDefaultLeaderElectionConfiguration(&c.LeaderElection)\n\tc.clusterInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewCluster := new.(*gardenerv1alpha1.Cluster)\n\t\t\toldCluster := old.(*gardenerv1alpha1.Cluster)\n\t\t\tklog.V(4).Infof(\"Update event on cluster: %v\", newCluster.Name)\n\t\t\tif newCluster.ResourceVersion == oldCluster.ResourceVersion {\n\t\t\t\t// Periodic resync will send update events for all known Deployments.\n\t\t\t\t// Two different versions of the same Deployment will always have different RVs.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif shootHibernationStateChanged(oldCluster, newCluster) {\n\t\t\t\t// namespace is same as cluster's name\n\t\t\t\tns := newCluster.Name\n\t\t\t\tklog.V(4).Infof(\"Requeueing namespace: %v\", ns)\n\t\t\t\tif c.probeDependantsList.Namespace != \"\" && ns != c.probeDependantsList.Namespace {\n\t\t\t\t\t// skip reconciling other namespaces if a namespace was already configured\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tc.workqueue.AddRateLimited(ns)\n\t\t\t\tklog.V(4).Infof(\"Requeued namespace: %v\", ns)\n\t\t\t} else {\n\t\t\t\tklog.V(5).Infof(\"Ignore update event on cluster: %v\", newCluster.Name)\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t})\n\tc.secretsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.enqueueProbe,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewSecret := new.(*v1.Secret)\n\t\t\toldSecret := old.(*v1.Secret)\n\t\t\tif newSecret.ResourceVersion == oldSecret.ResourceVersion {\n\t\t\t\t// Periodic resync will send update events for all known Deployments.\n\t\t\t\t// Two different versions of the same Deployment will always have different RVs.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.enqueueProbe(new)\n\t\t},\n\t\tDeleteFunc: c.enqueueProbe,\n\t})\n\tc.hasSecretsSynced = c.secretsInformer.HasSynced\n\tc.hasDeploymentsSynced = c.deploymentsInformer.HasSynced\n\tc.hasClustersSynced = c.clusterInformer.HasSynced\n\treturn c\n}", "func NewController(ctx context.Context, cmw configmap.Watcher) *controller.Impl {\n\tsubscriptionInformer := subscriptioninformersv1alpha1.Get(ctx)\n\teventActivationInformer := eventactivationinformersv1alpha1.Get(ctx)\n\tknativeLib, err := util.NewKnativeLib()\n\tif err != nil {\n\t\tpanic(\"Failed to initialize knative lib\")\n\t}\n\tStatsReporter, err := NewStatsReporter()\n\tif err != nil {\n\t\tpanic(\"Failed to Kyma Subscription Controller stats reporter\")\n\t}\n\n\tr := &Reconciler{\n\t\tBase: reconciler.NewBase(ctx, controllerAgentName, cmw),\n\t\tsubscriptionLister: subscriptionInformer.Lister(),\n\t\teventActivationLister: eventActivationInformer.Lister(),\n\t\tkymaEventingClient: eventbusclient.Get(ctx).EventingV1alpha1(),\n\t\tknativeLib: knativeLib,\n\t\topts: opts.DefaultOptions(),\n\t\ttime: util.NewDefaultCurrentTime(),\n\t\tStatsReporter: StatsReporter,\n\t}\n\timpl := controller.NewImpl(r, r.Logger, reconcilerName)\n\n\tsubscriptionInformer.Informer().AddEventHandler(controller.HandleAll(impl.Enqueue))\n\n\tregisterMetrics()\n\n\treturn impl\n}", "func NewController() *Controller {\n\treturn &Controller{}\n}", "func New(config HealthCheckConfig) *HealthCheck {\n\treturn &HealthCheck{\n\t\tbroker: &kafkaBrokerConnection{},\n\t\tzookeeper: &zkConnection{},\n\t\trandSrc: rand.NewSource(time.Now().UnixNano()),\n\t\tconfig: config,\n\t}\n}", "func NewHealthCheck(opt ...Option) *HealthCheck {\n\topts := GetOpts(opt...)\n\n\th := &HealthCheck{\n\t\tstatus: &healthStatus{},\n\t}\n\tif e, ok := opts[optionWithEngine].(*gin.Engine); ok {\n\t\th.Engine = e\n\t}\n\tif path, ok := opts[optionWithHealthPath].(string); ok {\n\t\th.HealthPath = path\n\t} else {\n\t\th.HealthPath = \"/ready\"\n\t}\n\tif handler, ok := opts[optionWithHealthHandler].(gin.HandlerFunc); ok {\n\t\th.Handler = handler\n\t} else {\n\t\th.Handler = h.DefaultHealthHandler()\n\t}\n\n\tif ticker, ok := opts[optionHealthTicker].(*time.Ticker); ok {\n\t\th.metricTicker = ticker\n\t} else {\n\t\th.metricTicker = time.NewTicker(DefaultHealthTickerDuration)\n\t}\n\n\treturn h\n}", "func newStatusService(log zerolog.Logger) *statusService {\n\treturn &statusService{\n\t\tlog: log,\n\t\toutputActuals: make(chan api.Output, 8),\n\t\tsensorActuals: make(chan api.Sensor, 8),\n\t\tswitchActuals: make(chan api.Switch, 8),\n\t}\n}", "func NewController() *Controller {\n\treturn &Controller{wrapper: NewWrapper()}\n}", "func New(ctx context.Context, config *config.CleanupConfig, db *database.Database, h *render.Renderer) *Controller {\n\tlogger := logging.FromContext(ctx)\n\treturn &Controller{\n\t\tconfig: config,\n\t\tdb: db,\n\t\th: h,\n\t\tlogger: logger,\n\t}\n}", "func (t tApp) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.App{}\n\n\t// Allocate its parents. Make sure controller of every type\n\t// is allocated just once, then reused.\n\tc.Controllers = &contr.Controllers{}\n\tc.Controllers.Templates = c.Controllers.Errors.Templates\n\tc.Controllers.Errors = &c5.Errors{}\n\tc.Controllers.Static = &c3.Static{}\n\tc.Controllers.Sessions = &c2.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Requests = &c1.Requests{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Global = &c0.Global{\n\n\t\tCurrentAction: act,\n\n\t\tCurrentController: ctr,\n\t}\n\tc.Controllers.Errors.Templates = &c4.Templates{}\n\tc.Controllers.Errors.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Errors.Templates.Global = c.Controllers.Global\n\tc.Controllers.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Templates.Global = c.Controllers.Global\n\n\treturn c\n}", "func New(ctx context.Context, config *config.ServerConfig, h *render.Renderer) *Controller {\n\tlogger := logging.FromContext(ctx)\n\n\treturn &Controller{\n\t\tconfig: config,\n\t\th: h,\n\t\tlogger: logger,\n\t}\n}", "func New() *Controller {\n\treturn &Controller{\n\t\tValidatePayload: ValidatePayload,\n\t}\n}", "func NewController(\n\tkubeclientset kubernetes.Interface,\n\tdanielfoehrknclientset clientset.Interface,\n\tkubeInformerFactory kubeinformers.SharedInformerFactory,\n\texampleInformerFactory informers.SharedInformerFactory) *Controller {\n\n\t// obtain references to shared index informers for the Deployment and Database\n\t// types.\n\tdeploymentInformer := kubeInformerFactory.Apps().V1().Deployments()\n\ttaggerInformer := exampleInformerFactory.Danielfoehrkn().V1().Taggers()\n\n\t// Create event broadcaster\n\t// Add example database types to the default Kubernetes Scheme so Events can be\n\t// logged for database types.\n\tsamplescheme.AddToScheme(scheme.Scheme)\n\tglog.V(4).Info(\"Creating event broadcaster\")\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(glog.Infof)\n\teventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events(\"\")})\n\trecorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName})\n\n\tcontroller := &Controller{\n\t\tkubeclientset: kubeclientset,\n\t\tdanielfoehrknclientset: danielfoehrknclientset,\n\t\tdeploymentsLister: deploymentInformer.Lister(),\n\t\tdeploymentsSynced: deploymentInformer.Informer().HasSynced,\n\t\ttaggerLister: taggerInformer.Lister(),\n\t\ttaggerSynced: taggerInformer.Informer().HasSynced,\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"\"),\n\t\trecorder: recorder,\n\t}\n\n\tglog.Info(\"Setting up event handlers\")\n\t// Set up an event handler for when Tagger resources change\n\ttaggerInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: controller.enqueueTagger,\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewTagger := new.(*danielfoehrknApiV1.Tagger)\n\t\t\toldTagger := old.(*danielfoehrknApiV1.Tagger)\n\t\t\tif newTagger.ResourceVersion == oldTagger.ResourceVersion {\n\t\t\t\t// Periodic resync will send update events for all known Deployments.\n\t\t\t\t// Two different versions of the same Deployment will always have different RVs.\n\n\t\t\t\t//TODO: why is this event being called ALL THE TIME so that I need to make a diff on the resource version from etcd? -> etcd watch should only give updates once the key changed\n\t\t\t\tglog.Info(\"EVENT FOR UNCHANGED TAGGER RECEIVED\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontroller.enqueueTagger(new)\n\t\t},\n\t})\n\n\treturn controller\n}", "func NewHealthChecker(registration Lifecycle, checks []healthcheck.Agent) *HealthChecker {\n\tif len(checks) == 0 {\n\t\tpanic(\"No health checks provided\")\n\t}\n\n\treturn &HealthChecker{\n\t\tstop: make(chan struct{}),\n\t\tagents: checks,\n\t\tregistration: registration,\n\t}\n}", "func getHealthStatus(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"ready\"})\n}", "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tbeeline.AddField(r.Context(), \"alive\", true)\n\tw.Write([]byte(`{\"alive\": \"yes\"}`))\n}", "func NewController() Controller {\n\treturn &controller{\n\t\tClient: client.NewClient(),\n\t}\n}", "func healthHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Alive!\"))\n}", "func NewController(exec boil.ContextExecutor) Controller {\n\trepo := &personRepository{executor: exec}\n\tsvc := &personService{repo: repo}\n\tpc := &personController{service: svc}\n\treturn pc\n}" ]
[ "0.779857", "0.74201", "0.7384725", "0.6947366", "0.6775966", "0.6758363", "0.6499691", "0.646478", "0.6408092", "0.6401599", "0.6373925", "0.6287439", "0.6262988", "0.6231156", "0.62296176", "0.62059814", "0.6192473", "0.61034393", "0.6041319", "0.60295445", "0.6028243", "0.6020633", "0.59760714", "0.5931426", "0.59228605", "0.5900292", "0.587456", "0.585333", "0.585253", "0.5819826", "0.58023125", "0.5789509", "0.5750365", "0.57462955", "0.57354754", "0.5727051", "0.56868947", "0.56850004", "0.5682972", "0.56713355", "0.56712085", "0.5670534", "0.5652833", "0.5620949", "0.56176454", "0.5617107", "0.5605921", "0.56053764", "0.5570454", "0.55697703", "0.5563706", "0.5563205", "0.55583894", "0.5552657", "0.55345607", "0.55291927", "0.55253613", "0.5524429", "0.5507976", "0.5506246", "0.55061966", "0.54911083", "0.5490722", "0.5490599", "0.5478076", "0.5478038", "0.5472501", "0.5463663", "0.5461209", "0.54495883", "0.5449134", "0.5447477", "0.5446565", "0.54365635", "0.5434504", "0.54178387", "0.541399", "0.541399", "0.5394146", "0.5390693", "0.5387289", "0.53871167", "0.5381021", "0.5377243", "0.5375054", "0.53748137", "0.5373141", "0.5365085", "0.5363417", "0.53533757", "0.5349154", "0.5345486", "0.53437513", "0.534308", "0.53415215", "0.53407544", "0.5337244", "0.53350556", "0.53345835", "0.5330537" ]
0.66545075
6
Index is index route for health
func (hc *HealthController) Index(c echo.Context) error { return c.JSON(http.StatusOK, newResponse( http.StatusOK, http.StatusText(http.StatusOK), "OK", )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func routeIndex(c echo.Context) error {\n\treturn c.JSON(200, map[string]interface{}{\n\t\t\"success\": true,\n\t\t\"message\": \"Welcome!\",\n\t})\n}", "func indexHandler(c *fiber.Ctx) error {\n\treturn common.HandleTemplate(c, \"index\",\n\t\t\"me\", nil, 200)\n}", "func (h *Root) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tif claims, err := auth.ClaimsFromContext(ctx); err == nil && claims.HasAuth() {\n\t\treturn h.indexDashboard(ctx, w, r, params)\n\t}\n\n\treturn h.indexDefault(ctx, w, r, params)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tenv.Output.WriteChDebug(\"(ApiEngine::Index)\")\n\thttp.Redirect(w, r, \"/api/node\", http.StatusFound)\n}", "func (si ServeIndex) Index(w http.ResponseWriter, r *http.Request) {\n\tpara := params.NewParams()\n\tdata, _, err := Updates(r, para)\n\tif err != nil {\n\t\tif _, ok := err.(params.RenamedConstError); ok {\n\t\t\thttp.Redirect(w, r, err.Error(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdata[\"Distrib\"] = si.StaticData.Distrib\n\tdata[\"Exporting\"] = exportingCopy() // from ./ws.go\n\tdata[\"OstentUpgrade\"] = OstentUpgrade.Get()\n\tdata[\"OstentVersion\"] = si.StaticData.OstentVersion\n\tdata[\"TAGGEDbin\"] = si.StaticData.TAGGEDbin\n\n\tsi.IndexTemplate.Apply(w, struct{ Data IndexData }{Data: data})\n}", "func (s *HTTPServer) Index(resp http.ResponseWriter, req *http.Request) {\n\t// Check if this is a non-index path\n\tif req.URL.Path != \"/\" {\n\t\tresp.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\t// Give them something helpful if there's no UI so they at least know\n\t// what this server is.\n\tif !s.IsUIEnabled() {\n\t\tfmt.Fprint(resp, \"Consul Agent\")\n\t\treturn\n\t}\n\n\t// Redirect to the UI endpoint\n\thttp.Redirect(resp, req, \"/ui/\", http.StatusMovedPermanently) // 301\n}", "func index(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"index\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\ta := \"hello from index router\"\n\tfmt.Fprintln(w, a)\n}", "func index(w http.ResponseWriter, req *http.Request, ctx httputil.Context) (e *httputil.Error) {\n\tif req.URL.Path != \"/\" {\n\t\tnotFound(w, req)\n\t\treturn\n\t}\n\tm := newManager(ctx)\n\n\tres, err := m.Index()\n\tif err != nil {\n\t\te = httputil.Errorf(err, \"couldn't query for test results\")\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tif err := T(\"index/index.html\").Execute(w, res); err != nil {\n\t\te = httputil.Errorf(err, \"error executing index template\")\n\t}\n\treturn\n}", "func IndexHandeler(w http.ResponseWriter, r *http.Request) {\n\trespond.OK(w, map[string]interface{}{\n\t\t\"name\": \"hotstar-schedular\",\n\t\t\"version\": 1,\n\t})\n}", "func IndexRoute(w http.ResponseWriter, r *http.Request) {\n\tforbidden := \"Error: Cannot access http-facter with \" + r.Method + \".\"\n\tindexResponse := \"HTTP-Facter\\n\"\n\tindexResponse += \"-----------\\n\"\n\tindexResponse += \"http-facter can be used to get facts from a remote server.\\n\\n\"\n\tindexResponse += \"For example, use /fact/os to gather facts about the OS.\\n\"\n\t// Check to make sure the API is not being accesses by POST, PUT, etc.\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tw.Write([]byte(forbidden))\n\t} else {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(indexResponse))\n\t}\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"index de uma função\")\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tname := p.ByName(\"name\")\n\tresponse := snakes[name].Info\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr := json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: response write: \" + err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Index: \" + name)\n}", "func (t tApp) Index(w http.ResponseWriter, r *http.Request) {\n\tvar h http.Handler\n\tc := App.New(w, r, \"App\", \"Index\")\n\tdefer func() {\n\t\tif h != nil {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t}()\n\tdefer App.After(c, w, r)\n\tif res := App.Before(c, w, r); res != nil {\n\t\th = res\n\t\treturn\n\t}\n\tif res := c.Index(); res != nil {\n\t\th = res\n\t\treturn\n\t}\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\n\t// Execute the template and respond with the index page.\n\ttemplates.ExecuteTemplate(res, \"index\", nil)\n}", "func (s *Server) index() httprouter.Handle {\n return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n if s.db.Connected(r.Context()) {\n\t\t\tfmt.Fprint(w, \"Connected!\")\n } else {\n http.Error(w, \"Error connecting to database\", http.StatusNotFound)\n s.log.Println(\"Error connectiong to database\")\n }\n }\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t//index_routes := []string{\"providers\"}\n\tvar index_routes []string\n\tindex_routes = GetJobs()\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(index_routes); err != nil {\n\t\tpanic(err)\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n}", "func IndexRouter(r *gin.Engine) {\n\tr.GET(\"/l4_check\", func(c *gin.Context) {\n\t\tc.String(200, \"SUCCESS\")\n\t})\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\talerts := cfg.Alerts\n\tfor _, alert := range alerts {\n\t\tfmt.Fprintln(w, \"\\tName: \", alert.Name)\n\t\tfmt.Fprintln(w, \"\\tAlertHost: \", alert.AlertHost)\n\t\tfmt.Fprintln(w, \"\\tAction: \", alert.Action)\n\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n}", "func EndpointGETIndex(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tvar returnResponse = map[string]interface{}{\"message\": \"Welcome to the TonicPow API!\"}\n\tapirouter.ReturnResponse(w, req, http.StatusOK, returnResponse)\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func index(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\terr := tpl.ExecuteTemplate(w, \"index.html\", nil)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(\"HERE INDEX\")\n}", "func handleIndex(w http.ResponseWriter, r *http.Request) {\n\tmsg := fmt.Sprintf(\"You've called url %s\", r.URL.String())\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(http.StatusOK) // 200\n\tw.Write([]byte(msg))\n}", "func (t tApp) Index(w http.ResponseWriter, r *http.Request) {\n\tvar h http.Handler\n\tc := App.newC(w, r, \"App\", \"Index\")\n\tdefer func() {\n\t\t// If one of the actions (Before, After or Index) returned\n\t\t// a handler, apply it.\n\t\tif h != nil {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t}()\n\tdefer App.after(c, w, r) // Call this at the very end, but before applying result.\n\tif res := App.before(c, w, r); res != nil {\n\t\th = res\n\t\treturn\n\t}\n\tif res := c.Index(); res != nil {\n\t\th = res\n\t\treturn\n\t}\n}", "func (s *Server) Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"[INDEX]: \", r.URL.Path[1:])\n\tu, ok := s.m[r.URL.Path[1:]]\n\tif !ok {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(w, \"not found\\n\")\n\t\treturn\n\t}\n\thttp.Redirect(w, r, u, http.StatusMovedPermanently)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Steve and Kyle Podcast: #api\")\n\tfmt.Fprintln(w, \"Number of episodes in database:\", EpCount())\n\tfmt.Fprintln(w, \"Created by Derek Slenk\")\n\tfmt.Println(\"Endpoint Hit: Index\")\n}", "func Index(w http.ResponseWriter, req *http.Request) {\n\thttp.NotFound(w, req)\n}", "func Index(w http.ResponseWriter, data interface{}) {\n\trender(tpIndex, w, data)\n}", "func (s *server) handleIndex(FSS fs.FS) http.HandlerFunc {\n\ttype AppConfig struct {\n\t\tAvatarService string\n\t\tToastTimeout int\n\t\tAllowGuests bool\n\t\tAllowRegistration bool\n\t\tDefaultLocale string\n\t\tAuthMethod string\n\t\tAppVersion string\n\t\tCookieName string\n\t\tPathPrefix string\n\t\tAPIEnabled bool\n\t\tCleanupGuestsDaysOld int\n\t\tCleanupStoryboardsDaysOld int\n\t\tShowActiveCountries bool\n\t}\n\ttype UIConfig struct {\n\t\tAnalyticsEnabled bool\n\t\tAnalyticsID string\n\t\tAppConfig AppConfig\n\t\tActiveAlerts []interface{}\n\t}\n\n\ttmpl := s.getIndexTemplate(FSS)\n\n\tappConfig := AppConfig{\n\t\tAvatarService: viper.GetString(\"config.avatar_service\"),\n\t\tToastTimeout: viper.GetInt(\"config.toast_timeout\"),\n\t\tAllowGuests: viper.GetBool(\"config.allow_guests\"),\n\t\tAllowRegistration: viper.GetBool(\"config.allow_registration\") && viper.GetString(\"auth.method\") == \"normal\",\n\t\tDefaultLocale: viper.GetString(\"config.default_locale\"),\n\t\tAuthMethod: viper.GetString(\"auth.method\"),\n\t\tAPIEnabled: viper.GetBool(\"config.allow_external_api\"),\n\t\tAppVersion: s.config.Version,\n\t\tCookieName: s.config.FrontendCookieName,\n\t\tPathPrefix: s.config.PathPrefix,\n\t\tCleanupGuestsDaysOld: viper.GetInt(\"config.cleanup_guests_days_old\"),\n\t\tCleanupStoryboardsDaysOld: viper.GetInt(\"config.cleanup_storyboards_days_old\"),\n\t\tShowActiveCountries: viper.GetBool(\"config.show_active_countries\"),\n\t}\n\n\tActiveAlerts = s.database.GetActiveAlerts()\n\n\tdata := UIConfig{\n\t\tAnalyticsEnabled: s.config.AnalyticsEnabled,\n\t\tAnalyticsID: s.config.AnalyticsID,\n\t\tAppConfig: appConfig,\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdata.ActiveAlerts = ActiveAlerts // get latest alerts from memory\n\n\t\tif embedUseOS {\n\t\t\ttmpl = s.getIndexTemplate(FSS)\n\t\t}\n\n\t\ttmpl.Execute(w, data)\n\t}\n}", "func GetIndex(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello world !!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tmessage := \"Welcome to Recipe Book!\"\n\tindexT.Execute(w, message)\n}", "func (h *indexHandler) Index() gin.HandlerFunc {\n\treturn func(context *gin.Context) {\n\t\tvar requestFromJson indexRequest\n\n\t\tif err := context.ShouldBindJSON(&requestFromJson); nil != err {\n\t\t\th.errorDispatcher.Dispatch(context, err)\n\n\t\t\treturn\n\t\t}\n\n\t\tvar payload *index.Index = h.indexBuilder.Build(\n\t\t\trequestFromJson.BuilderContext,\n\t\t\trequestFromJson.Locale,\n\t\t)\n\n\t\tcontext.JSON(\n\t\t\thttp.StatusOK,\n\t\t\t&indexResponse{response.NewOkResponse(), *payload},\n\t\t)\n\t}\n}", "func Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"[INFO] Horton is online...\")\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request) {\n\t// I set the content type...\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t// ... I write the I'm a Teapot status code :) ...\n\tw.WriteHeader(http.StatusTeapot)\n\t// ... and I write the a welcome message\n\tb, _ := json.Marshal(struct {\n\t\tWelcome string `json:\"welcome\"`\n\t}{\n\t\tWelcome: \"Welcome to abusim-coordinator API!\",\n\t})\n\tw.Write(b)\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(res, \"You requested: \"+req.URL.Path)\n}", "func (r *ResponseHandler) IndexEndpoint(c *gin.Context) {\n\tr.database.GetUser(c.Param(\"user\"))\n\tc.JSON(200, gin.H{\n\t\t\"message\": \"pong\",\n\t})\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa, Nice!\")\n}", "func Index(c echo.Context) error {\n\treturn c.Render(http.StatusOK, \"index\", echo.Map{})\n}", "func handleIndex(w http.ResponseWriter, r *http.Request) {\n\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tc := appengine.NewContext(r)\n\tlog.Infof(c, \"Serving main page.\")\n\n\ttmpl, _ := template.ParseFiles(\"web/tmpl/index.tmpl\")\n\n\ttmpl.Execute(w, time.Since(initTime))\n}", "func (h *HTTPApi) listIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tcollections := h.storageNode.Datasources[ps.ByName(\"datasource\")].GetMeta().Databases[ps.ByName(\"dbname\")].ShardInstances[ps.ByName(\"shardinstance\")].Collections[ps.ByName(\"collectionname\")]\n\n\t// Now we need to return the results\n\tif bytes, err := json.Marshal(collections.Indexes); err != nil {\n\t\t// TODO: log this better?\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bytes)\n\t}\n}", "func Index(ctx *fasthttp.RequestCtx) {\n\tfmt.Fprint(ctx, \"Welcome!\\n\")\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request) {\n\tresponse := info()\n\n\terr := utils.Respond(w, response)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: Failed to encode info response, %s\", err)\n\t}\n}", "func (s *ClusterHealthService) Index(indices ...string) *ClusterHealthService {\n\ts.indices = append(s.indices, indices...)\n\treturn s\n}", "func (d *Diagnosis) indexHandler(w http.ResponseWriter, r *http.Request) {\n\tvar profiles []profile\n\tfor _, p := range pprof.Profiles() {\n\t\tprofiles = append(profiles, profile{\n\t\t\tName: p.Name(),\n\t\t\tHref: p.Name() + \"?debug=1\",\n\t\t\tDesc: profileDescriptions[p.Name()],\n\t\t\tCount: p.Count(),\n\t\t})\n\t}\n\n\t// Adding other profiles exposed from within this package\n\tfor _, p := range []string{\"cmdline\", \"profile\", \"trace\"} {\n\t\tprofiles = append(profiles, profile{\n\t\t\tName: p,\n\t\t\tHref: p,\n\t\t\tDesc: profileDescriptions[p],\n\t\t})\n\t}\n\n\tsort.Slice(profiles, func(i, j int) bool {\n\t\treturn profiles[i].Name < profiles[j].Name\n\t})\n\n\tif err := indexTmpl.Execute(w, map[string]interface{}{\n\t\t\"AppName\": d.appName,\n\t\t\"PathPrefix\": d.pathPrefix,\n\t\t\"Profiles\": profiles,\n\t}); err != nil {\n\t\td.log.Error(err)\n\t}\n}", "func (h *IndexHandler) Healthy(w http.ResponseWriter, _ *http.Request) {\n\tresponse.OK(w)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tfmt.Fprint(w, \"Hello, World!\")\n}", "func IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" || r.Method != \"GET\" {\n\t\tlog.Println(r.Method, r.URL, http.StatusNotFound)\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tlog.Println(r.Method, r.URL, http.StatusOK)\n\tfmt.Fprintln(w, JsonResponse{\"status\": \"OK\"})\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello from our index page\")\n}", "func index(ctx *gin.Context) {\n\tctx.Header(\"Content-Type\", \"text/html\")\n\tctx.String(\n\t\thttp.StatusOK,\n\t\t\"<h1>Rasse Server</h1><p>Wel come to the api server.</p><p>%v</p>\",nil)\n}", "func (h *Root) indexDefault(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\treturn h.Renderer.Render(ctx, w, r, tmplLayoutSite, \"site-index.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, nil)\n}", "func Index(logger *log.Logger, basepath string, done <-chan struct{}, templ *template.Template) http.Handler {\n\ttracker, err := dir.Watch(basepath)\n\tif err != nil {\n\t\tlogger.Printf(\"failed to watch directory [%s] - %v\", basepath, err)\n\t\treturn ResponseCode(500, \"failed to initialize IndexHandler - %v\", err)\n\t}\n\tgo func() {\n\t\t<-done\n\t\ttracker.Close()\n\t}()\n\n\treturn indexHandler{basePath: basepath, templ: templ, l: logger, dir: tracker, done: done}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Hello World!\"))\n}", "func (h *Handlers) Index(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tfile := path.Join(\"index.html\")\n\n\tdata := struct{ Host string }{Host: h.Host}\n\n\ttemp, _ := template.ParseFiles(file)\n\ttemp.Execute(w, &data)\n}", "func main() {\n router := mux.NewRouter()\n router.HandleFunc(\"/\", home).Methods(\"GET\")\n router.HandleFunc(\"/health\", health).Methods(\"GET\")\n log.Fatal(http.ListenAndServe(\":9999\", router))\n}", "func GetIndex(w http.ResponseWriter, req *http.Request, app *App) {\n\tscheme := \"http\"\n\tif req.TLS != nil {\n\t\tscheme = \"https\"\n\t}\n\tbase := []string{scheme, \"://\", req.Host, app.Config.General.Prefix}\n\trender(w, \"index\", map[string]interface{}{\"base\": strings.Join(base, \"\"), \"hideNav\": true}, app)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome to this example API\\n\")\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdata, err := newPageData(1)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\terr = t.ExecuteTemplate(w, \"index\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func IndexHandler(ctx *Context, w http.ResponseWriter, r *http.Request) (int, error) {\n\tvar host string\n\tif r.Header.Get(\"X-Forwarded-Host\") != \"\" {\n\t\thost = r.Header.Get(\"X-Forwarded-Host\")\n\t} else {\n\t\thost = r.Host\n\t}\n\n\tvar hostConfig *gabs.Container\n\tvar ok bool\n\n\t// Check if host present in Config.\n\tchildren := ctx.Config.ChildrenMap()\n\tif hostConfig, ok = children[host]; !ok {\n\t\treturn 404, fmt.Errorf(\"Shortcut '%s' not found in Config.\", host)\n\t}\n\n\ttokens := tokenize(host + r.URL.Path)\n\n\t// Set up handles on token and Config. We might need to skip ahead if there's a custom schema set.\n\ttokensStart := tokens.Front()\n\tconf := ctx.Config\n\n\tvar path bytes.Buffer\n\tif s := hostConfig.Path(sslKey).Data(); s != nil && s.(bool) {\n\t\tpath.WriteString(httpPrefix)\n\t} else if s := hostConfig.Path(schemaKey).Data(); s != nil && s.(string) != \"\" {\n\t\tpath.WriteString(hostConfig.Path(schemaKey).Data().(string) + \":/\")\n\t\t// move one token ahead to parse expansions correctly.\n\t\tconf = conf.ChildrenMap()[tokensStart.Value.(string)]\n\t\ttokensStart = tokensStart.Next()\n\t} else {\n\t\t// Default to regular https prefix.\n\t\tpath.WriteString(httpsPrefix)\n\t}\n\n\tExpandPath(conf, tokensStart, &path)\n\n\t// send result\n\thttp.Redirect(w, r, path.String(), http.StatusFound)\n\n\treturn 302, nil\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\n\tctx, span := trace.StartSpan(ctx, \"indexHandler\")\n\tdefer span.End()\n\n\tlog.Debugf(ctx, \"Hi, 1\")\n\tlog.Infof(ctx, \"Hi, 2\")\n\n\tfmt.Fprint(w, \"Hello, World!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodGet {\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tfmt.Fprint(w, \"trueskilld v0.1!\\n\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != http.MethodGet {\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"I am running...\\n\")\n}", "func (c App) Index() revel.Result {\n\treturn c.Render()\n}", "func (c App) Index() revel.Result {\n\treturn c.Render()\n}", "func HandlerIndex(res http.ResponseWriter, req *http.Request) {\n\thttp.ServeFile(res, req, \"./static/index.html\")\n}", "func indexHandler(w http.ResponseWriter, req *http.Request) {\n\tlayout, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_LAYOUT)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tindex, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_INDEX)\n\t//artical, err := template.ParseFile(PATH_PUBLIC + TEMPLATE_ARTICAL)\n\tif err != nil {\n\t\thttp.Error(w, ERROR_TEMPLATE_NOT_FOUND, http.StatusNotFound)\n\t\treturn\n\t}\n\tmapOutput := map[string]interface{}{\"Title\": \"炫酷的网站技术\" + TITLE, \"Keyword\": KEYWORD, \"Description\": DESCRIPTION, \"Base\": BASE_URL, \"Url\": BASE_URL, \"Carousel\": getAddition(PREFIX_INDEX), \"Script\": getAddition(PREFIX_SCRIPT), \"Items\": leveldb.GetRandomContents(20, &Filter{})}\n\tcontent := []byte(index.RenderInLayout(layout, mapOutput))\n\tw.Write(content)\n\tgo cacheFile(\"index\", content)\n}", "func indexRouter(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome to my API\")\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func IndexHandler(c *gin.Context) {\n\tc.HTML(200, \"index.tmpl\", nil)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(indexHandlerResponse{Message: \"OK\"})\n}", "func serveIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\terr := serveAssets(w, r, \"index.html\")\n\tcheckError(err)\n}", "func (u MainController) Index(c *gin.Context) {\n\tuserState := c.MustGet(\"userstate\").(*permissionbolt.UserState)\n\tusername := userState.Username(c.Request)\n\n\tc.HTML(http.StatusOK, \"index\", gin.H{\n\t\t\"username\": username,\n\t\t\"isLogged\": (len(username) > 0),\n\t\t\"isAdmin\": userState.IsAdmin(username),\n\t})\n}", "func showIndex(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tServeTemplateWithParams(res, req, \"index.html\", nil)\n}", "func HealthyRouters(e *gin.Engine) {\n\te.GET(\"/\", func(c *gin.Context) {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"go transactions api is healthy\",\n\t\t})\n\t})\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif err := json.NewEncoder(w).Encode(ResultIndex{Connect: true}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"/image/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (c Application) Index() revel.Result {\n\tif user := c.connected(); user != nil {\n\t\treturn c.Redirect(routes.Dashboard.Index())\n\t}\n\treturn c.Render()\n}", "func Index(w http.ResponseWriter, r *http.Request, us httprouter.Params) {\n\tfmt.Fprint(w, \"WELCOMEEE!\")\n}", "func (v1 *V1Client) Index() error {\n\tresp := v1.POST(nil, \"/api/v1/index\")\n\treturn resp.Error\n}", "func (h *Root) indexDashboard(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"root-dashboard.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, nil)\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func ReadIndex(output http.ResponseWriter, reader *http.Request) {\n\tfmt.Fprintln(output, \"ImageManagerAPI v1.0\")\n\tLog(\"info\", \"Endpoint Hit: ReadIndex\")\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"website index\")\n\t//grab all partials\n\tpartials, err := loadPartials()\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t//get template function based on index and execute to load page\n\tt, _ := template.ParseFiles(\"../index.html\")\n\tt.Execute(res, partials)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"s-senpai, please don't hurt me ;_;\\n\")\n}", "func IndexHandler(c buffalo.Context) error {\n\treturn c.Render(200, r.HTML(\"index.html\"))\n}", "func (c *AppController) Index() {\n\tdata := aah.Data{\n\t\t\"Greet\": models.Greet{\n\t\t\tMessage: \"Welcome to aah framework - Web Application\",\n\t\t},\n\t}\n\n\tc.Reply().Ok().HTML(data)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func Index(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(appResponse{Message: \"OK\"})\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Welcome!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tresponse := make(map[string]interface{})\n\tw.WriteHeader(http.StatusOK)\n\tresponse[\"status\"] = true\n\tjson.NewEncoder(w).Encode(response)\n}", "func Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello World!\")\n}", "func Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello World!\")\n}", "func Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello World!\")\n}", "func Index(c *gin.Context) {\n\tc.String(http.StatusOK, \"Hello World!\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\t// Fill out the page data for index\n\tpd := PageData{\n\t\tTitle: \"Index Page\",\n\t\tBody: \"This is the body of the index page.\",\n\t}\n\n\t// Render a template with our page data\n\ttmpl, err := render(pd)\n\n\t// if we get an error, write it out and exit\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t// All went well, so write out the template\n\tw.Write([]byte(tmpl))\n\n\t//fmt.Fprintf(w, \"Hello world from %q\", html.EscapeString(r.URL.Path))\n}" ]
[ "0.70387924", "0.6908191", "0.67733145", "0.6721757", "0.66746527", "0.6673345", "0.66724163", "0.6634735", "0.6600483", "0.65861976", "0.6579026", "0.65608984", "0.65549064", "0.65352345", "0.6500487", "0.64980423", "0.64815146", "0.64801145", "0.64781564", "0.6444518", "0.6427906", "0.6427906", "0.64196295", "0.64107096", "0.6392901", "0.6392901", "0.6361326", "0.63482416", "0.6342279", "0.63332313", "0.6329089", "0.6324073", "0.6322617", "0.6313425", "0.62973964", "0.62882787", "0.62770057", "0.6235662", "0.6230458", "0.6209389", "0.6200854", "0.6188065", "0.6185672", "0.6185514", "0.61713904", "0.61697674", "0.6168985", "0.61677635", "0.6163872", "0.6161078", "0.61588687", "0.6146056", "0.61253923", "0.6121665", "0.6109051", "0.6105818", "0.61003786", "0.6098161", "0.6082499", "0.60781574", "0.60756034", "0.60709", "0.60699564", "0.60624224", "0.6060264", "0.605065", "0.6045626", "0.6045626", "0.6040376", "0.6034687", "0.6031252", "0.6026843", "0.6023598", "0.60223424", "0.6019154", "0.6016135", "0.60073024", "0.59999996", "0.5995024", "0.59940255", "0.59817415", "0.59795666", "0.59683836", "0.5968356", "0.5967995", "0.5965409", "0.5963551", "0.5953432", "0.5935594", "0.59300506", "0.59273714", "0.59191966", "0.5919169", "0.590631", "0.589745", "0.5897055", "0.5897055", "0.5897055", "0.5897055", "0.5893229" ]
0.7311362
0
encrypt encrypts plain string with a secret key and returns encrypt string.
func encrypt(plainData string, secret []byte) (string, error) { cipherBlock, err := aes.NewCipher(secret) if err != nil { return "", err } aead, err := cipher.NewGCM(cipherBlock) if err != nil { return "", err } nonce := make([]byte, aead.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } return base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func encrypt(plainData string, secret []byte) (string, error) {\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce := make([]byte, aead.NonceSize())\r\n\tif _, err = io.ReadFull(crt.Reader, nonce); err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\r\n}", "func encrypt(key string, plaintext string) string {\n\tvar iv = []byte{83, 71, 26, 58, 54, 35, 22, 11,\n\t\t83, 71, 26, 58, 54, 35, 22, 11}\n\tderivedKey := pbkdf2.Key([]byte(key), iv, 1000, 48, sha1.New)\n\tnewiv := derivedKey[0:16]\n\tnewkey := derivedKey[16:48]\n\tplaintextBytes := pkcs7Pad([]byte(plaintext), aes.BlockSize)\n\tblock, err := aes.NewCipher(newkey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn := aes.BlockSize - (len(plaintext) % aes.BlockSize)\n\tciphertext := make([]byte, len(plaintext)+n*2)\n\tmode := cipher.NewCBCEncrypter(block, newiv)\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\tcipherstring := base64.StdEncoding.EncodeToString(ciphertext[:len(ciphertext)-n])\n\treturn cipherstring\n}", "func encrypt(key []byte, text string) string {\n\t// key needs tp be 16, 24 or 32 bytes.\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func encrypt(decoded string, key []byte) (string, error) {\n\tplainText := []byte(anchor + decoded)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn decoded, err\n\t}\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn decoded, err\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\tencoded := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encoded, nil\n}", "func EncryptString(to_encrypt string, key_string string) string {\n\tkey := DecodeBase64(key_string)\n\tplaintext := []byte(to_encrypt)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: EncryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make a empty byte array to fill\n\tciphertext := make([]byte, len(plaintext))\n\t// create the ciphertext\n\tc.XORKeyStream(ciphertext, plaintext)\n\treturn EncodeBase64(ciphertext)\n}", "func (q MockService) Encrypt(input string) (encKey string, encVal string, err error) {\n\tencKey = `AQEDAHithgxYTcdIpj37aYm1VAycoViFcSM2L+KQ42Aw3R0MdAAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDMrhUevDKOjuP7L1\nXAIBEIA7/F9A1spnmoaehxqU5fi8lBwiZECAvXkSI33YPgJGAsCqmlEAQuirHHp4av4lI7jjvWCIj/nyHxa6Ss8=`\n\tencVal = \"+DKd7lg8HsLD+ISl7ZrP0n6XhmrTRCYDVq4Zj9hTrL1JjxAb2fGsp/2DMSPy\"\n\terr = nil\n\n\treturn encKey, encVal, err\n}", "func Encrypt(secret string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)\n\tCheck(err)\n\treturn string(hash)\n}", "func encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(str string) (string, error) {\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tcipherText := make([]byte, aes.BlockSize+len(str))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(str))\n\n\t//returns to base64 encoded string\n\tencmess := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encmess, nil\n}", "func encrypt(msg string) string {\n\tencryptionPassphrase := []byte(Secret)\n\tencryptionText := msg\n\tencryptionType := \"PGP SIGNATURE\"\n\n\tencbuf := bytes.NewBuffer(nil)\n\tw, err := armor.Encode(encbuf, encryptionType, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tplaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmessage := []byte(encryptionText)\n\t_, err = plaintext.Write(message)\n\n\tplaintext.Close()\n\tw.Close()\n\t//fmt.Printf(\"Encrypted:\\n%s\\n\", encbuf)\n\treturn encbuf.String()\n}", "func Encrypt(text string) (encryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tplaintext := []byte(text)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil {\n\t\terr = fmt.Errorf(\"iv ciphertext err: %s\", rErr)\n\t\treturn\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\tencryptedText = base64.URLEncoding.EncodeToString(ciphertext)\n\n\treturn\n}", "func Encrypt(plaintext, key string) (string, error) {\n\n\tvar ciphertext []byte\n\tvar err error\n\n\tciphertext, err = encrypt([]byte(plaintext), []byte(key))\n\n\treturn base64.StdEncoding.EncodeToString(ciphertext), err\n}", "func Encrypt(key []byte, plaintext string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, 12)\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintextbytes := []byte(plaintext)\n\tcipherStr := base64.StdEncoding.EncodeToString(aesgcm.Seal(nonce, nonce, plaintextbytes, nil))\n\treturn cipherStr, nil\n}", "func Encrypt(key, iv, plaintext []byte) string {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n ciphertext := gcm.Seal(nil, iv, plaintext, nil)\n return base64.StdEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key []byte, text string) string {\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key []byte, text string) string {\n\t// key := []byte(keyText)\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(randCry.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func (c *Caesar) Encrypt(input string, shift uint) (ret string) {\n\td := int(shift)\n\tshiftedAlphabet := c.doShiftedAlphabed(d)\n\tfor _, v := range strings.Split(input, \"\") {\n\t\tposition := c.findInAlphabet(c.Alphabet, v)\n\t\tif position != -1 {\n\t\t\tret = ret + shiftedAlphabet[position]\n\t\t} else {\n\t\t\tret = ret + v\n\t\t}\n\t}\n\treturn\n}", "func EncryptString(plainText string, key []byte, iv []byte) []byte {\n\tplainTextAsBytes := []byte(plainText)\n\treturn Encrypt(plainTextAsBytes, key, iv)\n}", "func Encrypt(key string, plaintext string) (string, error) {\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := FunctionReadfull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream, err := FunctionEncryptStream(key, iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))\n\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func Encrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tplaintext := []byte(fmt.Sprint(text))\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcipherText := make([]byte, len(plaintext))\n\tcfb.XORKeyStream(cipherText, plaintext)\n\treturn encodeBase64(cipherText)\n}", "func Encrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tplaintext := pad([]byte(text))\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"plaintext is not a multiple of the block size\")\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64Encode(ciphertext), nil\n}", "func (a Aes) Encrypt(text string) (string, error) {\n\treturn a.encrypt([]byte(a.Key), text)\n}", "func Encrypt(key []byte, text []byte) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Creating IV\n\tciphertext := make([]byte, aes.BlockSize+len(text))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrpytion Process\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], text)\n\n\t// Encode to Base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(plainText []byte, key []byte, iv []byte) []byte {\n\treturn getCipher(key).Seal(nil, iv, plainText, nil)\n}", "func Encrypt(plainText []byte, nonceBase64 string, key []byte) []byte {\n\tplainBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(plainText)))\n\tbase64.StdEncoding.Encode(plainBase64, plainText)\n\n\tnonce := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\tbase64.StdEncoding.Decode(nonce, []byte(nonceBase64))\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonce)\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tcypherText := []byte{}\n\tcypherText = secretbox.Seal(cypherText, plainText, nonceArray, encKey)\n\tcypherBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(cypherText)))\n\tbase64.StdEncoding.Encode(cypherBase64, cypherText)\n\treturn cypherBase64\n}", "func (o *OpenSSL) EncryptString(passphrase, plaintextString string) ([]byte, error) {\n\tsalt := make([]byte, 8) // Generate an 8 byte salt\n\t_, err := io.ReadFull(rand.Reader, salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o.EncryptStringWithSalt(passphrase, salt, plaintextString)\n}", "func Encrypt(pass string) (string, error) {\n\tval, err := bcrypt.GenerateFromPassword([]byte(pass), salt)\n\treturn string(val), err\n}", "func encrypt(aesKey []byte, plainText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Encrypt(plainText, associatedData)\n}", "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func EncryptString(publicKey []*big.Int, message string) ([]byte, error) {\n\treturn EncryptBytes(publicKey, []byte(message))\n}", "func encrypt(key, buf []byte) ([]byte, error) {\n\taesCipher, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tencrypter := cipher.NewCBCEncrypter(aesCipher, make([]byte, aes.BlockSize))\n\toutput := make([]byte, len(buf))\n\tencrypter.CryptBlocks(output, buf)\n\treturn output, nil\n}", "func Encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key string, secret string, nonce string) []byte {\n\tkeyInBytes, err := hex.DecodeString(key)\n\tPanicOnError(err)\n\tsecretInBytes, err := hex.DecodeString(secret)\n\tPanicOnError(err)\n\tblock, err := aes.NewCipher(keyInBytes)\n\tPanicOnError(err)\n\tgcm, err := cipher.NewGCM(block)\n\tPanicOnError(err)\n\tnonceInBytes, err := hex.DecodeString(nonce[0 : 2*gcm.NonceSize()])\n\tPanicOnError(err)\n\tdata := gcm.Seal(nil, nonceInBytes, secretInBytes, nil)\n\treturn data\n}", "func encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\n\tif len(iv) != aes.BlockSize {\n\t\treturn nil, fmt.Errorf(\"keystore.encrypt: IV not %d bytes\", aes.BlockSize)\n\t}\n\tif len(key) != 32 {\n\t\treturn nil, fmt.Errorf(\"keystore.encrypt: key not 32 bytes\")\n\t}\n\n\tbl, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"keystore.encrypt aes.NewCipher: %v\", err.Error())\n\t}\n\n\t// Write IV to the start of ciphertext.\n\tciphertext := make([]byte, len(plaintext)+aes.BlockSize)\n\tcopy(ciphertext[:aes.BlockSize], iv)\n\n\tstream := cipher.NewCFBEncrypter(bl, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\treturn ciphertext, nil\n}", "func (c *Cipher) Encrypt(plaintext string, context map[string]*string) (string, error) {\n\n\tkey, err := kms.GenerateDataKey(c.Client, c.KMSKeyID, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext, err := encryptBytes(key.Plaintext, []byte(plaintext))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencrypted := &encrypted{keyCiphertext: key.Ciphertext, ciphertext: ciphertext}\n\treturn encrypted.encode(), nil\n\n}", "func (v *DefaultVaultClient) Encrypt(key, b64text string) (string, error) {\n\tkv := map[string]interface{}{\"plaintext\": b64text}\n\ts, err := v.Logical().Write(v.encryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get encryption value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"ciphertext\"].(string), nil\n}", "func Encriptar(text string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(text), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tfmt.Println(\"no se pudo encriptar el text\")\n\t\treturn text\n\t}\n\treturn string(hash)\n}", "func (n *runtimeJavascriptNakamaModule) aesEncrypt(keySize int, input, key string) (string, error) {\n\tif len(key) != keySize {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"expects key %v bytes long\", keySize))\n\t}\n\n\t// Pad string up to length multiple of 4 if needed.\n\tif maybePad := len(input) % 4; maybePad != 0 {\n\t\tinput += strings.Repeat(\" \", 4-maybePad)\n\t}\n\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error creating cipher block: %v\", err.Error()))\n\t}\n\n\tcipherText := make([]byte, aes.BlockSize+len(input))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error getting iv: %v\", err.Error()))\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(input))\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func EncryptString(in string) (string, error) {\n\tcphr, err := aes.NewCipher(GetTokenKey())\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"new cipher\")\n\t}\n\tgcm, err := cipher.NewGCM(cphr)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"new gcm\")\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"new nonce\")\n\t}\n\tdata := gcm.Seal(nonce, nonce, []byte(in), nil)\n\n\t//base64 encode\n\tout := base64.StdEncoding.EncodeToString(data)\n\treturn out, nil\n}", "func EncryptString(k string, s string) (string, error) {\n\tkey := []byte(k)\n\tplaintext := []byte(s)\n\n\tciphertext, err := encrypt(key, plaintext)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to encrypt string: %w\", err)\n\t}\n\n\treturn ciphertext, nil\n}", "func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) {\n\tif len(secret) != secretLen {\n\t\tpanic(fmt.Sprintf(\"Secret must be 32 bytes long, got len %v\", len(secret)))\n\t}\n\tnonce := crypto.CRandBytes(nonceLen)\n\tnonceArr := [nonceLen]byte{}\n\tcopy(nonceArr[:], nonce)\n\tsecretArr := [secretLen]byte{}\n\tcopy(secretArr[:], secret)\n\tciphertext = make([]byte, nonceLen+secretbox.Overhead+len(plaintext))\n\tcopy(ciphertext, nonce)\n\tsecretbox.Seal(ciphertext[nonceLen:nonceLen], plaintext, &nonceArr, &secretArr)\n\treturn ciphertext\n}", "func Encrypt(pt string) string {\n\tvar (\n\t\tround_keys = make([]string, 16)\n\t)\n\tgenerate_keys(key, &round_keys)\n\tfmt.Printf(\"before encrtypting - %v\\n\", pt)\n\tct := DES(pt, round_keys)\n\tfmt.Printf(\"after encrtypting - %v\\n\", ct)\n\treturn ct\n}", "func encrypt(input []byte, key []byte) []byte {\n\n\tvar block cipher.Block\n\n\tkey = hashBytes(key)\n\tblock, _ = aes.NewCipher(key)\n\n\tbuff := make([]byte, len(input))\n\tcopy(buff, input)\n\n\tcipher.NewCFBEncrypter(block, key[0:block.BlockSize()]).XORKeyStream(buff, buff)\n\n\treturn []byte(base64.RawStdEncoding.EncodeToString(buff))\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func Encrypt(passphrase string, plaintext []byte) (string, error) {\n\tnow := time.Now()\n\tkey, salt, err := deriveKey(passphrase, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tutils.LogDebug(fmt.Sprintf(\"PBKDF2 key derivation took %d ms\", time.Now().Sub(now).Milliseconds()))\n\n\tiv := make([]byte, 12)\n\t// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\t// Section 8.2\n\t_, err = rand.Read(iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata := aesgcm.Seal(nil, iv, plaintext, nil)\n\treturn hex.EncodeToString(salt) + \"-\" + hex.EncodeToString(iv) + \"-\" + hex.EncodeToString(data), nil\n}", "func encryptionWrapper(myMessage []byte) []byte {\n\tsecret_base64 := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK\"\n\tsecretMessage, err := base64.StdEncoding.DecodeString(secret_base64)\n\tutils.Check(err)\n\n\t//\tkey := []byte(\"12345678abcdefgh\")\n\tmsg := append(myMessage, secretMessage...)\n\treturn Encrypt(msg, key)\n}", "func Encrypt(plaintext string) (string, error) {\n\treturn defaultEncryptor.Encrypt(plaintext)\n}", "func Encrypt(key *Key, password string, attrs map[string]interface{}) ([]byte, error) {\n\tprovider := &Web3KeyStore{}\n\n\treturn provider.Write(key, password, attrs)\n}", "func SecretPhrase(w http.ResponseWriter, r *http.Request) {\n unknown := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\\n\" +\n \"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\\n\" +\n \"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\\n\" +\n \"YnkK\"\n\n\tgetVars, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdata := getVars.Get(\"input\")\n\tfmt.Println(\"Input:\", data)\n decoded, _ := base64.StdEncoding.DecodeString(unknown)\n amended := append([]byte(data), decoded...)\n padded := AddPadding(amended, keysize)\n\n w.Write(ECBEncrypt(key, padded))\n}", "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func (m *TripleDesCBC) Encrypt(key, s string) (string, error) {\n\t//set aeskey\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tace, err := gocrypto.TripleDesCBCEncrypt([]byte(kpassSign + s))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(ace), nil\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func encrypt(s string) []byte {\n\ts = strings.ReplaceAll(s, \";\", \"%3B\")\n\ts = strings.ReplaceAll(s, \"=\", \"%3D\")\n\tplain := prefix + s + suffix\n\n\tvar enc bytes.Buffer\n\tif err := common.NewCTR(key, nonce).Process(strings.NewReader(plain), &enc); err != nil {\n\t\tpanic(err)\n\t}\n\treturn enc.Bytes()\n}", "func Encrypt(aeadCipher cipher.AEAD, metadata, data string) (string, error) {\n\n\tvar (\n\t\tnonce = make([]byte, aeadCipher.NonceSize())\n\t\tciphertext []byte\n\t\tb64metadata []byte\n\t\tb64ciphertext []byte\n\t\tb64nonce []byte\n\t\tbuf bytes.Buffer\n\t\terr error\n\t)\n\n\t//A nonce of the length required by the AEAD is generated\n\t_, err = rand.Read(nonce)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//Seal encrypts the data using the aeadCipher's key and the nonce and appends an authentication code for the metadata\n\tciphertext = aeadCipher.Seal(ciphertext, nonce, []byte(data), []byte(metadata))\n\n\t//Base64 Encode metadata, ciphertext and nonce\n\tb64metadata = make([]byte, base64.URLEncoding.EncodedLen(len([]byte(metadata))))\n\tbase64.URLEncoding.Encode(b64metadata, []byte(metadata))\n\tb64ciphertext = make([]byte, base64.URLEncoding.EncodedLen(len(ciphertext)))\n\tbase64.URLEncoding.Encode(b64ciphertext, ciphertext)\n\tb64nonce = make([]byte, base64.URLEncoding.EncodedLen(len(nonce)))\n\tbase64.URLEncoding.Encode(b64nonce, nonce)\n\n\t//Compose a <b64URLmetadata>.<b64URLciphertext>.<b64URLnonce> literal\n\tbuf.Write(b64metadata)\n\tbuf.Write([]byte(\".\"))\n\tbuf.Write(b64ciphertext)\n\tbuf.Write([]byte(\".\"))\n\tbuf.Write(b64nonce)\n\n\t//Return the AEAD literal\n\treturn string(buf.Bytes()), nil\n}", "func (store *SessionCookieStore) encrypt(buf []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher([]byte(store.SecretKey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taead, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tiv := make([]byte, aead.NonceSize(), len(buf)+aead.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tencrypted := aead.Seal(nil, iv, buf, nil)\n\treturn append(iv, encrypted...), nil\n}", "func Encrypt(key string, text string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n pub, err := x509.ParsePKIXPublicKey(block.Bytes)\n pubkey, _ := pub.(*rsa.PublicKey) \n\n // create the propertiess\n message := []byte(text)\n label := []byte(\"\")\n hash := sha256.New()\n\n ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, message, label)\n return string(base64.StdEncoding.EncodeToString(ciphertext)), err\n\n}", "func (e *gcm) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func (a *AES) Encrypt() []byte {\n\treturn aesCrypt(a, a.key)\n}", "func (item *Item) encrypt(skey []byte) error {\n\tif len(skey) == 0 {\n\t\treturn errors.New(\"empty item key for encyption\")\n\t}\n\tif item.Content == \"\" {\n\t\treturn errors.New(\"empty plainText\")\n\t}\n\tkey := item.cipherKey(skey)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tplainText := []byte(item.Content)\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn errors.New(\"iv random generation error\")\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\titem.eContent = hex.EncodeToString(cipherText)\n\treturn nil\n}", "func (e *cbcPKCS5Padding) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func (s *Secret) Encrypt() error {\n\treturn s.clean(s.encrypt)\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherText := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream := cipher.NewCTR(c, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plaintext)\n\treturn cipherText, nil\n}", "func encrypt(plaintext []byte) []byte {\n IV := genRandomBytes(ivLen)\n ciphertext := aead.Seal(nil, IV, plaintext, nil)\n\n return append(IV[:], ciphertext[:]...)\n}", "func doEncrypt(ctx context.Context, data []byte, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) (*string, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n \tvalue := base64.RawURLEncoding.EncodeToString(data)\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &value,\n\t}\n\t\n\tresult, err := kvClient.Encrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to encrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\treturn result.Result, nil\n}", "func SymmetricEncrypt(plaintext, id, key string) (*Encrypted, error) {\n\n\trawKey, err := hex.DecodeString(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not decode key: %s\", err)\n\t}\n\n\tnewKey, salt, err := ExpandKey(rawKey, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Cold not expand key: %s\", err)\n\t}\n\n\tciphertext, iv, err := AESEncrypt([]byte(plaintext), newKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := make(map[string]string)\n\tinputs[\"key-id\"] = id\n\tinputs[\"iv\"] = string(Base64Encode(iv))\n\tinputs[\"salt\"] = string(Base64Encode(salt))\n\n\treturn &Encrypted{Ciphertext: string(Base64Encode(ciphertext)), Mode: \"aes-cbc-256\", Inputs: inputs}, nil\n}", "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func (e aesGCMEncodedEncryptor) Encrypt(plaintext string) (ciphertext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"primary key is unavailable\")}\n\t}\n\n\tcipherbytes, err := gcmEncrypt([]byte(plaintext), e.primaryKey)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{errors.Errorf(\"unable to encrypt: %v\", err)}\n\t}\n\n\tciphertext = base64.StdEncoding.EncodeToString(cipherbytes)\n\treturn e.PrimaryKeyHash() + separator + ciphertext, nil\n}", "func Encrypt(key, iv, message []byte) []byte {\n\treturn encryption.EncryptAESECB(key, iv, message)\n}", "func Encrypt(input []byte, key []byte) []byte {\n\tresult := make([]byte, len(input))\n\n\tfor i, inputByte := range input {\n\t\tresult[i] = inputByte ^ key[i%len(key)]\n\t}\n\n\treturn result\n}", "func EncryptString(password string) ([]byte, error) {\n\tif len(password) == 0 {\n\t\treturn nil, errors.New(\"password should not be empty\")\n\t}\n\n\t// Make sure the second param `bcrypt generator cost` between [4, 32)\n\tpasswordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn passwordHash, nil\n}", "func (s SecureCellSymmetricBackend) Encrypt(key []byte, data []byte, context []byte) (out []byte, err error) {\n\tseal, err := cell.SealWithKey(&keys.SymmetricKey{Value: key})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn seal.Encrypt(data, context)\n}", "func encryptPassword(password string) string {\n\tencoded := sha1.New()\n\tencoded.Write([]byte(password))\n\treturn hex.EncodeToString(encoded.Sum(nil))\n}", "func encrypt(value []byte, key Key) ([]byte, error) {\n\tnsize := make([]byte, key.cipherObj.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nsize); err != nil {\n\t\treturn value, err\n\t}\n\n\treturn key.cipherObj.Seal(nsize, nsize, value, nil), nil\n}", "func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error) {\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesOpt.aesGCM.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encryptAES.io.ReadFull\")\n\t}\n\n\t//Encrypt the data using aesGCM.Seal\n\t//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.\n\tciphertext := aesOpt.aesGCM.Seal(nonce, nonce, plainText, nil)\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func (b *DynamoDbBackend) encrypt(value interface{}) (string, error) {\n\tr, err := readBinary(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ti := kms.EncryptInput{KeyId: aws.String(keyArn.String()), Plaintext: data}\n\to, err := b.k.Encrypt(&i)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tlog.Debugf(\"successfully encrypted data\")\n\n\t// Encrypt API call returns bytes, encode to base64 and return\n\treturn base64.StdEncoding.EncodeToString(o.CiphertextBlob), nil\n}", "func (e *AESCTREncryptor) Encrypt(secret []byte) (*EncryptedData, error) {\n\tciphertext := make([]byte, aes.BlockSize+len(secret))\n\n\t// Generate a random IV\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\t// No entropy? You've got bigger problems\n\t\treturn nil, err\n\t}\n\n\tstream := cipher.NewCTR(e.block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], secret)\n\n\t// Generate our HMAC\n\tmac := hmac.New(sha256.New, e.hmacKey)\n\tmac.Write(ciphertext)\n\n\treturn &EncryptedData{\n\t\tCiphertext: ciphertext,\n\t\tHMAC: mac.Sum(nil),\n\t\tType: AESCTR,\n\t}, nil\n}", "func (t *CryptoHandler) encryptInline(plain []byte, key, tfvf string, dblEncrypt bool, exclWhitespace bool) ([]byte, error) {\n\n\tif !dblEncrypt {\n\t\tr := regexp.MustCompile(thCryptoWrapRegExp)\n\t\tm := r.FindSubmatch(plain)\n\t\tif len(m) >= 1 {\n\t\t\treturn nil, newCryptoWrapError(errMsgAlreadyEncrypted)\n\t\t}\n\t}\n\n\ttfvu := NewTfVars(tfvf, exclWhitespace)\n\tinlineCreds, err := tfvu.Values()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinlinedText := string(plain)\n\tfor _, v := range inlineCreds {\n\t\tct, err := t.Encrypter.Encrypt(key, []byte(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinlinedText = strings.Replace(inlinedText, v, string(ct), -1)\n\t}\n\n\treturn []byte(inlinedText), nil\n}", "func encryptCBC(plainText, key []byte) (cipherText []byte, err error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText = pad(aes.BlockSize, plainText)\n\n\tcipherText = make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\t_, err = io.ReadFull(cryptoRand.Reader, iv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], plainText)\n\n\treturn cipherText, nil\n}", "func (c client) Encrypt(plaintext []byte) (*Secret, error) {\n\tr, err := c.cloudkmsClient.Projects.Locations.KeyRings.CryptoKeys.Encrypt(c.cryptoKey, &cloudkms.EncryptRequest{\n\t\tPlaintext: base64.StdEncoding.EncodeToString(plaintext),\n\t}).Do()\n\tif err != nil {\n\t\treturn nil, go_errors.Wrap(err, \"Failed to encrypt plaintext\")\n\t}\n\treturn &Secret{\n\t\tCiphertext: r.Ciphertext,\n\t\tName: r.Name,\n\t}, nil\n}", "func Encrypt(content string, salt string) string {\n\treturn fmt.Sprintf(\"%x\", pbkdf2.Key([]byte(content), []byte(salt), 4096, 16, sha1.New))\n}", "func encryptDecryptXor(input string, key byte) (output string) {\n for i := 0; i < len(input); i++ {\n output += string(input[i] ^ key)\n }\n return output\n}", "func encryptConfig(key []byte, clearText []byte) (string, error) {\n\tsecret := &AESSecret{}\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce, err := randomNonce(12)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.Nonce = nonce\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.CipherText = gcm.Seal(nil, secret.Nonce, clearText, nil)\n\n\tjsonSecret, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonSecret), nil\n}", "func (r *copyRunner) encrypt(plaintext []byte) ([]byte, error) {\n\tif (r.password != \"\" || r.symmetricKeyFile != \"\") && (r.publicKeyFile != \"\" || r.gpgUserID != \"\") {\n\t\treturn nil, fmt.Errorf(\"only one of the symmetric-key or public-key can be used for encryption\")\n\t}\n\n\t// Perform hybrid encryption with a public-key if it exists.\n\tif r.publicKeyFile != \"\" || r.gpgUserID != \"\" {\n\t\treturn r.encryptWithPubKey(plaintext)\n\t}\n\n\t// Encrypt with a symmetric-key if key exists.\n\tkey, err := getSymmetricKey(r.password, r.symmetricKeyFile)\n\tif errors.Is(err, errNotfound) {\n\t\treturn plaintext, nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get key: %w\", err)\n\t}\n\tencrypted, err := pbcrypto.Encrypt(key, plaintext)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encrypt the plaintext: %w\", err)\n\t}\n\treturn encrypted, nil\n}", "func Encrypt(input []byte, password string) ([]byte, error) {\n\tkey := sha256.Sum256([]byte(password))\n\tblock, err := aes.NewCipher(key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonce := make([]byte, 12)\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Seal(nonce, nonce, input, nil), nil\n}", "func Encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpad := aes.BlockSize - len(plaintext)%aes.BlockSize\n\tplaintext = append(plaintext, bytes.Repeat([]byte{byte(pad)}, pad)...)\n\tciphertext := make([]byte, len(plaintext))\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, plaintext)\n\treturn ciphertext, nil\n}", "func EncryptSHA256(text string) string {\n h := sha256.New()\n h.Write([]byte(text))\n s := base64.URLEncoding.EncodeToString(h.Sum(nil))\n return (s)\n}", "func Encrypt(plaintext, key []byte) ([]byte, error) {\n\n // Check the key size.\n if len(key) != KeySize {\n return nil, ErrInvalidKeySize\n }\n\n // Create a random initialization vector.\n iv := make([]byte, aes.BlockSize)\n _, err := io.ReadFull(rand.Reader, iv)\n if err != nil {\n return nil, ErrInvalidIV\n }\n\n // Pad the plaintext so its length is a multiple of the AES block size.\n pplaintext := pad(plaintext)\n ciphertext := make([]byte, len(pplaintext))\n\n // Generate the ciphertext and prepend the initialization vector.\n c, _ := aes.NewCipher(key)\n encrypter := cipher.NewCBCEncrypter(c, iv)\n encrypter.CryptBlocks(ciphertext, pplaintext)\n ciphertext = append(iv, ciphertext...)\n\n // Generate and append the HMAC.\n hash := hmac.New(sha256.New, key)\n hash.Write(ciphertext)\n ciphertext = hash.Sum(ciphertext)\n\n return ciphertext, nil\n}", "func (e ECBEncryptionOracle) Encrypt(myString []byte) []byte {\n\treturn e.ecb.Encrypt(append(e.prepend, append(myString, e.unknownString...)...))\n}", "func EncryptAES(src string) (based string, err error) {\n\t//Initial []byte token\n\ttoken, err := hex.DecodeString(\"46356afe55fa3cea9cbe73ad442cad47\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Block from Cipher\n\tblock, err := aes.NewCipher(token)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tblockSize := block.BlockSize()\n\tecbe := cipher.NewCBCEncrypter(block, token[:blockSize])\n\tcontent := PKCS5Padding([]byte(src), blockSize)\n\t// Initial crypt value\n\tcrypted := make([]byte, len(content))\n\tecbe.CryptBlocks(crypted, content)\n\tbased = base64.StdEncoding.EncodeToString(crypted)\n\treturn\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func (s service) EncryptPassword(src string) string {\n\tbytes, _ := bcrypt.GenerateFromPassword([]byte(s.getRawPasswordWithSalt(src)), bcrypt.MinCost)\n\treturn string(bytes)\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\t// Get cipher object with key\n\taesgcm, err := getCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate nonce\n\tnonce := make([]byte, aesgcm.NonceSize())\n\tif _, err := rand.Read(nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encrypt data\n\tciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)\n\n\treturn append(nonce, ciphertext...), nil\n}", "func EncryptThis(text string) string {\n\n\tif len(text) == 0 {\n\t\treturn text\n\t}\n\n\tstr := strings.Split(text, \" \")\n\n\tstrEncrypt := \"\"\n\n\tfor _, v := range str {\n\n\t\tstrEncrypt += fmt.Sprintf(\"%s \", encryptThis(v))\n\n\t}\n\n\treturn strings.TrimSpace(strEncrypt)\n}", "func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {\n\talgorithm, ok := parameters[Algorithm]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Encrypt\", Algorithm)\n\t\treturn nil\n\t}\n\n\tsecretName := parameters[SecretName]\n\tsecretValueKey := parameters[SecretValueKey]\n\tencryptionKey := parameters[EncryptionKey]\n\n\t// SecretName & SecretValueKey are optional if EncryptionKey specified\n\t// EncryptionKey is optional if SecretName & SecretValueKey are specified\n\n\t// If EncryptionKey not specified, then SecretName & SecretValueKey must be specified\n\tif len(encryptionKey) == 0 && (len(secretName) == 0 || len(secretValueKey) == 0) {\n\t\tapp.lc.Errorf(\"Could not find '%s' or '%s' and '%s' in configuration\", EncryptionKey, SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\t// SecretName & SecretValueKey both must be specified it one of them is.\n\tif (len(secretName) != 0 && len(secretValueKey) == 0) || (len(secretName) == 0 && len(secretValueKey) != 0) {\n\t\tapp.lc.Errorf(\"'%s' and '%s' both must be set in configuration\", SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\tswitch strings.ToLower(algorithm) {\n\tcase EncryptAES256:\n\t\tif len(secretName) > 0 && len(secretValueKey) > 0 {\n\t\t\tprotector := transforms.AESProtection{\n\t\t\t\tSecretName: secretName,\n\t\t\t\tSecretValueKey: secretValueKey,\n\t\t\t}\n\t\t\treturn protector.Encrypt\n\t\t}\n\t\tapp.lc.Error(\"secretName / secretValueKey are required for AES 256 encryption\")\n\t\treturn nil\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid encryption algorithm '%s'. Must be '%s\",\n\t\t\talgorithm,\n\t\t\tEncryptAES256)\n\t\treturn nil\n\t}\n}", "func EncryptWithUnknownStr(input []byte) ([]byte, error) {\n\tunknownStr := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\" +\n\t\t\"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\" +\n\t\t\"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\" +\n\t\t\"YnkK\"\n\n\tunknown, err := base64.StdEncoding.DecodeString(unknownStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tinput = append(input, unknown...)\n\treturn EncryptECBFixedKey(input)\n}", "func Encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\tplaintext = pad(plaintext, aes.BlockSize)\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn nil, fmt.Errorf(\"plaintext is not a multiple of the block size: %d / %d\", len(plaintext), aes.BlockSize)\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ciphertext []byte\n\tif iv == nil {\n\t\tciphertext = make([]byte, aes.BlockSize+len(plaintext))\n\t\tiv := ciphertext[:aes.BlockSize]\n\t\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcbc := cipher.NewCBCEncrypter(block, iv)\n\t\tcbc.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\t} else {\n\t\tciphertext = make([]byte, len(plaintext))\n\n\t\tcbc := cipher.NewCBCEncrypter(block, iv)\n\t\tcbc.CryptBlocks(ciphertext, plaintext)\n\t}\n\n\treturn ciphertext, nil\n}", "func Encrypt(pubkey string, pin string, uuid string) (string, error) {\n\tblock, err := base64.StdEncoding.DecodeString(pubkey)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpub, err := x509.ParsePKIXPublicKey(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trsaPub, _ := pub.(*rsa.PublicKey)\n\t//fmt.Printf(\"The key is: %v, its type is %T\", rsaPub, rsaPub)\n\n\t// do the encryption\n\tmsg := uuid + pin\n\trsakey, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPub, []byte(msg))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t//fmt.Printf(\"the encryption is: %v\", rsakey)\n\tencodedKey := base64.StdEncoding.EncodeToString(rsakey)\n\tfmt.Printf(\"the key is: %v\\n\", encodedKey)\n\tfmt.Printf(\"The uuid is: %v\\n\", uuid)\n\treturn encodedKey, nil\n}", "func encryptionWrapperDev(myMessage []byte) []byte {\n\tsecretMessage := []byte(\"Hi secret message\")\n\tkey := []byte(\"12345678abcdefgh\")\n\tmsg := append(myMessage, secretMessage...)\n\treturn Encrypt(msg, key)\n}", "func EncryptStr_AES_CBC(s, key string) (encoded string, err error) {\n\tvar ciphertext []byte\n\tif ciphertext, err = Encrypt_AES_CBC([]byte(s), []byte(key)); err != nil {\n\t\treturn\n\t}\n\n\tencoded = base64.StdEncoding.EncodeToString(ciphertext)\n\treturn\n}", "func Encrypt(publicKeyPath string, output string, data []byte) (encryptedKey, encryptedData string) {\n\t// Public key\n\tpublicKey := ReadRsaPublicKey(publicKeyPath)\n\n\t// AEs key\n\tkey := NewAesEncryptionKey()\n\t// fmt.Printf(\"AES key: %v \\n\", *key)\n\ttext := []byte(string(data))\n\tencrypted, _ := AesEncrypt(text, key)\n\n\t// Base64 encode\n\tencryptedRsa, _ := RsaEncrypt(key, publicKey)\n\tb64key := b64.StdEncoding.EncodeToString([]byte(encryptedRsa))\n\tsEnc := b64.StdEncoding.EncodeToString(encrypted)\n\n\treturn b64key, sEnc\n}" ]
[ "0.72404784", "0.71205395", "0.71038103", "0.6945274", "0.69017804", "0.6839854", "0.68293124", "0.67038935", "0.66716707", "0.6665801", "0.66609514", "0.6656868", "0.6652399", "0.6649661", "0.6634841", "0.66111594", "0.65648746", "0.64746803", "0.6450845", "0.64472514", "0.6437232", "0.6431552", "0.64067703", "0.64031065", "0.6395554", "0.6374633", "0.6362486", "0.6360183", "0.6358181", "0.62713134", "0.6261619", "0.62432885", "0.6242957", "0.62428844", "0.62345713", "0.6228109", "0.6226487", "0.62122434", "0.62074107", "0.6191647", "0.61885643", "0.6184982", "0.615862", "0.6136083", "0.6128262", "0.61103725", "0.61012334", "0.60829216", "0.60644567", "0.60511726", "0.6041865", "0.60150695", "0.60063964", "0.60001993", "0.5997942", "0.59972507", "0.5992581", "0.59900033", "0.59735715", "0.5950894", "0.59483635", "0.59463644", "0.59185874", "0.5901422", "0.58957547", "0.5893193", "0.5880772", "0.58805513", "0.58706206", "0.58653355", "0.586035", "0.5858839", "0.5858322", "0.5849962", "0.5843465", "0.58399177", "0.58392006", "0.58265704", "0.58183366", "0.58139634", "0.58064103", "0.58056366", "0.58018965", "0.57955027", "0.57880354", "0.57859176", "0.5782974", "0.5773277", "0.5769081", "0.5767021", "0.5746409", "0.5743227", "0.57418424", "0.5741099", "0.5739316", "0.5736286", "0.57347286", "0.573144", "0.5728284", "0.57279927" ]
0.7227071
1
NewMsgStartRequest creates a new MsgStartRequest instance with the given parameters.
func NewMsgStartRequest(from sdk.AccAddress, id uint64, addr hubtypes.NodeAddress) *MsgStartRequest { return &MsgStartRequest{ From: from.String(), ID: id, Address: addr.String(), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMsgCreateRequest(from hubtypes.ProvAddress, duration time.Duration, gigabytes int64, prices sdk.Coins) *MsgCreateRequest {\n\treturn &MsgCreateRequest{\n\t\tFrom: from.String(),\n\t\tDuration: duration,\n\t\tGigabytes: gigabytes,\n\t\tPrices: prices,\n\t}\n}", "func CreateStartNotaryRequest() (request *StartNotaryRequest) {\n\trequest = &StartNotaryRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Trademark\", \"2018-07-24\", \"StartNotary\", \"trademark\", \"openAPI\")\n\treturn\n}", "func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(id string, method string, params interface{}) *Request {\n\tbuffer, err := json.Marshal(params)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Request{JsonRPC: \"2.0\", Id: id, Method: method, Params: buffer}\n}", "func NewRequest(id, replyTo string, object ObjectID, method string, args ...interface{}) (*Request, error) {\n\tinputs, err := newTuple(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\tID: id,\n\t\tInputs: inputs,\n\t\tObject: object,\n\t\tReplyTo: replyTo,\n\t\tMethod: method,\n\t}, nil\n}", "func NewRequest(robot *Robot, message *Message, query []string) *Request {\n\treturn &Request{\n\t\tMessage: message,\n\t\tQuery: query,\n\t\trobot: robot,\n\t}\n}", "func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func CreateStartRecordTaskRequest() (request *StartRecordTaskRequest) {\n\trequest = &StartRecordTaskRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"rtc\", \"2018-01-11\", \"StartRecordTask\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest() *Request {\n\tr := &Request{\n\t\tAggregations: make(map[string]types.Aggregations, 0),\n\t\tExt: make(map[string]json.RawMessage, 0),\n\t\tScriptFields: make(map[string]types.ScriptField, 0),\n\t}\n\treturn r\n}", "func NewRequest() *Request {\n\tr := &Request{\n\t\tAggregations: make(map[string]types.Aggregations, 0),\n\t\tExt: make(map[string]json.RawMessage, 0),\n\t\tScriptFields: make(map[string]types.ScriptField, 0),\n\t}\n\treturn r\n}", "func NewRequest(bufid string, acts ...Action) Request {\n\tr := Request{BufferID: bufid}\n\tr.Add(acts...)\n\treturn r\n}", "func (s *HsmProvidersService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService22ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(query string, params map[string]interface{}) (*Request, error) {\n\treq := &Request{Query: query, Params: params}\n\n\t// serialize the params\n\td, err := clSzlr.Serialize(params)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error creating new request\")\n\t}\n\n\t// assign the data to request\n\treq.Data = d\n\treturn req, nil\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *Client) newRequest(t RequestType) *Request {\n\tc.seqID++\n\treturn &Request{\n\t\tAPIVersion: \"v1\",\n\t\tRequestType: t,\n\t\tTracerTime: time.Now().Unix(),\n\t\tRuntimeID: globalconfig.RuntimeID(),\n\t\tSeqID: c.seqID,\n\t\tDebug: c.debug,\n\t\tApplication: Application{\n\t\t\tServiceName: c.Service,\n\t\t\tEnv: c.Env,\n\t\t\tServiceVersion: c.Version,\n\t\t\tTracerVersion: version.Tag,\n\t\t\tLanguageName: \"go\",\n\t\t\tLanguageVersion: runtime.Version(),\n\t\t},\n\t\tHost: Host{\n\t\t\tHostname: hostname,\n\t\t\tContainerID: internal.ContainerID(),\n\t\t\tOS: getOSName(),\n\t\t\tOSVersion: getOSVersion(),\n\t\t},\n\t}\n}", "func (s *ApplicationsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService19ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService18ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService17ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService21ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *AuthnReqListsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *VirtualhostsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *SQS) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\t// Run custom request initialization if present\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}", "func NewRequest(m Manager) *Request {\n\treturn &Request{\n\t\tm: m,\n\t\trLocks: make(map[string]struct{}),\n\t\twLocks: make(map[string]struct{}),\n\t}\n}", "func newRequest(ctx context.Context, msg interface{}) *request {\n\treturn &request{\n\t\tctx: ctx,\n\t\tmsg: msg,\n\t\tfailure: make(chan error, 1),\n\t\tresponse: make(chan *Delivery, 1),\n\t}\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(conn Conn, data []byte, offset int) Request {\n\treturn &request{conn: conn, data: data, offset: offset}\n}", "func NewRequest(str string) (*Request, error) {\n\tallmatches := logRegexp.FindAllStringSubmatch(str, -1)\n\tif len(allmatches) == 0 {\n\t\treturn &Request{}, fmt.Errorf(\"no matches\")\n\t}\n\tmatches := allmatches[0]\n\n\tbytes, err := strconv.Atoi(matches[6])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq_time, err := strconv.ParseFloat(matches[7], 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := &Request{\n\t\tIp: matches[1],\n\t\tStatus: matches[5],\n\t\tBytesSent: bytes,\n\t\tReqTime: req_time,\n\t\tReferer: matches[8],\n\t\tAgent: matches[9],\n\t}\n\n\tparseTimestamp(matches[3], req)\n\tparseRequest(matches[4], req)\n\tfmt.Println(str)\n\treturn req, nil\n}", "func (s Benchmark_send_Params) NewReq() (Message, error) {\n\tss, err := NewMessage(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (c *InputService16ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService20ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest() *Request {\n\tr := &Request{}\n\treturn r\n}", "func NewRequest() *Request {\n\tr := &Request{}\n\treturn r\n}", "func NewRequest() *Request {\n\tr := &Request{}\n\treturn r\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(id string, method string) *Request {\n\n\treq := &Request{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t}\n\treturn req\n}", "func NewRequest(methodName string, params []interface{}) (req Request, err error) {\n\treq = Request{\n\t\tMethodName: methodName,\n\t\tParams: make([]Value, 0, len(params)),\n\t}\n\n\tfor _, p := range params {\n\t\tv := NewValue(p)\n\t\tif v == nil {\n\t\t\treturn req, fmt.Errorf(\"NewRequest: cannot convert parameter %v\", p)\n\t\t}\n\n\t\treq.Params = append(req.Params, *v)\n\t}\n\n\treturn req, nil\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *HighAvailabilityService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest() *Request {\n\treturn &Request{}\n}", "func NewRequest() *Request {\n\treturn &Request{}\n}", "func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (service *Service) CreateRequest(parameters map[string]string) (*Request, error) {\n\tvar int1, int2, limit int64\n\tvar err error\n\n\t// Convert string parameters to int64\n\tif int1, err = strconv.ParseInt(parameters[\"int1\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif int2, err = strconv.ParseInt(parameters[\"int2\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\tif limit, err = strconv.ParseInt(parameters[\"limit\"], 10, 64); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\tInt1: int1,\n\t\tInt2: int2,\n\t\tLimit: limit,\n\t\tStr1: parameters[\"str1\"],\n\t\tStr2: parameters[\"str2\"],\n\t}, nil\n}", "func NewRequest(command string) (qr quantum.Request, err error) {\n\tr := Request{\n\t\tCommand: command,\n\t}\n\td, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tqr = NewRequestJSON(d)\n\treturn\n}", "func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *OidcService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMintRequest(to common.Address, anchorID anchors.AnchorID, proofs []*proofspb.Proof, rootHash [32]byte) (*MintRequest, error) {\n\n\t// tokenID is uint256 in Solidity (256 bits | max value is 2^256-1)\n\t// tokenID should be random 32 bytes (32 byte = 256 bits)\n\ttokenID := utils.ByteSliceToBigInt(utils.RandomSlice(32))\n\ttokenURI := \"http:=//www.centrifuge.io/DUMMY_URI_SERVICE\"\n\tproofData, err := createProofData(proofs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MintRequest{\n\t\tTo: to,\n\t\tTokenID: tokenID,\n\t\tTokenURI: tokenURI,\n\t\tAnchorID: anchorID.BigInt(),\n\t\tMerkleRoot: rootHash,\n\t\tValues: proofData.Values,\n\t\tSalts: proofData.Salts,\n\t\tProofs: proofData.Proofs}, nil\n}", "func NewRequest(ctx context.Context, id uint32, ids []cid.Cid) *Request {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Request{id: id, bs: make(chan []blocks.Block, len(ids)/2), ids: ids, done: ctx.Done(), cancel: cancel}\n}", "func New(securityreqid string, securitylistrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityListRequestType(securitylistrequesttype)\n\treturn &m\n}", "func NewRequest(page, pageSize int32) PaginationRequest {\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\n\tif pageSize == 0 {\n\t\tpageSize = 15\n\t}\n\n\treturn PaginationRequest{\n\t\tPage: uint64(page),\n\t\tPageSize: uint64(pageSize),\n\t}\n}", "func (client *ManagedInstancesClient) startCreateRequest(ctx context.Context, resourceGroupName string, managedInstanceName string, options *ManagedInstancesClientBeginStartOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/start\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif managedInstanceName == \"\" {\n\t\treturn nil, errors.New(\"parameter managedInstanceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managedInstanceName}\", url.PathEscape(managedInstanceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (bt *BlipTester) newRequest() *blip.Message {\n\tmsg := blip.NewRequest()\n\tbt.addCollectionProperty(msg)\n\treturn msg\n}", "func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewReq(required []string) *Request {\n\treturn &Request{\n\t\targuments: make(map[string]string),\n\t\trequired: required,\n\t}\n}", "func (c *OutputService14ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func New(securityreqid string, securityrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityRequestType(securityrequesttype)\n\treturn &m\n}", "func CreateStartK8sApplicationRequest() (request *StartK8sApplicationRequest) {\n\trequest = &StartK8sApplicationRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Edas\", \"2017-08-01\", \"StartK8sApplication\", \"/pop/v5/k8s/acs/start_k8s_app\", \"Edas\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewRequest(addr string, body []byte) *Request {\n\treturn &Request{\n\t\tAddr: addr,\n\t\tHeader: defaultHeader(len(body)),\n\t\tBody: body,\n\t}\n}", "func (s *SitesService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService13ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(q string) *Request {\n\treq := &Request{\n\t\tq: q,\n\t\tHeader: make(map[string][]string),\n\t}\n\treturn req\n}", "func NewMsgEndRequest(from sdk.AccAddress, id uint64, rating uint64) *MsgEndRequest {\n\treturn &MsgEndRequest{\n\t\tFrom: from.String(),\n\t\tID: id,\n\t\tRating: rating,\n\t}\n}", "func NewRequest() (r *Request) {\n\treturn &Request{}\n}", "func NewGenRequest(payload *maze.GenPayload) *mazepb.GenRequest {\n\tmessage := &mazepb.GenRequest{\n\t\tW: int32(payload.W),\n\t\tH: int32(payload.H),\n\t}\n\treturn message\n}", "func NewRequest(reqType string) (req map[string]interface{}) {\n\treturn map[string]interface{}{\n\t\t\"req\": reqType,\n\t}\n}", "func NewRequest() *Request {\n\treturn defaul.NewRequest()\n}", "func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *APIGateway) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\t// Run custom request initialization if present\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}", "func (client *VirtualMachinesClient) startCreateRequest(ctx context.Context, resourceGroupName string, virtualMachineName string, options *VirtualMachinesClientBeginStartOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ConnectedVMwarevSphere/virtualMachines/{virtualMachineName}/start\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif virtualMachineName == \"\" {\n\t\treturn nil, errors.New(\"parameter virtualMachineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{virtualMachineName}\", url.PathEscape(virtualMachineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-10-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService15ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(name string) *Request {\n\tresult := Request{name: name}\n\tresult.pending = nil\n\tresult.approved = nil\n\treturn &result\n}" ]
[ "0.71772456", "0.6506978", "0.6439819", "0.6419403", "0.64005965", "0.6399491", "0.63943535", "0.6358463", "0.6330042", "0.6330042", "0.6317386", "0.62933475", "0.6277419", "0.6265687", "0.6265687", "0.62646914", "0.62646914", "0.6256092", "0.6254599", "0.62524027", "0.6251509", "0.62439466", "0.62382495", "0.62347656", "0.62347656", "0.62341595", "0.62107116", "0.620875", "0.62067086", "0.62067086", "0.6199746", "0.6197114", "0.61817", "0.61817", "0.61791456", "0.617008", "0.6167948", "0.6158019", "0.6153221", "0.6153192", "0.6152317", "0.6152317", "0.61483717", "0.61428875", "0.614183", "0.6135915", "0.6132254", "0.6123599", "0.6123599", "0.6123599", "0.61019945", "0.61019945", "0.60962045", "0.6080441", "0.6080276", "0.60789514", "0.60789514", "0.6075813", "0.6075813", "0.606624", "0.60602057", "0.6054052", "0.60391164", "0.60391164", "0.60356665", "0.60262996", "0.6025064", "0.6020093", "0.60126585", "0.60100985", "0.5994203", "0.5992753", "0.5992245", "0.5992055", "0.5991032", "0.59786373", "0.5961775", "0.5948577", "0.5942522", "0.5941057", "0.5940269", "0.5938967", "0.59301084", "0.5921129", "0.5917772", "0.59164053", "0.5915939", "0.5912199", "0.5911642", "0.5910652", "0.5896135", "0.5887974", "0.58722794", "0.58709556", "0.5865848", "0.5864776", "0.58633476", "0.58633476", "0.5862494", "0.585282" ]
0.83114254
0
ValidateBasic performs basic validation checks on the MsgStartRequest fields. It checks if the 'From' field is not empty and represents a valid account address, if the 'ID' field is not zero, if the 'Address' field is not empty and represents a valid node address.
func (m *MsgStartRequest) ValidateBasic() error { if m.From == "" { return sdkerrors.Wrap(ErrorInvalidMessage, "from cannot be empty") } if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.Wrap(ErrorInvalidMessage, err.Error()) } if m.ID == 0 { return sdkerrors.Wrap(ErrorInvalidMessage, "id cannot be zero") } if m.Address == "" { return sdkerrors.Wrap(ErrorInvalidMessage, "address cannot be empty") } if _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil { return sdkerrors.Wrap(ErrorInvalidMessage, err.Error()) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (msg MsgBeginUnstake) ValidateBasic() sdk.Error {\n\tif msg.Address.Empty() {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (m *MsgSubscribeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Denom == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"denom cannot be empty\")\n\t}\n\tif err := sdk.ValidateDenom(m.Denom); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgLinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgCreateRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.Duration < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be negative\")\n\t}\n\tif m.Duration == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be zero\")\n\t}\n\tif m.Gigabytes < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be negative\")\n\t}\n\tif m.Gigabytes == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be zero\")\n\t}\n\tif m.Prices == nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be nil\")\n\t}\n\tif m.Prices.Len() == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be empty\")\n\t}\n\tif m.Prices.IsAnyNil() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot contain nil\")\n\t}\n\tif !m.Prices.IsValid() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices must be valid\")\n\t}\n\n\treturn nil\n}", "func (m *MsgUpdateDetailsRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.Proof.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.id cannot be zero\")\n\t}\n\tif m.Proof.Bandwidth.IsAnyNil() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.bandwidth cannot contain nil\")\n\t}\n\tif m.Proof.Bandwidth.IsAnyNegative() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.bandwidth cannot be negative\")\n\t}\n\tif m.Proof.Duration < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.duration cannot be negative\")\n\t}\n\tif m.Signature != nil {\n\t\tif len(m.Signature) < 64 {\n\t\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"signature length cannot be less than %d\", 64)\n\t\t}\n\t\tif len(m.Signature) > 64 {\n\t\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"signature length cannot be greater than %d\", 64)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MsgEndRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Rating > 10 {\n\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"rating cannot be greater than %d\", 10)\n\t}\n\n\treturn nil\n}", "func (msg MsgSend) ValidateBasic() sdk.Error {\n\tif msg.FromAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.ToAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Amount.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadSendAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgInitDeal) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing owner address\")\n\t}\n\tif msg.Customer.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing customer address\")\n\t}\n\tif msg.MaxTemp <= msg.MinTemp {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"maxTemp/minTemp invalid\")\n\t}\n\treturn nil\n}", "func (m *MsgUpdateStatusRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif !m.Status.IsOneOf(hubtypes.StatusActive, hubtypes.StatusInactive) {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"status must be one of [active, inactive]\")\n\t}\n\n\treturn nil\n}", "func (m *MsgUnlinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgUnjail) ValidateBasic() sdk.Error {\n\tif msg.ValidatorAddr.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgCreate) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\treturn nil\n}", "func (msg MsgBlockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgAddRecord) ValidateBasic() error {\n\tif msg.Org.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Org.String())\n\t}\n\tif msg.Vin.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Vin.String())\n\t}\n\treturn nil\n}", "func (msg MsgCreatePDV) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Owner.String())\n\t}\n\tif msg.DataType < PDVTypeCookie || msg.DataType > PDVTypeLoginCookie {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid type\")\n\t}\n\tif !cerberusapi.IsAddressValid(msg.Address) {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid address\")\n\t}\n\tif msg.Timestamp == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"Timestamp can not be 0\")\n\t}\n\treturn nil\n}", "func (msg MsgRagnarok) ValidateBasic() error {\n\tif msg.Signer.Empty() {\n\t\treturn cosmos.ErrInvalidAddress(msg.Signer.String())\n\t}\n\tif msg.BlockHeight <= 0 {\n\t\treturn cosmos.ErrUnknownRequest(\"invalid block height\")\n\t}\n\tif err := msg.Tx.Valid(); err != nil {\n\t\treturn cosmos.ErrUnknownRequest(err.Error())\n\t}\n\treturn nil\n}", "func (msg MsgAddMember) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 || len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgHeartbeat) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgAuctionReveal) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (msg MsgSetPauseStatus) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgTest) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\tif strings.Contains(msg.Test, \"bad\") {\n\t\treturn sdk.ErrUnauthorized(\"\").TraceSDK(\"bad test\")\n\t}\n\treturn nil\n}", "func (msg MsgLock) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgFulfillTrade) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\treturn nil\n}", "func (msg *MsgInviteUser) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Recipient)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid recipient address: %s (%s)\", msg.Recipient, err))\n\t}\n\t_, err = sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid sender address: %s (%s)\", msg.Sender, err))\n\t}\n\treturn nil\n}", "func (msg MsgLeave) ValidateBasic() sdk.Error {\n\tif msg.Tx.FromAddress.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"from address cannot be empty\")\n\t}\n\tif msg.Tx.ID.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"tx id hash cannot be empty\")\n\t}\n\tif msg.Signer.Empty() {\n\t\treturn sdk.ErrUnknownRequest(\"signer cannot be empty \")\n\t}\n\treturn nil\n}", "func (msg MsgUnblockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgEthermint) ValidateBasic() sdk.Error {\n\tif msg.Price.Sign() != 1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"price must be positive %s\", msg.Price),\n\t\t)\n\t}\n\n\t// Amount can be 0\n\tif msg.Amount.Sign() == -1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"amount cannot be negative %s\", msg.Amount),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgSetMoniker) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\t//\tif len(msg.Moniker) == 0 || len(msg.Value) == 0 {\n\t//\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t//\t}\n\treturn nil\n}", "func (msg MsgBurn) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\treturn nil\n}", "func (msg MsgSetStakeData) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Name cannot be empty\")\n\t}\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Ticker cannot be empty\")\n\t}\n\tif len(msg.Atom) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Atom cannot be empty\")\n\t}\n\tif len(msg.Token) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Token cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgStake) ValidateBasic() sdk.Error {\n\n\tif msg.PubKey == nil || msg.PubKey.RawString() == \"\" {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Value.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadDelegationAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgRedeemTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\treturn nil\n}", "func (msg MsgCreateCoin) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\n\tif msg.PosminingEnabled {\n\t\ti := 1\n\n\t\tfor i < len(msg.PosminingBalance) - 1 {\n\t\t\tif !msg.PosminingBalance[i].FromAmount.Equal(msg.PosminingBalance[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Posmining coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\n\t\ti = 1\n\n\t\tfor i < len(msg.StructurePosmining) - 1 {\n\t\t\tif !msg.StructurePosmining[i].FromAmount.Equal(msg.StructurePosmining[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Structure coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *SendTx) ValidateBasic() error {\n\tif s.chainID == \"\" {\n\t\treturn errors.New(\"No chain-id specified\")\n\t}\n\tfor _, in := range s.Tx.Inputs {\n\t\tif len(in.Address) != 20 {\n\t\t\treturn errors.Errorf(\"Invalid input address length: %d\", len(in.Address))\n\t\t}\n\t\tif !in.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid input coins %v\", in.Coins)\n\t\t}\n\t\tif in.Coins.IsZero() {\n\t\t\treturn errors.New(\"Input coins cannot be zero\")\n\t\t}\n\t\tif in.Sequence <= 0 {\n\t\t\treturn errors.New(\"Sequence must be greater than 0\")\n\t\t}\n\t}\n\tfor _, out := range s.Tx.Outputs {\n\t\t// we now allow chain/addr, so it can be more than 20 bytes\n\t\tif len(out.Address) < 20 {\n\t\t\treturn errors.Errorf(\"Invalid output address length: %d\", len(out.Address))\n\t\t}\n\t\tif !out.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid output coins %v\", out.Coins)\n\t\t}\n\t\tif out.Coins.IsZero() {\n\t\t\treturn errors.New(\"Output coins cannot be zero\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgAuctionName) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.StartingPrice.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Starting price must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgCreateSession) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid session owner: %s\", msg.Owner))\n\t}\n\n\tif len(strings.TrimSpace(msg.Namespace)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session namespace cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.PubKey)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"signer's public key cannot be empty\")\n\t}\n\n\t// The external signer address doesn't have to exist on Desmos\n\tif len(strings.TrimSpace(msg.ExternalOwner)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session external owner cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.Signature)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session signature cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (msg MsgCreateIndex) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Field) ==0 {\n return sdk.ErrUnknownRequest(\"Field cannot be empty\")\n }\n return nil\n}", "func (msg MsgCreateTable) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (msg MsgFund) ValidateBasic() error {\n\tif !msg.Amount.IsValid() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())\n\t}\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"sender %s\", msg.Sender.String())\n\t}\n\tif msg.Recipient.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"recipient %s\", msg.Recipient.String())\n\t}\n\treturn nil\n}", "func (msg MsgClaimUSDXMintingReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif msg.MultiplierName == \"\" {\n\t\treturn errorsmod.Wrap(ErrInvalidMultiplier, \"multiplier name cannot be empty\")\n\t}\n\treturn nil\n}", "func (m *DKGMessage) ValidateBasic() error {\n\tif m.Type < 0 || m.Type > DKGDryRun {\n\t\treturn fmt.Errorf(\"invalid Type\")\n\t}\n\tif len(m.FromAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected FromAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.FromAddress),\n\t\t)\n\t}\n\tif m.DKGID < 0 || m.DKGIteration < 0 {\n\t\treturn fmt.Errorf(\"invalid DKGID/DKGIteration\")\n\t}\n\tif len(m.Data) == 0 || len(m.Data) > MaxDKGDataSize {\n\t\treturn fmt.Errorf(\"expected non-empty Data size to be less than %d bytes, got %d bytes\",\n\t\t\tMaxDKGDataSize,\n\t\t\tlen(m.Data),\n\t\t)\n\t}\n\t// ToAddress can be empty if it is intended for everyone\n\tif len(m.ToAddress) != 0 && len(m.ToAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected ToAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.ToAddress),\n\t\t)\n\t}\n\tif len(m.Signature) == 0 || len(m.Signature) > MaxSignatureSize {\n\t\treturn fmt.Errorf(\"expected Signature size be max %d bytes, got %d bytes\",\n\t\t\tMaxSignatureSize,\n\t\t\tlen(m.Signature),\n\t\t)\n\t}\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgRemoveMember) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgUpdateRecipe) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\tif len(msg.ID) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the id for the recipe require to update it\")\n\t}\n\n\tif len(msg.Description) < 20 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the description should have more than 20 characters\")\n\t}\n\n\treturn nil\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif strings.TrimSpace(msg.Dtag) == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"profile dtag cannot be empty or blank\")\n\t}\n\n\treturn nil\n}", "func (msg MsgClaimDelegatorReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgInsertRow) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (msg MsgSwap) ValidateBasic() sdk.Error {\n\tif len(msg.SourceTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Source Ticker cannot be empty\")\n\t}\n\tif len(msg.TargetTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Target cannot be empty\")\n\t}\n\tif len(msg.Amount) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Amount cannot be empty\")\n\t}\n\tif len(msg.Requester) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Requester cannot be empty\")\n\t}\n\tif len(msg.Destination) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Destination cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgDeleteName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\treturn nil\n}", "func (p Params) ValidateBasic() error {\n\tif err := validateMinimumGasPrices(p.MinimumGasPrices); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateBypassMinFeeMsgTypes(p.BypassMinFeeMsgTypes); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateMaxTotalBypassMinFeeMsgGasUsage(p.MaxTotalBypassMinFeeMsgGasUsage)\n}", "func (msg MsgSetAccData) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Account Name cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimEarnReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgAddSupply) ValidateBasic() error {\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (msg MsgBuyName) ValidateBasic() sdk.Error {\n\tif msg.Buyer.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Buyer.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.Bid.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Bids must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimHardReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg TinyTokenIssueMsg) ValidateBasic() error {\n\n\tif msg.From == nil {\n\t\treturn errors.New(\"sender address cannot be empty\")\n\t}\n\n\tif err := validateIssueMsgMiniTokenSymbol(msg.Symbol); err != nil {\n\t\treturn fmt.Errorf(\"Invalid symbol %v\", msg.Symbol)\n\t}\n\n\tif len(msg.Name) == 0 || len(msg.Name) > MaxMiniTokenNameLength {\n\t\treturn fmt.Errorf(\"token name should have 1 ~ %v characters\", MaxMiniTokenNameLength)\n\t}\n\n\tif len(msg.TokenURI) > MaxTokenURILength {\n\t\treturn fmt.Errorf(\"token seturi should not exceed %v characters\", MaxTokenURILength)\n\t}\n\n\t//if msg.MaxTotalSupply < MiniTokenMinTotalSupply || msg.MaxTotalSupply > MiniTokenMaxTotalSupplyUpperBound {\n\t//\treturn fmt.Errorf(\"max total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, MiniTokenMaxTotalSupplyUpperBound)\n\t//}\n\t//\n\t//if msg.TotalSupply < MiniTokenMinTotalSupply || msg.TotalSupply > msg.MaxTotalSupply {\n\t//\treturn fmt.Errorf(\"total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, msg.MaxTotalSupply)\n\t//}\n\n\treturn nil\n}", "func (msg MsgIssueTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\tif msg.Receiver.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"receiver address cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"create is empty\")\n\t}\n\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution is empty\")\n\t}\n\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution hash is empty\")\n\t}\n\n\tsolutionHash := sha256.Sum256([]byte(msg.Solution))\n\tsolutionHashString := hex.EncodeToString(solutionHash[:])\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\n\treturn nil\n}", "func (msg MsgDeleteShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\treturn nil\n}", "func (msg MsgPostPrice) ValidateBasic() error {\n\tif msg.From.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif strings.TrimSpace(msg.MarketID) == \"\" {\n\t\treturn errors.New(\"market id cannot be blank\")\n\t}\n\tif msg.Price.IsNegative() {\n\t\treturn fmt.Errorf(\"price cannot be negative: %s\", msg.Price.String())\n\t}\n\tif msg.Expiry.IsZero() {\n\t\treturn errors.New(\"must set an expiration time\")\n\t}\n\treturn nil\n}", "func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool {\n\tswitch {\n\tcase len(br.Name) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"name required but not specified\")\n\t\treturn false\n\n\tcase len(br.Password) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"password required but not specified\")\n\t\treturn false\n\n\tcase len(br.ChainID) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"chainID required but not specified\")\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (msg MsgClaimSavingsReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgSetPoolData) ValidateBasic() sdk.Error {\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool Ticker cannot be empty\")\n\t}\n\tif len(msg.TokenName) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool TokenName cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSetShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\tif msg.Rate.GTE(sdk.NewDec(1)) || msg.Rate.LTE(sdk.NewDec(0)) {\n\t\treturn sdk.ErrUnknownRequest(\"Rate can not great than 1 or less than 0!\")\n\t}\n\treturn nil\n}", "func (msg MsgCompletePurchaseOrder) ValidateBasic() sdkerrors {\r\n\tif msg.PurchaseOrderID == 0 {\r\n\t\treturn ErrUnknownPurchaseOrder(msg.PurchaseOrderID)\r\n\t}\r\n\tif len(msg.Counterparty) == 0 {\r\n\t\treturn sdk.ErrInvalidAddress(\"Invalid address: \" + msg.Counterparty.String())\r\n\t}\r\n\r\n\tif msg.PurchaseOrderStatus != \"COMPLETED\" {\r\n\t\treturn Error(\"The Purchase Order status must be Completed.\")\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (tx *CreateLegalEntityTx) ValidateBasic() abci.Result {\n\tif len(tx.Address) != 20 {\n\t\treturn abci.ErrBaseInvalidInput.AppendLog(\"Invalid address length\")\n\t}\n\tif tx.Signature == nil {\n\t\treturn abci.ErrBaseInvalidSignature.AppendLog(\"The transaction must be signed\")\n\t}\n\tif _, err := uuid.FromString(tx.EntityID); err != nil {\n\t\treturn abci.ErrBaseInvalidInput.AppendLog(common.Fmt(\"Invalid entity_id: %s\", err))\n\t}\n\tif _, err := uuid.FromString(tx.ParentID); err != nil {\n\t\treturn abci.ErrBaseInvalidInput.AppendLog(common.Fmt(\"Invalid parent_id: %s\", err))\n\t}\n\n\tif !IsValidEntityType(tx.Type) {\n\t\treturn abci.ErrBaseInvalidInput.AppendLog(common.Fmt(\"Invalid Type: %s\", tx.Type))\n\t}\n\treturn abci.OK\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionScavengerHash can't be empty\")\n\t}\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionHash can't be empty\")\n\t}\n\n\tvar solutionHash = sha256.Sum256([]byte(msg.Solution))\n\tvar solutionHashString = hex.EncodeToString(solutionHash[:])\n\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func (in Input) ValidateBasic() sdk.Error {\n\tif len(in.Address) == 0 {\n\t\treturn sdk.ErrInvalidAddress(in.Address.String())\n\t}\n\tif !in.Coins.IsValid() {\n\t\treturn sdk.ErrInvalidCoins(in.Coins.String())\n\t}\n\tif !in.Coins.IsAllPositive() {\n\t\treturn sdk.ErrInvalidCoins(in.Coins.String())\n\t}\n\treturn nil\n}", "func (msg MsgClaimSwapReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c MsgExecLegacyContent) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(c.Authority)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (msg MsgCreatePurchaseOrder) ValidateBasic() sdkerrors {\r\n\r\n\tif len(msg.PurchaseOrderID) == 0 {\r\n\t\treturn ErrInvalidPurchaseOrderID(msg.PurchaseOrderID)\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (m Params) ValidateBasic() error {\n\tif err := validateNominees(m.Nominees); err != nil {\n\t\treturn err\n\t}\n\tif err := validatePostPrice(m.PostPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (msg MsgSetOracleScriptID) ValidateBasic() error {\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\treturn nil\n}", "func (c Checkpoint) ValidateBasic(chainID string) error {\n\treturn nil\n}", "func (p Params) ValidateBasic() error {\n\tif p.CommunityTax.IsNegative() || p.CommunityTax.GT(sdk.OneDec()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"community tax should non-negative and less than one: %s\", p.CommunityTax,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgCreateCookbook) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\tif len(msg.Name) < 8 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the name of the cookbook should have more than 8 characters\")\n\t}\n\n\tif len(msg.Description) < 20 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the description should have more than 20 characters\")\n\t}\n\n\tif err := msg.SupportEmail.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\tif err := msg.Level.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\tif err := msg.Version.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif len(msg.Moniker) < MinMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot be less than %d characters\", MinMonikerLength))\n\t}\n\n\tif len(msg.Moniker) > MaxMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot exceed %d characters\", MaxMonikerLength))\n\t}\n\n\tif msg.Name != nil {\n\t\tif len(*msg.Name) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Name) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Surname != nil {\n\t\tif msg.Surname != nil && len(*msg.Surname) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Surname) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Bio != nil && len(*msg.Bio) > MaxBioLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile biography cannot exceed %d characters\", MaxBioLength))\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseGroup) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\tif err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t}\n\treturn nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\tif err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t}\n\treturn nil\n}", "func (msg MsgBuyAsset) ValidateBasic() error {\n\taddr, err := sdk.AccAddressFromBech32(msg.Buyer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif addr.Empty() {\n\t\treturn ErrEmptyAddr\n\t}\n\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (p *UpdateKeyNodesProposal) ValidateBasic() sdk.Error {\n\terr := govtypes.ValidateAbstract(DefaultCodespace, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(p.AddKeyNodes) == 0 && len(p.RemoveKeyNodes) == 0 {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\texists := make(map[string]bool)\n\tfor _, cu := range p.AddKeyNodes {\n\t\tif !cu.IsValidAddr() {\n\t\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t\t}\n\t\tif exists[cu.String()] {\n\t\t\treturn ErrDuplicatedValidatorAddr(DefaultCodespace)\n\t\t}\n\t\texists[cu.String()] = true\n\t}\n\tfor _, cu := range p.RemoveKeyNodes {\n\t\tif !cu.IsValidAddr() {\n\t\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t\t}\n\t\tif exists[cu.String()] {\n\t\t\treturn ErrDuplicatedValidatorAddr(DefaultCodespace)\n\t\t}\n\t\texists[cu.String()] = true\n\t}\n\treturn nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\t// if err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t// \treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t// }\n\treturn nil\n}", "func (lb LightBlock) ValidateBasic(chainID string) error {\n\tif lb.SignedHeader == nil {\n\t\treturn errors.New(\"missing signed header\")\n\t}\n\tif lb.ValidatorSet == nil {\n\t\treturn errors.New(\"missing validator set\")\n\t}\n\n\tif err := lb.SignedHeader.ValidateBasic(chainID); err != nil {\n\t\treturn fmt.Errorf(\"invalid signed header: %w\", err)\n\t}\n\tif err := lb.ValidatorSet.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid validator set: %w\", err)\n\t}\n\n\t// make sure the validator set is consistent with the header\n\tif valSetHash := lb.ValidatorSet.Hash(); !bytes.Equal(lb.SignedHeader.ValidatorsHash, valSetHash) {\n\t\treturn fmt.Errorf(\"expected validator hash of header to match validator set hash (%X != %X)\",\n\t\t\tlb.SignedHeader.ValidatorsHash, valSetHash,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (stateID StateID) ValidateBasic() error {\n\t// LastAppHash can be empty in case of genesis block.\n\tif err := ValidateAppHash(stateID.LastAppHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong app Hash\")\n\t}\n\treturn nil\n}", "func (msg MsgCreateBid) ValidateBasic() error {\n\tif err := msg.Order.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sdk.VerifyAddressFormat(msg.Provider); err != nil {\n\t\treturn ErrEmptyProvider\n\t}\n\n\tif msg.Provider.Equals(msg.Order.Owner) {\n\t\treturn ErrSameAccount\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn nil\n}", "func (p IbcAgreementPacketData) ValidateBasic() error {\r\n\r\n\t// TODO: Validate the packet data\r\n\r\n\treturn nil\r\n}", "func (m *ProposalResetWholeValidatorRank) ValidateBasic() error {\n\treturn nil\n}", "func (cs ConsensusState) ValidateBasic() error {\n\tif cs.Timestamp == 0 {\n\t\treturn sdkerrors.Wrap(clienttypes.ErrInvalidConsensus, \"timestamp cannot be zero Unix time\")\n\t}\n\treturn nil\n}", "func (msg MsgUpdateDeployment) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif len(msg.Version) == 0 {\n\t\treturn ErrEmptyVersion\n\t}\n\n\treturn nil\n}", "func (a AccAddresses) ValidateBasic() error {\n\tindex := make(map[string]struct{}, len(a))\n\tfor i := range a {\n\t\taccAddr := a[i]\n\t\taddr := string(accAddr)\n\t\tif _, exists := index[addr]; exists {\n\t\t\treturn sdkerrors.Wrapf(errors.ErrDuplicate, \"address: %s\", accAddr.String())\n\t\t}\n\t\tindex[addr] = struct{}{}\n\t}\n\treturn nil\n}", "func (p IbcDataInfoPacketData) ValidateBasic() error {\n\n\t// TODO: Validate the packet data\n\n\treturn nil\n}", "func (m *MsgCreateBatch) ValidateBasic() error {\n\tif _, err := sdk.AccAddressFromBech32(m.Issuer); err != nil {\n\t\treturn sdkerrors.ErrInvalidAddress.Wrapf(\"issuer: %s\", err)\n\t}\n\n\tif err := base.ValidateProjectID(m.ProjectId); err != nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"project id: %s\", err)\n\t}\n\n\tif len(m.Issuance) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"issuance cannot be empty\")\n\t}\n\n\tfor i, issuance := range m.Issuance {\n\t\tif err := issuance.Validate(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"issuance[%d]\", i)\n\t\t}\n\t}\n\n\t// we allow metadata to be empty for class and project but not for batch\n\tif m.Metadata == \"\" {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"metadata cannot be empty\")\n\t}\n\n\tif len(m.Metadata) > base.MaxMetadataLength {\n\t\treturn ecocredit.ErrMaxLimit.Wrapf(\"metadata: max length %d\", base.MaxMetadataLength)\n\t}\n\n\tif m.StartDate == nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"start date cannot be empty\")\n\t}\n\n\tif m.EndDate == nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"end date cannot be empty\")\n\t}\n\n\tif m.StartDate.After(*m.EndDate) {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"start date cannot be after end date\")\n\t}\n\n\t// origin tx is not required when creating a credit batch\n\tif m.OriginTx != nil {\n\t\tif err := m.OriginTx.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}" ]
[ "0.73804784", "0.73113424", "0.7261712", "0.72282255", "0.7100147", "0.7098479", "0.6897681", "0.68841374", "0.6851666", "0.6757597", "0.67477596", "0.67466974", "0.66906", "0.66889745", "0.66073847", "0.6564321", "0.6556893", "0.65362024", "0.65199435", "0.65130174", "0.6489039", "0.6441457", "0.64386976", "0.64386976", "0.64378107", "0.6414984", "0.63827133", "0.6326593", "0.6279694", "0.62740046", "0.6268648", "0.62545526", "0.62432253", "0.6240392", "0.62299085", "0.6225045", "0.61805254", "0.61313444", "0.6128315", "0.6126087", "0.6117496", "0.6105636", "0.6095098", "0.6082256", "0.6082256", "0.607545", "0.6058971", "0.6051861", "0.6047341", "0.603822", "0.60069543", "0.6004504", "0.59993714", "0.59863985", "0.5984978", "0.5972738", "0.59699345", "0.59626114", "0.59546113", "0.5953866", "0.594357", "0.5934497", "0.5932704", "0.59264135", "0.5922185", "0.5895859", "0.5873735", "0.58611274", "0.5859616", "0.58354855", "0.5824987", "0.5822505", "0.58209145", "0.58192575", "0.5816296", "0.5791513", "0.57800776", "0.5743795", "0.5667698", "0.56674016", "0.5643152", "0.55900633", "0.5551053", "0.5551053", "0.5550227", "0.5546391", "0.5484556", "0.5435575", "0.5427007", "0.5427007", "0.5419618", "0.5404185", "0.53839934", "0.53679216", "0.53586286", "0.53469753", "0.53103447", "0.5309782", "0.53060853", "0.52841765" ]
0.8412553
0
GetSigners returns an array containing the signer's account address extracted from the 'From' field of the MsgStartRequest.
func (m *MsgStartRequest) GetSigners() []sdk.AccAddress { from, err := sdk.AccAddressFromBech32(m.From) if err != nil { panic(err) } return []sdk.AccAddress{from} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MsgEndRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgCreateRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (m *MsgSubscribeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(msg.FromAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgUpdateDetailsRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.NodeAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgClaim) GetSigners() []sdk.Address {\n\treturn []sdk.Address{sdk.Address(msg.FromAddress)}\n}", "func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgEthermint) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.From}\n}", "func (m *MsgUpdateStatusRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgBurn) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg TinyTokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} }", "func (msg MsgAddRecord) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Org}\n}", "func (msg MsgFund) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (m *MsgLinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgOrderRetry) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.From)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCollectFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgBlockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgRagnarok) GetSigners() []cosmos.AccAddress {\n\treturn []cosmos.AccAddress{msg.Signer}\n}", "func (msg MsgLock) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg MsgAddSupply) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCreateCookbook) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCollectSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCreatePDV) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgStake) GetSigners() []sdk.AccAddress {\n\taddrs := []sdk.AccAddress{sdk.AccAddress(msg.Address)}\n\treturn addrs\n}", "func (msg MsgCollectWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgProof) GetSigners() []sdk.Address {\n\tpk, err := crypto.NewPublicKey(msg.Leaf.ServicerPubKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"an error occured getting the signer for the proof message, %v\", err))\n\t}\n\treturn []sdk.Address{sdk.Address(pk.Address())}\n}", "func (msg MsgRedeemTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (m *MsgUnlinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgClaimUSDXMintingReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgHeartbeat) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCreateIndex) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgClaimSavingsReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgUpdateRecipe) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCompletePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (tx StdTx) GetSigners() []AccAddress {\n\tseen := map[string]bool{}\n\tvar signers []AccAddress\n\tfor _, msg := range tx.GetMsgs() {\n\t\tfor _, addr := range msg.GetSigners() {\n\t\t\tif !seen[addr.String()] {\n\t\t\t\tsigners = append(signers, addr)\n\t\t\t\tseen[addr.String()] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn signers\n}", "func (msg MsgFulfillTrade) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgClaimEarnReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgSetShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (msg MsgCreatePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Counterparty)}\r\n}", "func (msg MsgAddMember) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.FromCU}\n}", "func (msg MsgCreateSession) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgDeleteName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgCreatePermanentLockedAccount) GetSigners() []sdk.AccAddress {\n\tfrom, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgAddAdminAccount) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (m *MsgCreateBatch) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(m.Issuer)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgSetMoniker) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCreateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg CreateZoneMsg) GetSigners() []sdk.AccAddress {\n\ttxHash := utils.ToEthSignedMessageHash(msg.TxHash())\n\n\tpubKey, err := crypto.SigToPub(txHash, msg.Signature[:])\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn []sdk.AccAddress{sdk.AccAddress(crypto.PubkeyToAddress(*pubKey).Bytes())}\n\n}", "func (msg MsgIssueTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgSysTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgDeleteShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\tprovider, err := sdk.AccAddressFromBech32(msg.Provider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{provider}\n}", "func (msg MsgOpcuAssetTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCancelPurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgConfirmedDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.From}\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgAuctionName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgBuyAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Buyer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgSetOracleScriptID) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgWithdrawal) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgWithdrawalWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgConfirmSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgConfirmBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgClaimHardReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgUnblockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgSysTransferFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgChangeBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgSetAccData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetPauseStatus) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgSysTransferWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgChangeSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgWithdrawalFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgOpcuAssetTransferWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCreateTable) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgFinancePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgAuctionReveal) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgSysTransferSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgWithdrawalSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSellAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Seller)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgSwap) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgUpdateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgOpcuAssetTransferFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgClaimSwapReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgCancelWithdrawal) GetSigners() []sdk.CUAddress {\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgOpcuAssetTransferSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSetPoolData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetKarma) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgLeave) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Signer}\n}", "func (msg MsgSetStakeData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}" ]
[ "0.8129325", "0.80024564", "0.797764", "0.7540568", "0.75166833", "0.74983877", "0.73720056", "0.7351297", "0.73304814", "0.72582644", "0.7247849", "0.72333807", "0.7205962", "0.7187367", "0.71820444", "0.71338636", "0.7123505", "0.71225077", "0.7093302", "0.7067477", "0.7062478", "0.7053064", "0.70380735", "0.7024768", "0.70172864", "0.6927862", "0.6927862", "0.69227535", "0.691544", "0.69126093", "0.6899463", "0.68759185", "0.6861562", "0.6857182", "0.68558365", "0.6855191", "0.6850819", "0.6828883", "0.6826577", "0.68252236", "0.6825109", "0.68216383", "0.6807812", "0.68071884", "0.67769504", "0.6767829", "0.6766285", "0.6766285", "0.6765269", "0.67413783", "0.67393106", "0.67369854", "0.6712841", "0.6701402", "0.6692196", "0.6677436", "0.66637146", "0.66598016", "0.66545177", "0.6651014", "0.6650484", "0.66415155", "0.66415155", "0.66359305", "0.6635552", "0.66331196", "0.66302556", "0.6615836", "0.6614257", "0.6614257", "0.66005546", "0.65971774", "0.6584478", "0.65832496", "0.6570836", "0.65654975", "0.6564779", "0.6556213", "0.6541165", "0.6526022", "0.6524471", "0.65231097", "0.6520923", "0.65199673", "0.65165234", "0.6514227", "0.6494868", "0.6485596", "0.64596075", "0.645687", "0.6419441", "0.6419441", "0.64185417", "0.64171904", "0.64068365", "0.639082", "0.6389059", "0.6370639", "0.635009", "0.6330497" ]
0.8656046
0
NewMsgUpdateDetailsRequest creates a new MsgUpdateDetailsRequest instance with the given parameters.
func NewMsgUpdateDetailsRequest(from hubtypes.NodeAddress, proof Proof, signature []byte) *MsgUpdateDetailsRequest { return &MsgUpdateDetailsRequest{ From: from.String(), Proof: proof, Signature: signature, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMsgUpdate(addr sdk.AccAddress, data PersonalData) MsgUpdate {\n\treturn MsgUpdate{Address: addr, Data: data}\n}", "func NewMsgUpdateStatusRequest(from hubtypes.ProvAddress, id uint64, status hubtypes.Status) *MsgUpdateStatusRequest {\n\treturn &MsgUpdateStatusRequest{\n\t\tFrom: from.String(),\n\t\tID: id,\n\t\tStatus: status,\n\t}\n}", "func NewMsgEndRequest(from sdk.AccAddress, id uint64, rating uint64) *MsgEndRequest {\n\treturn &MsgEndRequest{\n\t\tFrom: from.String(),\n\t\tID: id,\n\t\tRating: rating,\n\t}\n}", "func NewMsgCreateRequest(from hubtypes.ProvAddress, duration time.Duration, gigabytes int64, prices sdk.Coins) *MsgCreateRequest {\n\treturn &MsgCreateRequest{\n\t\tFrom: from.String(),\n\t\tDuration: duration,\n\t\tGigabytes: gigabytes,\n\t\tPrices: prices,\n\t}\n}", "func NewReqDetails(key string, details interface{}, msg string) E {\n\treturn newRequest(errmap{key: details}, msg, 1)\n}", "func (x *fastReflection_MsgUpdateParams) New() protoreflect.Message {\n\treturn new(fastReflection_MsgUpdateParams)\n}", "func CreateUpdateMessageAppRequest() (request *UpdateMessageAppRequest) {\n\trequest = &UpdateMessageAppRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"live\", \"2016-11-01\", \"UpdateMessageApp\", \"live\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func NewCreateanewSMSRequest(server string, body CreateanewSMSJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSMSRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewUpdateRequest(payload *roles.Role) *rolespb.UpdateRequest {\n\tmessage := &rolespb.UpdateRequest{\n\t\tName: payload.Name,\n\t}\n\tif payload.Description != nil {\n\t\tmessage.Description = *payload.Description\n\t}\n\treturn message\n}", "func (k *msgServer) MsgUpdateDetails(c context.Context, msg *types.MsgUpdateDetailsRequest) (*types.MsgUpdateDetailsResponse, error) {\n\t// Unwrap the SDK context from the standard context.\n\tctx := sdk.UnwrapSDKContext(c)\n\n\t// Get the session from the store using the provided session ID.\n\tsession, found := k.GetSession(ctx, msg.Proof.ID)\n\tif !found {\n\t\t// If the session is not found, return an error indicating that the session was not found.\n\t\treturn nil, types.NewErrorSessionNotFound(msg.Proof.ID)\n\t}\n\n\t// Check if the session status is 'Inactive' as only active or inactive-pending sessions can be updated.\n\tif session.Status.Equal(hubtypes.StatusInactive) {\n\t\t// If the session status is 'Inactive', return an error indicating that the session status is invalid for updating details.\n\t\treturn nil, types.NewErrorInvalidSessionStatus(session.ID, session.Status)\n\t}\n\n\t// Ensure that the message sender (msg.From) is authorized to update the session details.\n\tif msg.From != session.NodeAddress {\n\t\t// If the message sender is not authorized, return an error indicating unauthorized access.\n\t\treturn nil, types.NewErrorUnauthorized(msg.From)\n\t}\n\n\t// If proof verification is enabled, verify the signature of the message using the account address associated with the session.\n\tif k.ProofVerificationEnabled(ctx) {\n\t\tif err := k.VerifySignature(ctx, session.GetAddress(), msg.Proof, msg.Signature); err != nil {\n\t\t\t// If the signature verification fails, return an error indicating an invalid signature.\n\t\t\treturn nil, types.NewErrorInvalidSignature(msg.Signature)\n\t\t}\n\t}\n\n\t// If the session status is 'Active', update the session's InactiveAt value based on the status change delay.\n\tif session.Status.Equal(hubtypes.StatusActive) {\n\t\t// Get the status change delay from the Store.\n\t\tstatusChangeDelay := k.StatusChangeDelay(ctx)\n\n\t\t// Delete the session's entry from the InactiveAt index before updating the InactiveAt value.\n\t\tk.DeleteSessionForInactiveAt(ctx, session.InactiveAt, session.ID)\n\n\t\t// Calculate the new InactiveAt value by adding the status change delay to the current block time.\n\t\tsession.InactiveAt = ctx.BlockTime().Add(statusChangeDelay)\n\n\t\t// Update the session entry in the InactiveAt index with the new InactiveAt value.\n\t\tk.SetSessionForInactiveAt(ctx, session.InactiveAt, session.ID)\n\t}\n\n\t// Update the session's bandwidth and duration using the details from the provided proof.\n\tsession.Bandwidth = msg.Proof.Bandwidth\n\tsession.Duration = msg.Proof.Duration\n\n\t// Save the updated session to the store.\n\tk.SetSession(ctx, session)\n\n\t// Emit an event to notify that the session details have been updated.\n\tctx.EventManager().EmitTypedEvent(\n\t\t&types.EventUpdateDetails{\n\t\t\tAddress: session.Address,\n\t\t\tNodeAddress: session.NodeAddress,\n\t\t\tID: session.ID,\n\t\t\tPlanID: 0,\n\t\t\tSubscriptionID: session.SubscriptionID,\n\t\t},\n\t)\n\n\t// Return an empty MsgUpdateDetailsResponse, indicating the successful completion of the message.\n\treturn &types.MsgUpdateDetailsResponse{}, nil\n}", "func NewUpdate(zone string, class uint16) *Msg {\n\tu := new(Msg)\n\tu.MsgHdr.Response = false\n\tu.MsgHdr.Opcode = OpcodeUpdate\n\tu.Compress = false // Seems BIND9 at least cannot handle compressed update pkgs\n\tu.Question = make([]Question, 1)\n\tu.Question[0] = Question{zone, TypeSOA, class}\n\treturn u\n}", "func NewMsgUpdateRecipe(recipeName, cookbookID, id, description string,\n\tcoinInputs types.CoinInputList,\n\titemInputs types.ItemInputList,\n\tentries types.EntriesList,\n\toutputs types.WeightedOutputsList,\n\tsender sdk.AccAddress) MsgUpdateRecipe {\n\treturn MsgUpdateRecipe{\n\t\tName: recipeName,\n\t\tID: id,\n\t\tCookbookID: cookbookID,\n\t\tDescription: description,\n\t\tCoinInputs: coinInputs,\n\t\tItemInputs: itemInputs,\n\t\tEntries: entries,\n\t\tOutputs: outputs,\n\t\tBlockInterval: 0,\n\t\tSender: sender,\n\t}\n}", "func New(mdreqid string, subscriptionrequesttype string, marketdepth int, nomdentrytypes []NoMDEntryTypes, norelatedsym []NoRelatedSym) *Message {\n\tvar m Message\n\tm.SetMDReqID(mdreqid)\n\tm.SetSubscriptionRequestType(subscriptionrequesttype)\n\tm.SetMarketDepth(marketdepth)\n\tm.SetNoMDEntryTypes(nomdentrytypes)\n\tm.SetNoRelatedSym(norelatedsym)\n\treturn &m\n}", "func NewEventMessageDetail()(*EventMessageDetail) {\n m := &EventMessageDetail{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func New(securityreqid string, securityrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityRequestType(securityrequesttype)\n\treturn &m\n}", "func New(securityreqid string, securitylistrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityListRequestType(securitylistrequesttype)\n\treturn &m\n}", "func UpdateMsg(update Update) Message {\n\treturn &messageStruct{\n\t\tupdate: &update,\n\t}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) New() protoreflect.Message {\n\treturn new(fastReflection_MsgUpdateParamsResponse)\n}", "func New(rfqreqid string, norelatedsym []NoRelatedSym) *Message {\n\tvar m Message\n\tm.SetRFQReqID(rfqreqid)\n\tm.SetNoRelatedSym(norelatedsym)\n\treturn &m\n}", "func NewMsg(typ string) Msg {\n\treturn Msg{\n\t\tID: uuid.New().String(),\n\t\tType: typ,\n\t\tTimestamp: time.Now().UTC(),\n\t}\n}", "func NewMessage(req *http.Request) (IMessage, error) {\n\tvar msg Message\n\terr := json.NewDecoder(req.Body).Decode(&msg)\n\treturn &msg, err\n}", "func NewReqInfo(userip net.IP, secret string) *Message {\n\tmsg := newMessage(ReqInfo, userip, newSerialNo(), 0)\n\tmsg.AuthBy(secret)\n\treturn msg\n}", "func newMsg(t string) ([]byte, error) {\n\tswitch t {\n\tcase \"version\":\n\t\treturn newVersion()\n\tcase \"verack\":\n\t\treturn newVerack()\n\tcase \"getheaders\":\n\t\treturn newHeadersReq()\n\tcase \"getaddr\":\n\t\treturn newGetAddr()\n\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}", "func NewMsgSpec(subjectName string, newMsg func() interface{}) (MsgSpec, error) {\n\tif !SubjectNameRegexp.MatchString(subjectName) {\n\t\treturn nil, fmt.Errorf(\"SubjectName format invalid\")\n\t}\n\n\tif newMsg == nil {\n\t\treturn nil, fmt.Errorf(\"NewMsg is empty\")\n\t}\n\tmsgValue := newMsg()\n\tif msgValue == nil {\n\t\treturn nil, fmt.Errorf(\"NewMsg() returns nil\")\n\t}\n\tmsgType := reflect.TypeOf(msgValue)\n\tif msgType.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"NewMsg() returns %s which is not a pointer\", msgType.String())\n\t}\n\n\treturn &msgSpec{\n\t\tsubjectName: subjectName,\n\t\tnewMsg: newMsg,\n\t\tmsgType: msgType,\n\t\tmsgValue: msgValue,\n\t}, nil\n}", "func NewUpdateClinicUserDetailsRequest(server string, userId UserId, body UpdateClinicUserDetailsJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdateClinicUserDetailsRequestWithBody(server, userId, \"application/json\", bodyReader)\n}", "func newRequest(ctx context.Context, msg interface{}) *request {\n\treturn &request{\n\t\tctx: ctx,\n\t\tmsg: msg,\n\t\tfailure: make(chan error, 1),\n\t\tresponse: make(chan *Delivery, 1),\n\t}\n}", "func CreateSaveReceiverDetailRequest() (request *SaveReceiverDetailRequest) {\r\n\trequest = &SaveReceiverDetailRequest{\r\n\t\tRpcRequest: &requests.RpcRequest{},\r\n\t}\r\n\trequest.InitWithApiInfo(\"Dm\", \"2015-11-23\", \"SaveReceiverDetail\", \"\", \"\")\r\n\treturn\r\n}", "func NewMsgSubscribeRequest(from sdk.AccAddress, id uint64, denom string) *MsgSubscribeRequest {\n\treturn &MsgSubscribeRequest{\n\t\tFrom: from.String(),\n\t\tID: id,\n\t\tDenom: denom,\n\t}\n}", "func NewRequest(id string, method string, params interface{}) *Request {\n\tbuffer, err := json.Marshal(params)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Request{JsonRPC: \"2.0\", Id: id, Method: method, Params: buffer}\n}", "func NewCreateanewSMSRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/sms\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func newIDRequestMessage(sender ID, receiver ID) (*Message, error) {\n\t// Create the payload\n\tidr, err := newidRequest(sender, receiver)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"newIDRequestMessage: error while creating new IDRequest message\")\n\t}\n\n\t// Marshal it\n\tbin, err := idr.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"newIDRequestMessage: error when marshalling id request\")\n\t}\n\n\treturn NewMessage(identification, bytes.NewReader(bin))\n}", "func New(side string, transacttime time.Time, orderqtydata orderqtydata.OrderQtyData, ordtype string) *Message {\n\tvar m Message\n\tm.SetSide(side)\n\tm.SetTransactTime(transacttime)\n\tm.SetOrderQtyData(orderqtydata)\n\tm.SetOrdType(ordtype)\n\treturn &m\n}", "func (rm *resourceManager) newUpdateRequestPayload(\n\tctx context.Context,\n\tr *resource,\n) (*svcsdk.UpdateModelPackageInput, error) {\n\tres := &svcsdk.UpdateModelPackageInput{}\n\n\tif r.ko.Spec.ApprovalDescription != nil {\n\t\tres.SetApprovalDescription(*r.ko.Spec.ApprovalDescription)\n\t}\n\tif r.ko.Spec.ModelApprovalStatus != nil {\n\t\tres.SetModelApprovalStatus(*r.ko.Spec.ModelApprovalStatus)\n\t}\n\tif r.ko.Status.ACKResourceMetadata != nil && r.ko.Status.ACKResourceMetadata.ARN != nil {\n\t\tres.SetModelPackageArn(string(*r.ko.Status.ACKResourceMetadata.ARN))\n\t} else {\n\t\tres.SetModelPackageArn(rm.ARNFromName(*r.ko.Spec.ModelPackageName))\n\t}\n\n\treturn res, nil\n}", "func NewMsgMint(symbol string, amount int64, owner sdk.AccAddress) MsgMint {\n\treturn MsgMint{\n\t\tSymbol: symbol,\n\t\tAmount: amount,\n\t\tOwner: owner,\n\t}\n}", "func BuildPNRDetailsRequest(c *srvc.SessionConf, binsec string, body PassengerDetailBody) PNRDetailsRequest {\n\treturn PNRDetailsRequest{\n\t\tEnvelope: srvc.CreateEnvelope(),\n\t\tHeader: srvc.SessionHeader{\n\t\t\tMessageHeader: srvc.MessageHeader{\n\t\t\t\tMustUnderstand: srvc.SabreMustUnderstand,\n\t\t\t\tEbVersion: srvc.SabreEBVersion,\n\t\t\t\tFrom: srvc.FromElem{\n\t\t\t\t\tPartyID: srvc.CreatePartyID(c.From, srvc.PartyIDTypeURN),\n\t\t\t\t},\n\t\t\t\tTo: srvc.ToElem{\n\t\t\t\t\tPartyID: srvc.CreatePartyID(srvc.SabreToBase, srvc.PartyIDTypeURN),\n\t\t\t\t},\n\t\t\t\tCPAID: c.PCC,\n\t\t\t\tConversationID: c.Convid,\n\t\t\t\tService: srvc.ServiceElem{Value: \"PassengerDetailsRQ\", Type: \"sabreXML\"},\n\t\t\t\tAction: \"PassengerDetailsRQ\",\n\t\t\t\tMessageData: srvc.MessageDataElem{\n\t\t\t\t\tMessageID: srvc.GenerateMessageID(),\n\t\t\t\t\tTimestamp: srvc.SabreTimeNowFmt(),\n\t\t\t\t},\n\t\t\t},\n\t\t\tSecurity: srvc.Security{\n\t\t\t\tXMLNSWsseBase: srvc.BaseWsse,\n\t\t\t\tXMLNSWsu: srvc.BaseWsuNameSpace,\n\t\t\t\tBinarySecurityToken: binsec,\n\t\t\t},\n\t\t},\n\t\tBody: body,\n\t}\n}", "func (s SCIONDMsg) NewServiceInfoRequest() (ServiceInfoRequest, error) {\n\ts.Struct.SetUint16(8, 8)\n\tss, err := NewServiceInfoRequest(s.Struct.Segment())\n\tif err != nil {\n\t\treturn ServiceInfoRequest{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func NewCreateCollectInfoRequestWithoutParam() *CreateCollectInfoRequest {\n\n return &CreateCollectInfoRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/logtopics/{logtopicUID}/collectinfos\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func CreateUpdateTicketRequest() (request *UpdateTicketRequest) {\n\trequest = &UpdateTicketRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"scsp\", \"2020-07-02\", \"UpdateTicket\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func New(orderid string, execid int, exectranstype string, ordstatus string, symbol string, side string, orderqty int, lastshares int, lastpx float64, cumqty int, avgpx float64) *Message {\n\tvar m Message\n\tm.SetOrderID(orderid)\n\tm.SetExecID(execid)\n\tm.SetExecTransType(exectranstype)\n\tm.SetOrdStatus(ordstatus)\n\tm.SetSymbol(symbol)\n\tm.SetSide(side)\n\tm.SetOrderQty(orderqty)\n\tm.SetLastShares(lastshares)\n\tm.SetLastPx(lastpx)\n\tm.SetCumQty(cumqty)\n\tm.SetAvgPx(avgpx)\n\treturn &m\n}", "func (bt *BlipTester) newRequest() *blip.Message {\n\tmsg := blip.NewRequest()\n\tbt.addCollectionProperty(msg)\n\treturn msg\n}", "func NewCreateanewSystemContactRequest(server string, body CreateanewSystemContactJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSystemContactRequestWithBody(server, \"application/json\", bodyReader)\n}", "func New(clientbidid string, bidrequesttranstype string, totnorelatedsym int, bidtype int, bidtradetype string, basispxtype string) *Message {\n\tvar m Message\n\tm.SetClientBidID(clientbidid)\n\tm.SetBidRequestTransType(bidrequesttranstype)\n\tm.SetTotNoRelatedSym(totnorelatedsym)\n\tm.SetBidType(bidtype)\n\tm.SetBidTradeType(bidtradetype)\n\tm.SetBasisPxType(basispxtype)\n\treturn &m\n}", "func New(orderid string, execackstatus string, execid string, instrument instrument.Instrument, side string, orderqtydata orderqtydata.OrderQtyData) *Message {\n\tvar m Message\n\tm.SetOrderID(orderid)\n\tm.SetExecAckStatus(execackstatus)\n\tm.SetExecID(execid)\n\tm.SetInstrument(instrument)\n\tm.SetSide(side)\n\tm.SetOrderQtyData(orderqtydata)\n\treturn &m\n}", "func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *HsmProvidersService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewAppStoreReviewDetailsUpdateInstanceRequest(server string, id string, body AppStoreReviewDetailsUpdateInstanceJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewAppStoreReviewDetailsUpdateInstanceRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewMsgExtended(command string, payload []byte) *MsgExtended {\n\treturn &MsgExtended{\n\t\tExtCommand: command,\n\t\tLength: uint64(len(payload)),\n\t\tPayload: payload,\n\t}\n}", "func (c *InputService21ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewInfoMessage(text string) InfoMessage {\n\treturn InfoMessage{NewMessage(text)}\n}", "func NewUpdatePrivateNetworkRequest(server string, id string, body UpdatePrivateNetworkJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdatePrivateNetworkRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewMsg(channel string, pk string, kind int64, options ...func(*Msg) error) (*Msg, error) {\n\tmsg := &Msg{ChannelPK: channel, AuthorPK: pk, Kind: kind, CreatedAt: time.Now().Unix()}\n\tmsg.Data = make(map[string]interface{})\n\tfor _, opt := range options {\n\t\terr := opt(msg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif msg.PK == \"\" {\n\t\tid, err := ksuid.NewRandomWithTime(time.Unix(msg.CreatedAt, 0))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmsg.PK = fmt.Sprintf(\"%s%s\", MsgKeyPrefix, id.String())\n\t\tmsg.CreatedAt = id.Time().Unix() //there is a bit difference from origin, we need this to be stored\n\t}\n\n\tmsg.UMS.PK = msg.AuthorPK\n\tmsg.SK = msg.PK\n\treturn msg, nil\n}", "func (s *DirectMessageService) New(params *DirectMessageNewParams) (*DirectMessage, *http.Response, error) {\n\tdm := new(DirectMessage)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"new.json\").BodyForm(params).Receive(dm, apiError)\n\treturn dm, resp, relevantError(err, *apiError)\n}", "func New(listid string, bidtype int, totnoorders int, listordgrp listordgrp.ListOrdGrp) *Message {\n\tvar m Message\n\tm.SetListID(listid)\n\tm.SetBidType(bidtype)\n\tm.SetTotNoOrders(totnoorders)\n\tm.SetListOrdGrp(listordgrp)\n\treturn &m\n}", "func NewScoreDetailRequest(payload *score.ScoreDetailPayload) *scorepb.ScoreDetailRequest {\n\tmessage := &scorepb.ScoreDetailRequest{\n\t\tId: int32(payload.ID),\n\t}\n\treturn message\n}", "func NewMsgCreate(addr sdk.AccAddress, data PersonalData) MsgCreate {\n\treturn MsgCreate{Address: addr, Data: data}\n}", "func NewBuildBetaDetailsUpdateInstanceRequest(server string, id string, body BuildBetaDetailsUpdateInstanceJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBuildBetaDetailsUpdateInstanceRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func (m *manager) newRequest(ctx context.Context, selector ipld.Node, isPull bool, voucher datatransfer.Voucher, baseCid cid.Cid, to peer.ID) (datatransfer.Request, error) {\n\t// Generate a new transfer ID for the request\n\ttid := datatransfer.TransferID(m.transferIDGen.next())\n\treturn message.NewRequest(tid, false, isPull, voucher.Type(), voucher, baseCid, selector)\n}", "func (c *InputService22ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsg(server string, gid string) *Msg {\n\treturn &Msg{\n\t\tMsgData: MsgData{\n\t\t\tGid: gid,\n\t\t\tTransType: \"msg\",\n\t\t},\n\t\tTransBase: TransBase{\n\t\t\tDtm: server,\n\t\t},\n\t}\n}", "func GenerateUpdateRequest(name string, s v1alpha1.TopicParameters, t pubsub.Topic) *pubsub.UpdateTopicRequest {\n\tobserved := &v1alpha1.TopicParameters{}\n\tLateInitialize(observed, t)\n\tut := &pubsub.UpdateTopicRequest{\n\t\tTopic: &pubsub.Topic{Name: name},\n\t}\n\tmask := []string{}\n\tif !cmp.Equal(s.MessageStoragePolicy, observed.MessageStoragePolicy) {\n\t\tmask = append(mask, \"messageStoragePolicy\")\n\t\tif s.MessageStoragePolicy != nil {\n\t\t\tut.Topic.MessageStoragePolicy = &pubsub.MessageStoragePolicy{\n\t\t\t\tAllowedPersistenceRegions: s.MessageStoragePolicy.AllowedPersistenceRegions,\n\t\t\t}\n\t\t}\n\t}\n\tif !cmp.Equal(s.MessageRetentionDuration, observed.MessageRetentionDuration) {\n\t\tmask = append(mask, \"messageRetentionDuration\")\n\t\tif s.MessageRetentionDuration != nil {\n\t\t\tut.Topic.MessageRetentionDuration = gcp.StringValue(s.MessageRetentionDuration)\n\t\t}\n\t}\n\tif !cmp.Equal(s.Labels, observed.Labels) {\n\t\tmask = append(mask, \"labels\")\n\t\tut.Topic.Labels = s.Labels\n\t}\n\tut.UpdateMask = strings.Join(mask, \",\")\n\treturn ut\n}", "func (s Benchmark_send_Params) NewReq() (Message, error) {\n\tss, err := NewMessage(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *UPHostClient) NewModifyPHostInfoRequest() *ModifyPHostInfoRequest {\n\treq := &ModifyPHostInfoRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(true)\n\treturn req\n}", "func (rm *resourceManager) newUpdateRequestPayload(\n\tctx context.Context,\n\tr *resource,\n) (*svcsdk.ModifyVpnConnectionInput, error) {\n\tres := &svcsdk.ModifyVpnConnectionInput{}\n\n\tif r.ko.Spec.CustomerGatewayID != nil {\n\t\tres.SetCustomerGatewayId(*r.ko.Spec.CustomerGatewayID)\n\t}\n\tif r.ko.Spec.DryRun != nil {\n\t\tres.SetDryRun(*r.ko.Spec.DryRun)\n\t}\n\tif r.ko.Spec.TransitGatewayID != nil {\n\t\tres.SetTransitGatewayId(*r.ko.Spec.TransitGatewayID)\n\t}\n\tif r.ko.Status.VPNConnectionID != nil {\n\t\tres.SetVpnConnectionId(*r.ko.Status.VPNConnectionID)\n\t}\n\tif r.ko.Spec.VPNGatewayID != nil {\n\t\tres.SetVpnGatewayId(*r.ko.Spec.VPNGatewayID)\n\t}\n\n\treturn res, nil\n}", "func NewAppInfosUpdateInstanceRequest(server string, id string, body AppInfosUpdateInstanceJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewAppInfosUpdateInstanceRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewMessage(data map[string]interface{}, regIDs ...string) *Message {\n\treturn &Message{RegistrationIDs: regIDs, Data: data}\n}", "func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsg(n string, f string, t string, w []io.Writer) (obj *Object, err error) {\n\tobj = new(Object)\n\tobj.Name = n\n\tobj.DebugEnabled = true\n\tobj.InfoEnabled = true\n\tobj.WarningEnabled = true\n\tobj.ErrorExitCode = 1\n\n\tif len(w) == 0 {\n\t\tobj.Writers = append(obj.Writers, os.Stdout)\n\t} else {\n\t\tobj.Writers = w\n\t}\n\n\t// Set the time format. If it is empty, set the default.\n\tif t == \"\" {\n\t\tobj.TimeFormat = \"2006-01-02 15:05:05.000 MST\"\n\t} else {\n\t\tobj.TimeFormat = t\n\t}\n\n\t// Set the format. If it is empty use the default.\n\tif f == \"\" {\n\t\tobj.Format = `%(-27)time %(-7)type %file %line - %msg`\n\t} else {\n\t\tobj.Format = f\n\t}\n\n\t// Parse the format.\n\tofmt, oflds, err := ParseFormatString(obj.Format)\n\tobj.outputFormat = ofmt\n\tobj.outputFlds = oflds\n\n\treturn\n}", "func NewServiceUpdateMessageViewpoint()(*ServiceUpdateMessageViewpoint) {\n m := &ServiceUpdateMessageViewpoint{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (c *InputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewGetRequestDetailsParams() *GetRequestDetailsParams {\n\tvar ()\n\treturn &GetRequestDetailsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func New(payload string) *Message {\n\n\tmsg := &Message{\n\t\tpayload: payload,\n\t\tenteredUtc: time.Time{},\n\t\texitedUtc: time.Time{},\n\t}\n\n\treturn msg\n}", "func NewMsg(v NodeID, i SlotID, q QSet, t Topic) *Msg {\n\tc := atomic.AddInt32(&msgCounter, 1)\n\treturn &Msg{\n\t\tC: c,\n\t\tV: v,\n\t\tI: i,\n\t\tQ: q,\n\t\tT: t,\n\t}\n}", "func NewCreateanewPhonebookEntryRequest(server string, body CreateanewPhonebookEntryJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewPhonebookEntryRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewMessage(action string, version int8, key []byte, data []byte) *Message {\n\t// NOTE: take a look at other ways of generating id's\n\tid := uuid.Must(uuid.NewV4()).String()\n\n\tif key == nil {\n\t\tkey = []byte(id)\n\t}\n\n\treturn &Message{\n\t\tID: id,\n\t\tAction: action,\n\t\tVersion: Version(version),\n\t\tKey: key,\n\t\tData: data,\n\t\tack: make(chan struct{}),\n\t\tnack: make(chan struct{}),\n\t\tresponse: UnkownResolvedStatus,\n\t\tStatus: StatusOK,\n\t\tTimestamp: time.Now(),\n\t\tctx: context.Background(),\n\t}\n}", "func NewMessage(initiator string, t MsgType, payload interface{}, span opentracing.Span) Message {\n\tmsg := Message{\n\t\tID: NewMessageID(),\n\t\tType: t,\n\t\tPayload: payload,\n\t\tInitiator: initiator,\n\t\tCreated: time.Now(),\n\t\tDeadline: time.Now().Add(time.Minute * 2),\n\t\tHeaders: map[string]string{},\n\t}\n\n\tif span != nil {\n\t\tmsg.Tracing = opentracing.TextMapCarrier{}\n\t\tspan.Tracer().Inject(span.Context(), opentracing.TextMap, msg.Tracing)\n\t}\n\n\treturn msg\n}", "func NewCreateanewLnpNumberRequest(server string, body CreateanewLnpNumberJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewLnpNumberRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewMsgCreateTable(owner sdk.AccAddress, tableName string, fields []string) MsgCreateTable {\n return MsgCreateTable {\n Owner: owner,\n TableName: tableName,\n Fields: fields,\n }\n}", "func NewCreateanewCallControlRequest(server string, body CreateanewCallControlJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewCallControlRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewSendMessagesByPinUsingPOSTRequestWithoutParam() *SendMessagesByPinUsingPOSTRequest {\n\n return &SendMessagesByPinUsingPOSTRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/sendMessagesByPin\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func New(mdreqid field.MDReqIDField) (m MarketDataRequestReject) {\n\tm.Message = quickfix.NewMessage()\n\tm.Header = fix42.NewHeader(&m.Message.Header)\n\tm.Body = &m.Message.Body\n\tm.Trailer.Trailer = &m.Message.Trailer\n\n\tm.Header.Set(field.NewMsgType(\"Y\"))\n\tm.Set(mdreqid)\n\n\treturn\n}", "func (p *Pipe) newMessage() message {\n\tm := message{sourceID: p.ID()}\n\tif len(p.params) > 0 {\n\t\tm.params = p.params\n\t\tp.params = make(map[string][]phono.ParamFunc)\n\t}\n\tif len(p.feedback) > 0 {\n\t\tm.feedback = p.feedback\n\t\tp.feedback = make(map[string][]phono.ParamFunc)\n\t}\n\treturn m\n}", "func New() *Message {\n\tmsg := &Message{\n\t\tStatus: STATUS_NEW,\n\t\tFilter: false,\n\t\tContent: Content{\n\t\t\tHead: Head{},\n\t\t\tData: nil,\n\t\t},\n\t}\n\treturn msg\n}", "func NewUpdateCustomerRequest(server string, id string, body UpdatedCustomer) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdateCustomerRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func CreatePushTradeDetailRequest() (request *PushTradeDetailRequest) {\n\trequest = &PushTradeDetailRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"UniMkt\", \"2018-12-12\", \"PushTradeDetail\", \"uniMkt\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewCreateanewPbxDeviceModelRequest(server string, body CreateanewPbxDeviceModelJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewPbxDeviceModelRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewUpdateConfigRequest(server string, body UpdateConfigJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewUpdateConfigRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (c *InputService20ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func New(dkreason string, symbol string, side string) *Message {\n\tvar m Message\n\tm.SetDKReason(dkreason)\n\tm.SetSymbol(symbol)\n\tm.SetSide(side)\n\treturn &m\n}", "func (c *InputService17ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(params interface{}, atta map[string]interface{}) *DubboRequest {\n\tif atta == nil {\n\t\tatta = make(map[string]interface{})\n\t}\n\treturn &DubboRequest{\n\t\tParams: params,\n\t\tAttachments: atta,\n\t}\n}", "func NewUpdateCredentialParams() *UpdateCredentialParams {\n\tvar ()\n\treturn &UpdateCredentialParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func NewMessagesParams() *MessagesParams {\n\tvar (\n\t\tlevelDefault = string(\"ALL\")\n\t\tlimitDefault = int64(500)\n\t)\n\treturn &MessagesParams{\n\t\tLevel: &levelDefault,\n\t\tLimit: &limitDefault,\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService19ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (client *AlertsClient) updateCreateRequest(ctx context.Context, scope string, alertID string, parameters Alert, options *AlertsClientUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.Authorization/roleManagementAlerts/{alertId}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\turlPath = strings.ReplaceAll(urlPath, \"{alertId}\", alertID)\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, parameters)\n}", "func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}" ]
[ "0.6899251", "0.6611999", "0.6316249", "0.63091165", "0.6199742", "0.6177823", "0.60338837", "0.5944278", "0.5899433", "0.5830226", "0.58138627", "0.5758874", "0.5755675", "0.57067907", "0.57052994", "0.56717116", "0.5567275", "0.5392661", "0.53787595", "0.53742707", "0.5361401", "0.5360618", "0.5342714", "0.5337329", "0.52948236", "0.5294341", "0.5288633", "0.52795506", "0.5275665", "0.52736443", "0.5259269", "0.5256473", "0.52409387", "0.52409035", "0.52337956", "0.52289677", "0.5200671", "0.5199473", "0.5197808", "0.51892847", "0.5179108", "0.5178317", "0.5168072", "0.5164048", "0.5160402", "0.5157791", "0.5154188", "0.512468", "0.512251", "0.51181346", "0.5110804", "0.5109965", "0.51081294", "0.5103851", "0.5096406", "0.50927866", "0.5089674", "0.5083947", "0.5069631", "0.5065412", "0.5065391", "0.5064976", "0.5064976", "0.50642174", "0.50624853", "0.506104", "0.50442505", "0.5036347", "0.5028985", "0.5027225", "0.5006291", "0.49982986", "0.4996042", "0.49899352", "0.4985912", "0.4983486", "0.4980903", "0.4980585", "0.49731475", "0.4969266", "0.49690986", "0.49690044", "0.4960503", "0.4955498", "0.4951321", "0.495075", "0.4950616", "0.4948989", "0.49480718", "0.4937258", "0.49314874", "0.49261072", "0.49258453", "0.49229795", "0.4919644", "0.4918187", "0.4918187", "0.49175805", "0.4917296", "0.4913401" ]
0.8274957
0
ValidateBasic performs basic validation checks on the MsgUpdateDetailsRequest fields. It checks if the 'From' field is not empty and represents a valid node address, if the 'Proof.ID' field is not zero, if the 'Proof.Bandwidth' field does not contain nil or negative values, if the 'Proof.Duration' field is not negative, and if the 'Signature' field has a length of exactly 64 bytes (if not nil).
func (m *MsgUpdateDetailsRequest) ValidateBasic() error { if m.From == "" { return sdkerrors.Wrap(ErrorInvalidMessage, "from cannot be empty") } if _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil { return sdkerrors.Wrap(ErrorInvalidMessage, err.Error()) } if m.Proof.ID == 0 { return sdkerrors.Wrap(ErrorInvalidMessage, "proof.id cannot be zero") } if m.Proof.Bandwidth.IsAnyNil() { return sdkerrors.Wrap(ErrorInvalidMessage, "proof.bandwidth cannot contain nil") } if m.Proof.Bandwidth.IsAnyNegative() { return sdkerrors.Wrap(ErrorInvalidMessage, "proof.bandwidth cannot be negative") } if m.Proof.Duration < 0 { return sdkerrors.Wrap(ErrorInvalidMessage, "proof.duration cannot be negative") } if m.Signature != nil { if len(m.Signature) < 64 { return sdkerrors.Wrapf(ErrorInvalidMessage, "signature length cannot be less than %d", 64) } if len(m.Signature) > 64 { return sdkerrors.Wrapf(ErrorInvalidMessage, "signature length cannot be greater than %d", 64) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MsgUpdateStatusRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif !m.Status.IsOneOf(hubtypes.StatusActive, hubtypes.StatusInactive) {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"status must be one of [active, inactive]\")\n\t}\n\n\treturn nil\n}", "func (m *MsgStartRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Address == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgEndRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Rating > 10 {\n\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"rating cannot be greater than %d\", 10)\n\t}\n\n\treturn nil\n}", "func (m *MsgCreateRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.Duration < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be negative\")\n\t}\n\tif m.Duration == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be zero\")\n\t}\n\tif m.Gigabytes < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be negative\")\n\t}\n\tif m.Gigabytes == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be zero\")\n\t}\n\tif m.Prices == nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be nil\")\n\t}\n\tif m.Prices.Len() == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be empty\")\n\t}\n\tif m.Prices.IsAnyNil() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot contain nil\")\n\t}\n\tif !m.Prices.IsValid() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices must be valid\")\n\t}\n\n\treturn nil\n}", "func (msg MsgUpdateRecipe) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\tif len(msg.ID) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the id for the recipe require to update it\")\n\t}\n\n\tif len(msg.Description) < 20 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the description should have more than 20 characters\")\n\t}\n\n\treturn nil\n}", "func (m *MsgSubscribeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Denom == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"denom cannot be empty\")\n\t}\n\tif err := sdk.ValidateDenom(m.Denom); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgUnlinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgLinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgCreatePDV) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Owner.String())\n\t}\n\tif msg.DataType < PDVTypeCookie || msg.DataType > PDVTypeLoginCookie {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid type\")\n\t}\n\tif !cerberusapi.IsAddressValid(msg.Address) {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid address\")\n\t}\n\tif msg.Timestamp == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"Timestamp can not be 0\")\n\t}\n\treturn nil\n}", "func (msg MsgSend) ValidateBasic() sdk.Error {\n\tif msg.FromAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.ToAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Amount.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadSendAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgInitDeal) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing owner address\")\n\t}\n\tif msg.Customer.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing customer address\")\n\t}\n\tif msg.MaxTemp <= msg.MinTemp {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"maxTemp/minTemp invalid\")\n\t}\n\treturn nil\n}", "func (msg MsgBurn) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\treturn nil\n}", "func (msg MsgUnjail) ValidateBasic() sdk.Error {\n\tif msg.ValidatorAddr.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgLock) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\treturn nil\n}", "func (msg MsgBlockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgRagnarok) ValidateBasic() error {\n\tif msg.Signer.Empty() {\n\t\treturn cosmos.ErrInvalidAddress(msg.Signer.String())\n\t}\n\tif msg.BlockHeight <= 0 {\n\t\treturn cosmos.ErrUnknownRequest(\"invalid block height\")\n\t}\n\tif err := msg.Tx.Valid(); err != nil {\n\t\treturn cosmos.ErrUnknownRequest(err.Error())\n\t}\n\treturn nil\n}", "func (msg MsgAuctionReveal) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (msg MsgPostPrice) ValidateBasic() error {\n\tif msg.From.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif strings.TrimSpace(msg.MarketID) == \"\" {\n\t\treturn errors.New(\"market id cannot be blank\")\n\t}\n\tif msg.Price.IsNegative() {\n\t\treturn fmt.Errorf(\"price cannot be negative: %s\", msg.Price.String())\n\t}\n\tif msg.Expiry.IsZero() {\n\t\treturn errors.New(\"must set an expiration time\")\n\t}\n\treturn nil\n}", "func (msg MsgBeginUnstake) ValidateBasic() sdk.Error {\n\tif msg.Address.Empty() {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func NewMsgUpdateDetailsRequest(from hubtypes.NodeAddress, proof Proof, signature []byte) *MsgUpdateDetailsRequest {\n\treturn &MsgUpdateDetailsRequest{\n\t\tFrom: from.String(),\n\t\tProof: proof,\n\t\tSignature: signature,\n\t}\n}", "func (msg MsgHeartbeat) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgFund) ValidateBasic() error {\n\tif !msg.Amount.IsValid() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())\n\t}\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"sender %s\", msg.Sender.String())\n\t}\n\tif msg.Recipient.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"recipient %s\", msg.Recipient.String())\n\t}\n\treturn nil\n}", "func (msg MsgUnblockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgUpdateDeployment) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif len(msg.Version) == 0 {\n\t\treturn ErrEmptyVersion\n\t}\n\n\treturn nil\n}", "func (msg MsgEthermint) ValidateBasic() sdk.Error {\n\tif msg.Price.Sign() != 1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"price must be positive %s\", msg.Price),\n\t\t)\n\t}\n\n\t// Amount can be 0\n\tif msg.Amount.Sign() == -1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"amount cannot be negative %s\", msg.Amount),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgLeave) ValidateBasic() sdk.Error {\n\tif msg.Tx.FromAddress.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"from address cannot be empty\")\n\t}\n\tif msg.Tx.ID.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"tx id hash cannot be empty\")\n\t}\n\tif msg.Signer.Empty() {\n\t\treturn sdk.ErrUnknownRequest(\"signer cannot be empty \")\n\t}\n\treturn nil\n}", "func (msg MsgAddRecord) ValidateBasic() error {\n\tif msg.Org.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Org.String())\n\t}\n\tif msg.Vin.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Vin.String())\n\t}\n\treturn nil\n}", "func (m *MsgUpdateSellOrders) ValidateBasic() error {\n\tif len(m.Seller) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"seller cannot be empty\")\n\t}\n\n\tif _, err := sdk.AccAddressFromBech32(m.Seller); err != nil {\n\t\treturn sdkerrors.ErrInvalidAddress.Wrapf(\"seller is not a valid address: %s\", err)\n\t}\n\n\tif len(m.Updates) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"updates cannot be empty\")\n\t}\n\n\tfor i, update := range m.Updates {\n\t\tupdateIndex := fmt.Sprintf(\"updates[%d]\", i)\n\n\t\tif update.SellOrderId == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: sell order id cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif len(update.NewQuantity) == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new quantity cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif _, err := math.NewPositiveDecFromString(update.NewQuantity); err != nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new quantity must be a positive decimal\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate panics if coin is nil\n\t\tif update.NewAskPrice == nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price cannot be empty\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate provides inadequate error if coin denom is empty\n\t\tif len(update.NewAskPrice.Denom) == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: denom cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif err := sdk.ValidateDenom(update.NewAskPrice.Denom); err != nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: %s\", updateIndex, err)\n\t\t}\n\n\t\t// sdk.Coin.Validate panics if coin amount is nil\n\t\tif update.NewAskPrice.Amount.IsNil() {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: amount cannot be empty\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate provides inadequate error if coin amount is not a positive integer\n\t\tif !update.NewAskPrice.Amount.IsPositive() {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: amount must be a positive integer\", updateIndex)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgCreate) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\treturn nil\n}", "func (msg MsgFulfillTrade) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\treturn nil\n}", "func (msg MsgSwap) ValidateBasic() sdk.Error {\n\tif len(msg.SourceTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Source Ticker cannot be empty\")\n\t}\n\tif len(msg.TargetTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Target cannot be empty\")\n\t}\n\tif len(msg.Amount) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Amount cannot be empty\")\n\t}\n\tif len(msg.Requester) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Requester cannot be empty\")\n\t}\n\tif len(msg.Destination) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Destination cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimSwapReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgClaimUSDXMintingReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif msg.MultiplierName == \"\" {\n\t\treturn errorsmod.Wrap(ErrInvalidMultiplier, \"multiplier name cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgCreateCoin) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\n\tif msg.PosminingEnabled {\n\t\ti := 1\n\n\t\tfor i < len(msg.PosminingBalance) - 1 {\n\t\t\tif !msg.PosminingBalance[i].FromAmount.Equal(msg.PosminingBalance[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Posmining coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\n\t\ti = 1\n\n\t\tfor i < len(msg.StructurePosmining) - 1 {\n\t\t\tif !msg.StructurePosmining[i].FromAmount.Equal(msg.StructurePosmining[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Structure coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif len(msg.Moniker) < MinMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot be less than %d characters\", MinMonikerLength))\n\t}\n\n\tif len(msg.Moniker) > MaxMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot exceed %d characters\", MaxMonikerLength))\n\t}\n\n\tif msg.Name != nil {\n\t\tif len(*msg.Name) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Name) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Surname != nil {\n\t\tif msg.Surname != nil && len(*msg.Surname) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Surname) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Bio != nil && len(*msg.Bio) > MaxBioLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile biography cannot exceed %d characters\", MaxBioLength))\n\t}\n\n\treturn nil\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif strings.TrimSpace(msg.Dtag) == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"profile dtag cannot be empty or blank\")\n\t}\n\n\treturn nil\n}", "func (msg MsgTest) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\tif strings.Contains(msg.Test, \"bad\") {\n\t\treturn sdk.ErrUnauthorized(\"\").TraceSDK(\"bad test\")\n\t}\n\treturn nil\n}", "func (p Params) ValidateBasic() error {\n\tif err := validateMinimumGasPrices(p.MinimumGasPrices); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateBypassMinFeeMsgTypes(p.BypassMinFeeMsgTypes); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateMaxTotalBypassMinFeeMsgGasUsage(p.MaxTotalBypassMinFeeMsgGasUsage)\n}", "func (msg MsgAddMember) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 || len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimHardReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *DKGMessage) ValidateBasic() error {\n\tif m.Type < 0 || m.Type > DKGDryRun {\n\t\treturn fmt.Errorf(\"invalid Type\")\n\t}\n\tif len(m.FromAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected FromAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.FromAddress),\n\t\t)\n\t}\n\tif m.DKGID < 0 || m.DKGIteration < 0 {\n\t\treturn fmt.Errorf(\"invalid DKGID/DKGIteration\")\n\t}\n\tif len(m.Data) == 0 || len(m.Data) > MaxDKGDataSize {\n\t\treturn fmt.Errorf(\"expected non-empty Data size to be less than %d bytes, got %d bytes\",\n\t\t\tMaxDKGDataSize,\n\t\t\tlen(m.Data),\n\t\t)\n\t}\n\t// ToAddress can be empty if it is intended for everyone\n\tif len(m.ToAddress) != 0 && len(m.ToAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected ToAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.ToAddress),\n\t\t)\n\t}\n\tif len(m.Signature) == 0 || len(m.Signature) > MaxSignatureSize {\n\t\treturn fmt.Errorf(\"expected Signature size be max %d bytes, got %d bytes\",\n\t\t\tMaxSignatureSize,\n\t\t\tlen(m.Signature),\n\t\t)\n\t}\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgRemoveMember) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimEarnReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg *MsgInviteUser) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Recipient)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid recipient address: %s (%s)\", msg.Recipient, err))\n\t}\n\t_, err = sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid sender address: %s (%s)\", msg.Sender, err))\n\t}\n\treturn nil\n}", "func (msg MsgSetPauseStatus) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgRedeemTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\treturn nil\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionScavengerHash can't be empty\")\n\t}\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionHash can't be empty\")\n\t}\n\n\tvar solutionHash = sha256.Sum256([]byte(msg.Solution))\n\tvar solutionHashString = hex.EncodeToString(solutionHash[:])\n\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\treturn nil\n}", "func (msg MsgAuctionName) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.StartingPrice.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Starting price must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgClaimDelegatorReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg TinyTokenIssueMsg) ValidateBasic() error {\n\n\tif msg.From == nil {\n\t\treturn errors.New(\"sender address cannot be empty\")\n\t}\n\n\tif err := validateIssueMsgMiniTokenSymbol(msg.Symbol); err != nil {\n\t\treturn fmt.Errorf(\"Invalid symbol %v\", msg.Symbol)\n\t}\n\n\tif len(msg.Name) == 0 || len(msg.Name) > MaxMiniTokenNameLength {\n\t\treturn fmt.Errorf(\"token name should have 1 ~ %v characters\", MaxMiniTokenNameLength)\n\t}\n\n\tif len(msg.TokenURI) > MaxTokenURILength {\n\t\treturn fmt.Errorf(\"token seturi should not exceed %v characters\", MaxTokenURILength)\n\t}\n\n\t//if msg.MaxTotalSupply < MiniTokenMinTotalSupply || msg.MaxTotalSupply > MiniTokenMaxTotalSupplyUpperBound {\n\t//\treturn fmt.Errorf(\"max total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, MiniTokenMaxTotalSupplyUpperBound)\n\t//}\n\t//\n\t//if msg.TotalSupply < MiniTokenMinTotalSupply || msg.TotalSupply > msg.MaxTotalSupply {\n\t//\treturn fmt.Errorf(\"total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, msg.MaxTotalSupply)\n\t//}\n\n\treturn nil\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"create is empty\")\n\t}\n\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution is empty\")\n\t}\n\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution hash is empty\")\n\t}\n\n\tsolutionHash := sha256.Sum256([]byte(msg.Solution))\n\tsolutionHashString := hex.EncodeToString(solutionHash[:])\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\n\treturn nil\n}", "func (msg MsgClaimSavingsReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgCreateSession) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid session owner: %s\", msg.Owner))\n\t}\n\n\tif len(strings.TrimSpace(msg.Namespace)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session namespace cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.PubKey)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"signer's public key cannot be empty\")\n\t}\n\n\t// The external signer address doesn't have to exist on Desmos\n\tif len(strings.TrimSpace(msg.ExternalOwner)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session external owner cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.Signature)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session signature cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (c MsgExecLegacyContent) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(c.Authority)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (msg MsgStake) ValidateBasic() sdk.Error {\n\n\tif msg.PubKey == nil || msg.PubKey.RawString() == \"\" {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Value.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadDelegationAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn nil\n}", "func (msg MsgSetStakeData) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Name cannot be empty\")\n\t}\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Ticker cannot be empty\")\n\t}\n\tif len(msg.Atom) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Atom cannot be empty\")\n\t}\n\tif len(msg.Token) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Token cannot be empty\")\n\t}\n\treturn nil\n}", "func (s *SendTx) ValidateBasic() error {\n\tif s.chainID == \"\" {\n\t\treturn errors.New(\"No chain-id specified\")\n\t}\n\tfor _, in := range s.Tx.Inputs {\n\t\tif len(in.Address) != 20 {\n\t\t\treturn errors.Errorf(\"Invalid input address length: %d\", len(in.Address))\n\t\t}\n\t\tif !in.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid input coins %v\", in.Coins)\n\t\t}\n\t\tif in.Coins.IsZero() {\n\t\t\treturn errors.New(\"Input coins cannot be zero\")\n\t\t}\n\t\tif in.Sequence <= 0 {\n\t\t\treturn errors.New(\"Sequence must be greater than 0\")\n\t\t}\n\t}\n\tfor _, out := range s.Tx.Outputs {\n\t\t// we now allow chain/addr, so it can be more than 20 bytes\n\t\tif len(out.Address) < 20 {\n\t\t\treturn errors.Errorf(\"Invalid output address length: %d\", len(out.Address))\n\t\t}\n\t\tif !out.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid output coins %v\", out.Coins)\n\t\t}\n\t\tif out.Coins.IsZero() {\n\t\t\treturn errors.New(\"Output coins cannot be zero\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgIssueTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\tif msg.Receiver.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"receiver address cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgAddSupply) ValidateBasic() error {\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (m Params) ValidateBasic() error {\n\tif err := validateNominees(m.Nominees); err != nil {\n\t\treturn err\n\t}\n\tif err := validatePostPrice(m.PostPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (msg MsgSetMoniker) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\t//\tif len(msg.Moniker) == 0 || len(msg.Value) == 0 {\n\t//\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t//\t}\n\treturn nil\n}", "func (msg MsgDeleteShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\treturn nil\n}", "func (p *UpdateKeyNodesProposal) ValidateBasic() sdk.Error {\n\terr := govtypes.ValidateAbstract(DefaultCodespace, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(p.AddKeyNodes) == 0 && len(p.RemoveKeyNodes) == 0 {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\texists := make(map[string]bool)\n\tfor _, cu := range p.AddKeyNodes {\n\t\tif !cu.IsValidAddr() {\n\t\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t\t}\n\t\tif exists[cu.String()] {\n\t\t\treturn ErrDuplicatedValidatorAddr(DefaultCodespace)\n\t\t}\n\t\texists[cu.String()] = true\n\t}\n\tfor _, cu := range p.RemoveKeyNodes {\n\t\tif !cu.IsValidAddr() {\n\t\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t\t}\n\t\tif exists[cu.String()] {\n\t\t\treturn ErrDuplicatedValidatorAddr(DefaultCodespace)\n\t\t}\n\t\texists[cu.String()] = true\n\t}\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgDeleteName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\treturn nil\n}", "func (p IbcDataInfoPacketData) ValidateBasic() error {\n\n\t// TODO: Validate the packet data\n\n\treturn nil\n}", "func (msg MsgCreateTable) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (b *Block) ValidateBasic() error {\n\tif b == nil {\n\t\treturn errors.New(\"nil block\")\n\t}\n\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif err := b.Header.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid header: %w\", err)\n\t}\n\n\tif b.CoreChainLock != nil {\n\t\tif err := b.CoreChainLock.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid chain lock data: %w\", err)\n\t\t}\n\t}\n\n\t// Validate the last commit and its hash.\n\tif b.LastCommit == nil {\n\t\treturn errors.New(\"nil LastPrecommits\")\n\t}\n\tif err := b.LastCommit.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastPrecommits: %v\", err)\n\t}\n\n\tif !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.LastCommitHash. Expected %v, got %v\",\n\t\t\tb.LastCommit.Hash(),\n\t\t\tb.LastCommitHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.\n\tif !bytes.Equal(b.DataHash, b.Data.Hash()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"wrong Header.DataHash. Expected %v, got %v\",\n\t\t\tb.Data.Hash(),\n\t\t\tb.DataHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Evidence.Evidence may be nil, but we're just looping.\n\tfor i, ev := range b.Evidence.Evidence {\n\t\tif err := ev.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid evidence (#%d): %v\", i, err)\n\t\t}\n\t}\n\n\tif !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.EvidenceHash. Expected %v, got %v\",\n\t\t\tb.EvidenceHash,\n\t\t\tb.Evidence.Hash(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (msg MsgCreateCookbook) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\tif len(msg.Name) < 8 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the name of the cookbook should have more than 8 characters\")\n\t}\n\n\tif len(msg.Description) < 20 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the description should have more than 20 characters\")\n\t}\n\n\tif err := msg.SupportEmail.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\tif err := msg.Level.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\tif err := msg.Version.Validate(); err != nil {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgChangeSellerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ChangeBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (k *msgServer) MsgUpdateDetails(c context.Context, msg *types.MsgUpdateDetailsRequest) (*types.MsgUpdateDetailsResponse, error) {\n\t// Unwrap the SDK context from the standard context.\n\tctx := sdk.UnwrapSDKContext(c)\n\n\t// Get the session from the store using the provided session ID.\n\tsession, found := k.GetSession(ctx, msg.Proof.ID)\n\tif !found {\n\t\t// If the session is not found, return an error indicating that the session was not found.\n\t\treturn nil, types.NewErrorSessionNotFound(msg.Proof.ID)\n\t}\n\n\t// Check if the session status is 'Inactive' as only active or inactive-pending sessions can be updated.\n\tif session.Status.Equal(hubtypes.StatusInactive) {\n\t\t// If the session status is 'Inactive', return an error indicating that the session status is invalid for updating details.\n\t\treturn nil, types.NewErrorInvalidSessionStatus(session.ID, session.Status)\n\t}\n\n\t// Ensure that the message sender (msg.From) is authorized to update the session details.\n\tif msg.From != session.NodeAddress {\n\t\t// If the message sender is not authorized, return an error indicating unauthorized access.\n\t\treturn nil, types.NewErrorUnauthorized(msg.From)\n\t}\n\n\t// If proof verification is enabled, verify the signature of the message using the account address associated with the session.\n\tif k.ProofVerificationEnabled(ctx) {\n\t\tif err := k.VerifySignature(ctx, session.GetAddress(), msg.Proof, msg.Signature); err != nil {\n\t\t\t// If the signature verification fails, return an error indicating an invalid signature.\n\t\t\treturn nil, types.NewErrorInvalidSignature(msg.Signature)\n\t\t}\n\t}\n\n\t// If the session status is 'Active', update the session's InactiveAt value based on the status change delay.\n\tif session.Status.Equal(hubtypes.StatusActive) {\n\t\t// Get the status change delay from the Store.\n\t\tstatusChangeDelay := k.StatusChangeDelay(ctx)\n\n\t\t// Delete the session's entry from the InactiveAt index before updating the InactiveAt value.\n\t\tk.DeleteSessionForInactiveAt(ctx, session.InactiveAt, session.ID)\n\n\t\t// Calculate the new InactiveAt value by adding the status change delay to the current block time.\n\t\tsession.InactiveAt = ctx.BlockTime().Add(statusChangeDelay)\n\n\t\t// Update the session entry in the InactiveAt index with the new InactiveAt value.\n\t\tk.SetSessionForInactiveAt(ctx, session.InactiveAt, session.ID)\n\t}\n\n\t// Update the session's bandwidth and duration using the details from the provided proof.\n\tsession.Bandwidth = msg.Proof.Bandwidth\n\tsession.Duration = msg.Proof.Duration\n\n\t// Save the updated session to the store.\n\tk.SetSession(ctx, session)\n\n\t// Emit an event to notify that the session details have been updated.\n\tctx.EventManager().EmitTypedEvent(\n\t\t&types.EventUpdateDetails{\n\t\t\tAddress: session.Address,\n\t\t\tNodeAddress: session.NodeAddress,\n\t\t\tID: session.ID,\n\t\t\tPlanID: 0,\n\t\t\tSubscriptionID: session.SubscriptionID,\n\t\t},\n\t)\n\n\t// Return an empty MsgUpdateDetailsResponse, indicating the successful completion of the message.\n\treturn &types.MsgUpdateDetailsResponse{}, nil\n}", "func (msg MsgSetShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\tif msg.Rate.GTE(sdk.NewDec(1)) || msg.Rate.LTE(sdk.NewDec(0)) {\n\t\treturn sdk.ErrUnknownRequest(\"Rate can not great than 1 or less than 0!\")\n\t}\n\treturn nil\n}", "func (h Header) ValidateBasic() error {\n\tif h.Version.Block != version.BlockProtocol {\n\t\treturn fmt.Errorf(\"block protocol is incorrect: got: %d, want: %d \", h.Version.Block, version.BlockProtocol)\n\t}\n\tif len(h.ChainID) > MaxChainIDLen {\n\t\treturn fmt.Errorf(\"chainID is too long; got: %d, max: %d\", len(h.ChainID), MaxChainIDLen)\n\t}\n\n\tif h.Height < 0 {\n\t\treturn errors.New(\"negative Height\")\n\t} else if h.Height == 0 {\n\t\treturn errors.New(\"zero Height\")\n\t}\n\n\tif err := h.LastBlockID.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastBlockID: %w\", err)\n\t}\n\n\tif err := ValidateHash(h.LastCommitHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastCommitHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.DataHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong DataHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.EvidenceHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong EvidenceHash: %v\", err)\n\t}\n\n\tif len(h.ProposerAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\n\t\t\t\"invalid ProposerAddress length; got: %d, expected: %d\",\n\t\t\tlen(h.ProposerAddress), crypto.AddressSize,\n\t\t)\n\t}\n\n\t// Basic validation of hashes related to application data.\n\t// Will validate fully against state in state#ValidateBlock.\n\tif err := ValidateHash(h.ValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.NextValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong NextValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.ConsensusHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ConsensusHash: %v\", err)\n\t}\n\t// NOTE: AppHash is arbitrary length\n\tif err := ValidateHash(h.LastResultsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastResultsHash: %v\", err)\n\t}\n\n\treturn nil\n}", "func (h Header) ValidateBasic() error {\n\tif h.Version.Block != version.BlockProtocol {\n\t\treturn fmt.Errorf(\"block protocol is incorrect: got: %d, want: %d \", h.Version.Block, version.BlockProtocol)\n\t}\n\tif len(h.ChainID) > MaxChainIDLen {\n\t\treturn fmt.Errorf(\"chainID is too long; got: %d, max: %d\", len(h.ChainID), MaxChainIDLen)\n\t}\n\n\tif h.Height < 0 {\n\t\treturn errors.New(\"negative Height\")\n\t} else if h.Height == 0 {\n\t\treturn errors.New(\"zero Height\")\n\t}\n\n\tif err := h.LastBlockID.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastBlockID: %w\", err)\n\t}\n\n\tif err := ValidateHash(h.LastCommitHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastCommitHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.DataHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong DataHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.EvidenceHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong EvidenceHash: %v\", err)\n\t}\n\n\tif len(h.ProposerAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\n\t\t\t\"invalid ProposerAddress length; got: %d, expected: %d\",\n\t\t\tlen(h.ProposerAddress), crypto.AddressSize,\n\t\t)\n\t}\n\n\t// Basic validation of hashes related to application data.\n\t// Will validate fully against state in state#ValidateBlock.\n\tif err := ValidateHash(h.ValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.NextValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong NextValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.ConsensusHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ConsensusHash: %v\", err)\n\t}\n\t// NOTE: AppHash is arbitrary length\n\tif err := ValidateHash(h.LastResultsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastResultsHash: %v\", err)\n\t}\n\n\treturn nil\n}", "func (b *Block) ValidateBasic() error {\n\tif b == nil {\n\t\treturn errors.New(\"nil block\")\n\t}\n\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif err := b.Header.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid header: %w\", err)\n\t}\n\n\t// Validate the last commit and its hash.\n\tif b.LastCommit == nil {\n\t\treturn errors.New(\"nil LastCommit\")\n\t}\n\tif err := b.LastCommit.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastCommit: %v\", err)\n\t}\n\n\tif !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.LastCommitHash. Expected %v, got %v\",\n\t\t\tb.LastCommit.Hash(),\n\t\t\tb.LastCommitHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.\n\tif !bytes.Equal(b.DataHash, b.Data.Hash()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"wrong Header.DataHash. Expected %v, got %v\",\n\t\t\tb.Data.Hash(),\n\t\t\tb.DataHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Evidence.Evidence may be nil, but we're just looping.\n\tfor i, ev := range b.Evidence.Evidence {\n\t\tif err := ev.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid evidence (#%d): %v\", i, err)\n\t\t}\n\t}\n\n\tif !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.EvidenceHash. Expected %v, got %v\",\n\t\t\tb.EvidenceHash,\n\t\t\tb.Evidence.Hash(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func (msg MsgCreateBid) ValidateBasic() error {\n\tif err := msg.Order.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sdk.VerifyAddressFormat(msg.Provider); err != nil {\n\t\treturn ErrEmptyProvider\n\t}\n\n\tif msg.Provider.Equals(msg.Order.Owner) {\n\t\treturn ErrSameAccount\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseGroup) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h Header) ValidateBasic() error {\n\tif h.Version.Block != version.BlockProtocol {\n\t\treturn fmt.Errorf(\"block protocol is incorrect: got: %d, want: %d \", h.Version.Block, version.BlockProtocol)\n\t}\n\tif len(h.ChainID) > MaxChainIDLen {\n\t\treturn fmt.Errorf(\"chainID is too long; got: %d, max: %d\", len(h.ChainID), MaxChainIDLen)\n\t}\n\n\tif h.Height < 0 {\n\t\treturn errors.New(\"negative Height\")\n\t} else if h.Height == 0 {\n\t\treturn errors.New(\"zero Height\")\n\t}\n\n\tif err := h.LastBlockID.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastBlockID: %w\", err)\n\t}\n\n\tif err := ValidateHash(h.LastCommitHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastCommitHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.DataHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong DataHash: %v\", err)\n\t}\n\n\tif err := ValidateHash(h.EvidenceHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong EvidenceHash: %v\", err)\n\t}\n\n\tif len(h.ProposerProTxHash) != crypto.DefaultHashSize {\n\t\treturn fmt.Errorf(\n\t\t\t\"invalid ProposerProTxHash length; got: %d, expected: %d\",\n\t\t\tlen(h.ProposerProTxHash), crypto.DefaultHashSize,\n\t\t)\n\t}\n\n\t// Basic validation of hashes related to application data.\n\t// Will validate fully against state in state#ValidateBlock.\n\tif err := ValidateHash(h.ValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.NextValidatorsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong NextValidatorsHash: %v\", err)\n\t}\n\tif err := ValidateHash(h.ConsensusHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong ConsensusHash: %v\", err)\n\t}\n\t// NOTE: AppHash is arbitrary length\n\tif err := ValidateHash(h.LastResultsHash); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastResultsHash: %v\", err)\n\t}\n\n\treturn nil\n}", "func (c Checkpoint) ValidateBasic(chainID string) error {\n\treturn nil\n}", "func (msg MsgCloseBid) ValidateBasic() error {\n\treturn nil\n}", "func (cs CommitSig) ValidateBasic() error {\n\tswitch cs.BlockIDFlag {\n\tcase BlockIDFlagAbsent:\n\tcase BlockIDFlagCommit:\n\tcase BlockIDFlagNil:\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown BlockIDFlag: %v\", cs.BlockIDFlag)\n\t}\n\n\tswitch cs.BlockIDFlag {\n\tcase BlockIDFlagAbsent:\n\t\tif len(cs.ValidatorAddress) != 0 {\n\t\t\treturn errors.New(\"validator address is present\")\n\t\t}\n\t\tif !cs.Timestamp.IsZero() {\n\t\t\treturn errors.New(\"time is present\")\n\t\t}\n\t\tif len(cs.Signature) != 0 {\n\t\t\treturn errors.New(\"signature is present\")\n\t\t}\n\tdefault:\n\t\tif len(cs.ValidatorAddress) != crypto.AddressSize {\n\t\t\treturn fmt.Errorf(\"expected ValidatorAddress size to be %d bytes, got %d bytes\",\n\t\t\t\tcrypto.AddressSize,\n\t\t\t\tlen(cs.ValidatorAddress),\n\t\t\t)\n\t\t}\n\t\t// NOTE: Timestamp validation is subtle and handled elsewhere.\n\t\tif len(cs.Signature) == 0 {\n\t\t\treturn errors.New(\"signature is missing\")\n\t\t}\n\t\tif len(cs.Signature) > MaxSignatureSize {\n\t\t\treturn fmt.Errorf(\"signature is too big (max: %d)\", MaxSignatureSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgCreateIndex) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Field) ==0 {\n return sdk.ErrUnknownRequest(\"Field cannot be empty\")\n }\n return nil\n}", "func (msg MsgInsertRow) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\tif err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t}\n\treturn nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\tif err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t}\n\treturn nil\n}", "func (msg MsgCompletePurchaseOrder) ValidateBasic() sdkerrors {\r\n\tif msg.PurchaseOrderID == 0 {\r\n\t\treturn ErrUnknownPurchaseOrder(msg.PurchaseOrderID)\r\n\t}\r\n\tif len(msg.Counterparty) == 0 {\r\n\t\treturn sdk.ErrInvalidAddress(\"Invalid address: \" + msg.Counterparty.String())\r\n\t}\r\n\r\n\tif msg.PurchaseOrderStatus != \"COMPLETED\" {\r\n\t\treturn Error(\"The Purchase Order status must be Completed.\")\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (msg MsgSetPoolData) ValidateBasic() sdk.Error {\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool Ticker cannot be empty\")\n\t}\n\tif len(msg.TokenName) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool TokenName cannot be empty\")\n\t}\n\treturn nil\n}", "func (blockID BlockID) ValidateBasic() error {\n\t// Hash can be empty in case of POLBlockID in Proposal.\n\tif err := ValidateHash(blockID.Hash); err != nil {\n\t\treturn fmt.Errorf(\"wrong Hash\")\n\t}\n\t// if err := blockID.PartSetHeader.ValidateBasic(); err != nil {\n\t// \treturn fmt.Errorf(\"wrong PartSetHeader: %v\", err)\n\t// }\n\treturn nil\n}", "func (p IbcAgreementPacketData) ValidateBasic() error {\r\n\r\n\t// TODO: Validate the packet data\r\n\r\n\treturn nil\r\n}", "func (msg MsgChangeBuyerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ChangeBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (p Params) ValidateBasic() error {\n\tif p.CommunityTax.IsNegative() || p.CommunityTax.GT(sdk.OneDec()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"community tax should non-negative and less than one: %s\", p.CommunityTax,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (lb LightBlock) ValidateBasic(chainID string) error {\n\tif lb.SignedHeader == nil {\n\t\treturn errors.New(\"missing signed header\")\n\t}\n\tif lb.ValidatorSet == nil {\n\t\treturn errors.New(\"missing validator set\")\n\t}\n\n\tif err := lb.SignedHeader.ValidateBasic(chainID); err != nil {\n\t\treturn fmt.Errorf(\"invalid signed header: %w\", err)\n\t}\n\tif err := lb.ValidatorSet.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid validator set: %w\", err)\n\t}\n\n\t// make sure the validator set is consistent with the header\n\tif valSetHash := lb.ValidatorSet.Hash(); !bytes.Equal(lb.SignedHeader.ValidatorsHash, valSetHash) {\n\t\treturn fmt.Errorf(\"expected validator hash of header to match validator set hash (%X != %X)\",\n\t\t\tlb.SignedHeader.ValidatorsHash, valSetHash,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgBuyName) ValidateBasic() sdk.Error {\n\tif msg.Buyer.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Buyer.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.Bid.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Bids must be positive\")\n\t}\n\treturn nil\n}" ]
[ "0.7474643", "0.6959759", "0.6938357", "0.69371945", "0.68740106", "0.67453146", "0.66567594", "0.66225344", "0.65584713", "0.6542098", "0.6541585", "0.65343434", "0.6520683", "0.6472837", "0.6433965", "0.63979644", "0.6355426", "0.6354033", "0.6335431", "0.6324084", "0.6321093", "0.630882", "0.6298524", "0.629507", "0.6244421", "0.62427956", "0.6241343", "0.62391883", "0.6219536", "0.61842114", "0.61806566", "0.61684334", "0.61480033", "0.6131394", "0.6122533", "0.61000156", "0.6085375", "0.6078356", "0.60567695", "0.60414904", "0.6039277", "0.60179067", "0.60179067", "0.60129243", "0.6011041", "0.6008488", "0.6002307", "0.5986914", "0.5984214", "0.5979034", "0.5958648", "0.59443676", "0.5921466", "0.5901016", "0.59001815", "0.5891089", "0.58112526", "0.58100075", "0.5796871", "0.5789162", "0.5780419", "0.57760686", "0.57257426", "0.57232064", "0.572057", "0.5710783", "0.571036", "0.571036", "0.57037675", "0.5677849", "0.566471", "0.564902", "0.56392896", "0.56392896", "0.5591885", "0.5580807", "0.55686", "0.5551696", "0.5550925", "0.5550925", "0.55503416", "0.55476654", "0.5538529", "0.5536507", "0.5527281", "0.5526855", "0.552173", "0.5496687", "0.54808664", "0.54798883", "0.54753256", "0.54753256", "0.54685396", "0.5467257", "0.5453168", "0.5446144", "0.5444061", "0.543613", "0.5422057", "0.54186" ]
0.86414045
0
GetSigners returns an array containing the signer's account address extracted from the 'From' field of the MsgUpdateDetailsRequest.
func (m *MsgUpdateDetailsRequest) GetSigners() []sdk.AccAddress { from, err := hubtypes.NodeAddressFromBech32(m.From) if err != nil { panic(err) } return []sdk.AccAddress{from.Bytes()} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MsgUpdateStatusRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (m *MsgStartRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgEndRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgCreateRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (m *MsgSubscribeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgUpdateRecipe) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg TinyTokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} }", "func (msg MsgEthermint) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.From}\n}", "func (msg MsgUpdateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgClaim) GetSigners() []sdk.Address {\n\treturn []sdk.Address{sdk.Address(msg.FromAddress)}\n}", "func (msg MsgFund) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgBlockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgAddRecord) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Org}\n}", "func (msg MsgBurn) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(msg.FromAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgAddAdminAccount) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgChangeBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgHeartbeat) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgChangeSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgAddSupply) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCollectFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCreateIndex) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgUnblockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCreatePDV) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgLock) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg MsgOrderRetry) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.From)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (m *MsgUnlinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgStake) GetSigners() []sdk.AccAddress {\n\taddrs := []sdk.AccAddress{sdk.AccAddress(msg.Address)}\n\treturn addrs\n}", "func (m *MsgLinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgRagnarok) GetSigners() []cosmos.AccAddress {\n\treturn []cosmos.AccAddress{msg.Signer}\n}", "func (msg MsgAddMember) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgDeleteName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCollectSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgRedeemTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCreateCookbook) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgProof) GetSigners() []sdk.Address {\n\tpk, err := crypto.NewPublicKey(msg.Leaf.ServicerPubKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"an error occured getting the signer for the proof message, %v\", err))\n\t}\n\treturn []sdk.Address{sdk.Address(pk.Address())}\n}", "func (msg MsgSwap) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetMoniker) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgFulfillTrade) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCollectWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgClaimUSDXMintingReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgDeleteShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (msg MsgSetShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (m *MsgUpdateSellOrders) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(m.Seller)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgClaimSavingsReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgConfirmBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (tx StdTx) GetSigners() []AccAddress {\n\tseen := map[string]bool{}\n\tvar signers []AccAddress\n\tfor _, msg := range tx.GetMsgs() {\n\t\tfor _, addr := range msg.GetSigners() {\n\t\t\tif !seen[addr.String()] {\n\t\t\t\tsigners = append(signers, addr)\n\t\t\t\tseen[addr.String()] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn signers\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.FromCU}\n}", "func (msg MsgConfirmSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgCreateTable) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgClaimEarnReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgInsertRow) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgAuctionName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgSysTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgIssueTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCreateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\tprovider, err := sdk.AccAddressFromBech32(msg.Provider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{provider}\n}", "func (msg MsgCreateSession) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgRemoveMember) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg CreateZoneMsg) GetSigners() []sdk.AccAddress {\n\ttxHash := utils.ToEthSignedMessageHash(msg.TxHash())\n\n\tpubKey, err := crypto.SigToPub(txHash, msg.Signature[:])\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn []sdk.AccAddress{sdk.AccAddress(crypto.PubkeyToAddress(*pubKey).Bytes())}\n\n}", "func (msg MsgSysTransferFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgClaimSwapReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgSetOracleScriptID) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgWithdrawal) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgAuctionReveal) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgCompletePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgSetAccData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCreatePermanentLockedAccount) GetSigners() []sdk.AccAddress {\n\tfrom, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgCreatePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Counterparty)}\r\n}", "func (m *MsgCreateBatch) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(m.Issuer)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgClaimHardReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgSysTransferSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSellAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Seller)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCancelWithdrawal) GetSigners() []sdk.CUAddress {\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgWithdrawalWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgBuyAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Buyer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgWithdrawalFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgConfirmedDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.From}\n}", "func (msg MsgCancelPurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgLeave) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Signer}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgWithdrawalSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCloseGroup) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgSysTransferWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgOpcuAssetTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgWithdrawalConfirm) GetSigners() []sdk.CUAddress {\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCloseOrder) GetSigners() []sdk.AccAddress {\n\towner, err := sdk.AccAddressFromBech32(msg.OrderID.Owner)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{owner}\n}", "func (msg MsgSetStakeData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgFinancePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}" ]
[ "0.8101883", "0.7721838", "0.7720588", "0.7672856", "0.75393844", "0.7413979", "0.73201245", "0.72163343", "0.72091883", "0.72026163", "0.71498334", "0.71179664", "0.70827734", "0.70779043", "0.7072743", "0.7046519", "0.7042325", "0.70180446", "0.7002432", "0.69465554", "0.6940922", "0.6936872", "0.6934858", "0.6929657", "0.69265217", "0.6923672", "0.6920973", "0.6887377", "0.6879458", "0.68610454", "0.6860608", "0.6859638", "0.6858321", "0.6851763", "0.68314594", "0.68235606", "0.67837536", "0.6767288", "0.6765057", "0.67429584", "0.67426497", "0.6739709", "0.6739709", "0.6720068", "0.67072046", "0.67018086", "0.6700929", "0.6693796", "0.6686284", "0.6685883", "0.6685607", "0.6685607", "0.6675367", "0.6668598", "0.6667525", "0.6662867", "0.6660292", "0.66431457", "0.66431457", "0.66378134", "0.6629494", "0.6609145", "0.6600821", "0.6600066", "0.6587337", "0.6585318", "0.6577922", "0.6577922", "0.6529872", "0.65223324", "0.65162426", "0.65116614", "0.65026164", "0.64977854", "0.6495057", "0.6475018", "0.64708924", "0.6455709", "0.6452761", "0.64465004", "0.64422697", "0.64404744", "0.64346683", "0.6428218", "0.64254016", "0.6420737", "0.64169616", "0.6406128", "0.64013386", "0.6400539", "0.6394618", "0.6394618", "0.6391507", "0.63863117", "0.6382975", "0.6378336", "0.63431597", "0.631071", "0.62836295", "0.62829244" ]
0.847251
0
NewMsgEndRequest creates a new MsgEndRequest instance with the given parameters.
func NewMsgEndRequest(from sdk.AccAddress, id uint64, rating uint64) *MsgEndRequest { return &MsgEndRequest{ From: from.String(), ID: id, Rating: rating, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMsgCreateRequest(from hubtypes.ProvAddress, duration time.Duration, gigabytes int64, prices sdk.Coins) *MsgCreateRequest {\n\treturn &MsgCreateRequest{\n\t\tFrom: from.String(),\n\t\tDuration: duration,\n\t\tGigabytes: gigabytes,\n\t\tPrices: prices,\n\t}\n}", "func newRequest(ctx context.Context, msg interface{}) *request {\n\treturn &request{\n\t\tctx: ctx,\n\t\tmsg: msg,\n\t\tfailure: make(chan error, 1),\n\t\tresponse: make(chan *Delivery, 1),\n\t}\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService22ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(id string, method string, params interface{}) *Request {\n\tbuffer, err := json.Marshal(params)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Request{JsonRPC: \"2.0\", Id: id, Method: method, Params: buffer}\n}", "func New(mdreqid string, subscriptionrequesttype string, marketdepth int, nomdentrytypes []NoMDEntryTypes, norelatedsym []NoRelatedSym) *Message {\n\tvar m Message\n\tm.SetMDReqID(mdreqid)\n\tm.SetSubscriptionRequestType(subscriptionrequesttype)\n\tm.SetMarketDepth(marketdepth)\n\tm.SetNoMDEntryTypes(nomdentrytypes)\n\tm.SetNoRelatedSym(norelatedsym)\n\treturn &m\n}", "func (c *InputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsgUpdateDetailsRequest(from hubtypes.NodeAddress, proof Proof, signature []byte) *MsgUpdateDetailsRequest {\n\treturn &MsgUpdateDetailsRequest{\n\t\tFrom: from.String(),\n\t\tProof: proof,\n\t\tSignature: signature,\n\t}\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService21ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *HighAvailabilityService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *HsmProvidersService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsgStartRequest(from sdk.AccAddress, id uint64, addr hubtypes.NodeAddress) *MsgStartRequest {\n\treturn &MsgStartRequest{\n\t\tFrom: from.String(),\n\t\tID: id,\n\t\tAddress: addr.String(),\n\t}\n}", "func (s *ApplicationsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewCreateanewSMSRequest(server string, body CreateanewSMSJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewSMSRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func New(securityreqid string, securityrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityRequestType(securityrequesttype)\n\treturn &m\n}", "func (c *InputService20ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService16ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(params interface{}, atta map[string]interface{}) *DubboRequest {\n\tif atta == nil {\n\t\tatta = make(map[string]interface{})\n\t}\n\treturn &DubboRequest{\n\t\tParams: params,\n\t\tAttachments: atta,\n\t}\n}", "func (g *Group) newRequest(operation *request.Operation, input interface{}, output interface{}, handlers *request.Handlers) *request.Request {\n return request.New(g.Client, operation, input, output, handlers)\n}", "func (c *InputService19ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func newIDRequestMessage(sender ID, receiver ID) (*Message, error) {\n\t// Create the payload\n\tidr, err := newidRequest(sender, receiver)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"newIDRequestMessage: error while creating new IDRequest message\")\n\t}\n\n\t// Marshal it\n\tbin, err := idr.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"newIDRequestMessage: error when marshalling id request\")\n\t}\n\n\treturn NewMessage(identification, bytes.NewReader(bin))\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *OidcService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService14ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (bt *BlipTester) newRequest() *blip.Message {\n\tmsg := blip.NewRequest()\n\tbt.addCollectionProperty(msg)\n\treturn msg\n}", "func (c *InputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewProcessEHRMessageRequest(server string, body ProcessEHRMessageJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewProcessEHRMessageRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (c *OutputService12ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(robot *Robot, message *Message, query []string) *Request {\n\treturn &Request{\n\t\tMessage: message,\n\t\tQuery: query,\n\t\trobot: robot,\n\t}\n}", "func New(securityreqid string, securitylistrequesttype int) *Message {\n\tvar m Message\n\tm.SetSecurityReqID(securityreqid)\n\tm.SetSecurityListRequestType(securitylistrequesttype)\n\treturn &m\n}", "func (c *InputService18ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *SQS) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\t// Run custom request initialization if present\n\tif initRequest != nil {\n\t\tinitRequest(req)\n\t}\n\n\treturn req\n}", "func (c *InputService17ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsg(server string, gid string) *Msg {\n\treturn &Msg{\n\t\tMsgData: MsgData{\n\t\t\tGid: gid,\n\t\t\tTransType: \"msg\",\n\t\t},\n\t\tTransBase: TransBase{\n\t\t\tDtm: server,\n\t\t},\n\t}\n}", "func (c *OutputService13ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *AuthnReqListsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(bufid string, acts ...Action) Request {\n\tr := Request{BufferID: bufid}\n\tr.Add(acts...)\n\treturn r\n}", "func NewRequest(id, replyTo string, object ObjectID, method string, args ...interface{}) (*Request, error) {\n\tinputs, err := newTuple(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Request{\n\t\tID: id,\n\t\tInputs: inputs,\n\t\tObject: object,\n\t\tReplyTo: replyTo,\n\t\tMethod: method,\n\t}, nil\n}", "func (s Benchmark_send_Params) NewReq() (Message, error) {\n\tss, err := NewMessage(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Message{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsg(typ string) Msg {\n\treturn Msg{\n\t\tID: uuid.New().String(),\n\t\tType: typ,\n\t\tTimestamp: time.Now().UTC(),\n\t}\n}", "func NewMsg(v NodeID, i SlotID, q QSet, t Topic) *Msg {\n\tc := atomic.AddInt32(&msgCounter, 1)\n\treturn &Msg{\n\t\tC: c,\n\t\tV: v,\n\t\tI: i,\n\t\tQ: q,\n\t\tT: t,\n\t}\n}", "func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (s *VirtualhostsService) newRequest(op *request.Operation, params, data interface{}) *request.Request {\n\treq := s.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService15ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsgRequestNextHeaders() *MsgRequestNextHeaders {\n\treturn &MsgRequestNextHeaders{}\n}", "func NewRequest(ctx context.Context, id uint32, ids []cid.Cid) *Request {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Request{id: id, bs: make(chan []blocks.Block, len(ids)/2), ids: ids, done: ctx.Done(), cancel: cancel}\n}", "func (m *manager) newRequest(ctx context.Context, selector ipld.Node, isPull bool, voucher datatransfer.Voucher, baseCid cid.Cid, to peer.ID) (datatransfer.Request, error) {\n\t// Generate a new transfer ID for the request\n\ttid := datatransfer.TransferID(m.transferIDGen.next())\n\treturn message.NewRequest(tid, false, isPull, voucher.Type(), voucher, baseCid, selector)\n}", "func NewMsg(n string, f string, t string, w []io.Writer) (obj *Object, err error) {\n\tobj = new(Object)\n\tobj.Name = n\n\tobj.DebugEnabled = true\n\tobj.InfoEnabled = true\n\tobj.WarningEnabled = true\n\tobj.ErrorExitCode = 1\n\n\tif len(w) == 0 {\n\t\tobj.Writers = append(obj.Writers, os.Stdout)\n\t} else {\n\t\tobj.Writers = w\n\t}\n\n\t// Set the time format. If it is empty, set the default.\n\tif t == \"\" {\n\t\tobj.TimeFormat = \"2006-01-02 15:05:05.000 MST\"\n\t} else {\n\t\tobj.TimeFormat = t\n\t}\n\n\t// Set the format. If it is empty use the default.\n\tif f == \"\" {\n\t\tobj.Format = `%(-27)time %(-7)type %file %line - %msg`\n\t} else {\n\t\tobj.Format = f\n\t}\n\n\t// Parse the format.\n\tofmt, oflds, err := ParseFormatString(obj.Format)\n\tobj.outputFormat = ofmt\n\tobj.outputFlds = oflds\n\n\treturn\n}", "func NewMsgSpec(subjectName string, newMsg func() interface{}) (MsgSpec, error) {\n\tif !SubjectNameRegexp.MatchString(subjectName) {\n\t\treturn nil, fmt.Errorf(\"SubjectName format invalid\")\n\t}\n\n\tif newMsg == nil {\n\t\treturn nil, fmt.Errorf(\"NewMsg is empty\")\n\t}\n\tmsgValue := newMsg()\n\tif msgValue == nil {\n\t\treturn nil, fmt.Errorf(\"NewMsg() returns nil\")\n\t}\n\tmsgType := reflect.TypeOf(msgValue)\n\tif msgType.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"NewMsg() returns %s which is not a pointer\", msgType.String())\n\t}\n\n\treturn &msgSpec{\n\t\tsubjectName: subjectName,\n\t\tnewMsg: newMsg,\n\t\tmsgType: msgType,\n\t\tmsgValue: msgValue,\n\t}, nil\n}", "func NewMessage(initiator string, t MsgType, payload interface{}, span opentracing.Span) Message {\n\tmsg := Message{\n\t\tID: NewMessageID(),\n\t\tType: t,\n\t\tPayload: payload,\n\t\tInitiator: initiator,\n\t\tCreated: time.Now(),\n\t\tDeadline: time.Now().Add(time.Minute * 2),\n\t\tHeaders: map[string]string{},\n\t}\n\n\tif span != nil {\n\t\tmsg.Tracing = opentracing.TextMapCarrier{}\n\t\tspan.Tracer().Inject(span.Context(), opentracing.TextMap, msg.Tracing)\n\t}\n\n\treturn msg\n}", "func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewMsgUpdate(addr sdk.AccAddress, data PersonalData) MsgUpdate {\n\treturn MsgUpdate{Address: addr, Data: data}\n}", "func (m *InMemManager) NewRequest() *Request {\n\treturn NewRequest(m)\n}", "func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(methodName string, params []interface{}) (req Request, err error) {\n\treq = Request{\n\t\tMethodName: methodName,\n\t\tParams: make([]Value, 0, len(params)),\n\t}\n\n\tfor _, p := range params {\n\t\tv := NewValue(p)\n\t\tif v == nil {\n\t\t\treturn req, fmt.Errorf(\"NewRequest: cannot convert parameter %v\", p)\n\t\t}\n\n\t\treq.Params = append(req.Params, *v)\n\t}\n\n\treturn req, nil\n}", "func (c *OutputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewRequest(id string, method string) *Request {\n\n\treq := &Request{\n\t\tJSONRPC: \"2.0\",\n\t\tID: id,\n\t\tMethod: method,\n\t}\n\treturn req\n}", "func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func NewCreateanewSMSRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/sms\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func NewRequest(conn Conn, data []byte, offset int) Request {\n\treturn &request{conn: conn, data: data, offset: offset}\n}", "func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}", "func (c *InputService10ProtocolTest) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {\n\treq := c.NewRequest(op, params, data)\n\n\treturn req\n}" ]
[ "0.62026787", "0.5946389", "0.5756797", "0.5756797", "0.57563", "0.57205117", "0.5709054", "0.5703476", "0.5657828", "0.5651425", "0.5651425", "0.56457436", "0.56424123", "0.5628975", "0.5628975", "0.5610753", "0.5607929", "0.5606953", "0.5600522", "0.5587441", "0.558687", "0.5556749", "0.5554474", "0.55534273", "0.55534273", "0.5552982", "0.55524087", "0.55386925", "0.5532798", "0.5532798", "0.55316913", "0.55316913", "0.5520235", "0.5510978", "0.55079246", "0.5492936", "0.5488853", "0.54821527", "0.54821527", "0.5481053", "0.5481053", "0.54793096", "0.54753506", "0.5471597", "0.5459317", "0.54580045", "0.54523", "0.54456055", "0.5444295", "0.5437386", "0.5425326", "0.5425326", "0.54241455", "0.54241455", "0.54210126", "0.54210126", "0.5420325", "0.5417001", "0.5407835", "0.5406812", "0.5406059", "0.5405049", "0.5402035", "0.54009324", "0.5399863", "0.53972536", "0.53972536", "0.5392402", "0.5358742", "0.5346149", "0.53459", "0.53445756", "0.53389406", "0.53368133", "0.53297985", "0.53295815", "0.5320156", "0.5312293", "0.53091407", "0.5299607", "0.52946717", "0.52946717", "0.5292361", "0.52885526", "0.5282882", "0.5274589", "0.52730525", "0.5264872", "0.5264348", "0.5261106", "0.5242024", "0.52265406", "0.5225785", "0.5225785", "0.5224064", "0.5218752", "0.52128834", "0.52125484", "0.52125484", "0.52039087" ]
0.8401176
0
ValidateBasic performs basic validation checks on the MsgEndRequest fields. It checks if the 'From' field is not empty and represents a valid account address, if the 'ID' field is not zero, and if the 'Rating' field is not greater than 10.
func (m *MsgEndRequest) ValidateBasic() error { if m.From == "" { return sdkerrors.Wrap(ErrorInvalidMessage, "from cannot be empty") } if _, err := sdk.AccAddressFromBech32(m.From); err != nil { return sdkerrors.Wrap(ErrorInvalidMessage, err.Error()) } if m.ID == 0 { return sdkerrors.Wrap(ErrorInvalidMessage, "id cannot be zero") } if m.Rating > 10 { return sdkerrors.Wrapf(ErrorInvalidMessage, "rating cannot be greater than %d", 10) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MsgUpdateDetailsRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.Proof.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.id cannot be zero\")\n\t}\n\tif m.Proof.Bandwidth.IsAnyNil() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.bandwidth cannot contain nil\")\n\t}\n\tif m.Proof.Bandwidth.IsAnyNegative() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.bandwidth cannot be negative\")\n\t}\n\tif m.Proof.Duration < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"proof.duration cannot be negative\")\n\t}\n\tif m.Signature != nil {\n\t\tif len(m.Signature) < 64 {\n\t\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"signature length cannot be less than %d\", 64)\n\t\t}\n\t\tif len(m.Signature) > 64 {\n\t\t\treturn sdkerrors.Wrapf(ErrorInvalidMessage, \"signature length cannot be greater than %d\", 64)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *MsgSubscribeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Denom == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"denom cannot be empty\")\n\t}\n\tif err := sdk.ValidateDenom(m.Denom); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (m *MsgStartRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.Address == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.Address); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgSend) ValidateBasic() sdk.Error {\n\tif msg.FromAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.ToAddress.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Amount.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadSendAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (m *MsgUpdateStatusRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif !m.Status.IsOneOf(hubtypes.StatusActive, hubtypes.StatusInactive) {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"status must be one of [active, inactive]\")\n\t}\n\n\treturn nil\n}", "func (m *MsgCreateRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.Duration < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be negative\")\n\t}\n\tif m.Duration == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"duration cannot be zero\")\n\t}\n\tif m.Gigabytes < 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be negative\")\n\t}\n\tif m.Gigabytes == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"gigabytes cannot be zero\")\n\t}\n\tif m.Prices == nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be nil\")\n\t}\n\tif m.Prices.Len() == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot be empty\")\n\t}\n\tif m.Prices.IsAnyNil() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices cannot contain nil\")\n\t}\n\tif !m.Prices.IsValid() {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"prices must be valid\")\n\t}\n\n\treturn nil\n}", "func (msg MsgLeave) ValidateBasic() sdk.Error {\n\tif msg.Tx.FromAddress.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"from address cannot be empty\")\n\t}\n\tif msg.Tx.ID.IsEmpty() {\n\t\treturn sdk.ErrUnknownRequest(\"tx id hash cannot be empty\")\n\t}\n\tif msg.Signer.Empty() {\n\t\treturn sdk.ErrUnknownRequest(\"signer cannot be empty \")\n\t}\n\treturn nil\n}", "func (msg MsgUnjail) ValidateBasic() sdk.Error {\n\tif msg.ValidatorAddr.Empty() {\n\t\treturn ErrBadValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgInitDeal) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing owner address\")\n\t}\n\tif msg.Customer.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"missing customer address\")\n\t}\n\tif msg.MaxTemp <= msg.MinTemp {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"maxTemp/minTemp invalid\")\n\t}\n\treturn nil\n}", "func (msg MsgAddRecord) ValidateBasic() error {\n\tif msg.Org.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Org.String())\n\t}\n\tif msg.Vin.Empty() {\n\t\treturn sdkErrors.Wrap(sdkErrors.ErrInvalidAddress, msg.Vin.String())\n\t}\n\treturn nil\n}", "func (msg MsgBeginUnstake) ValidateBasic() sdk.Error {\n\tif msg.Address.Empty() {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgPostPrice) ValidateBasic() error {\n\tif msg.From.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif strings.TrimSpace(msg.MarketID) == \"\" {\n\t\treturn errors.New(\"market id cannot be blank\")\n\t}\n\tif msg.Price.IsNegative() {\n\t\treturn fmt.Errorf(\"price cannot be negative: %s\", msg.Price.String())\n\t}\n\tif msg.Expiry.IsZero() {\n\t\treturn errors.New(\"must set an expiration time\")\n\t}\n\treturn nil\n}", "func (msg MsgRagnarok) ValidateBasic() error {\n\tif msg.Signer.Empty() {\n\t\treturn cosmos.ErrInvalidAddress(msg.Signer.String())\n\t}\n\tif msg.BlockHeight <= 0 {\n\t\treturn cosmos.ErrUnknownRequest(\"invalid block height\")\n\t}\n\tif err := msg.Tx.Valid(); err != nil {\n\t\treturn cosmos.ErrUnknownRequest(err.Error())\n\t}\n\treturn nil\n}", "func (msg MsgClaimEarnReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgAuctionReveal) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (msg MsgBlockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (m *DKGMessage) ValidateBasic() error {\n\tif m.Type < 0 || m.Type > DKGDryRun {\n\t\treturn fmt.Errorf(\"invalid Type\")\n\t}\n\tif len(m.FromAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected FromAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.FromAddress),\n\t\t)\n\t}\n\tif m.DKGID < 0 || m.DKGIteration < 0 {\n\t\treturn fmt.Errorf(\"invalid DKGID/DKGIteration\")\n\t}\n\tif len(m.Data) == 0 || len(m.Data) > MaxDKGDataSize {\n\t\treturn fmt.Errorf(\"expected non-empty Data size to be less than %d bytes, got %d bytes\",\n\t\t\tMaxDKGDataSize,\n\t\t\tlen(m.Data),\n\t\t)\n\t}\n\t// ToAddress can be empty if it is intended for everyone\n\tif len(m.ToAddress) != 0 && len(m.ToAddress) != crypto.AddressSize {\n\t\treturn fmt.Errorf(\"expected ToAddress size to be %d bytes, got %d bytes\",\n\t\t\tcrypto.AddressSize,\n\t\t\tlen(m.ToAddress),\n\t\t)\n\t}\n\tif len(m.Signature) == 0 || len(m.Signature) > MaxSignatureSize {\n\t\treturn fmt.Errorf(\"expected Signature size be max %d bytes, got %d bytes\",\n\t\t\tMaxSignatureSize,\n\t\t\tlen(m.Signature),\n\t\t)\n\t}\n\treturn nil\n}", "func (msg MsgUnblockAddress) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Address.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"blocked address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (msg MsgFulfillTrade) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\treturn nil\n}", "func (msg MsgClaimDelegatorReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgClaimSavingsReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg *MsgInviteUser) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Recipient)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid recipient address: %s (%s)\", msg.Recipient, err))\n\t}\n\t_, err = sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn sdkErr.Wrap(sdkErr.ErrInvalidAddress, fmt.Sprintf(\"Invalid sender address: %s (%s)\", msg.Sender, err))\n\t}\n\treturn nil\n}", "func (msg MsgUpdateRecipe) ValidateBasic() error {\n\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Sender.String())\n\n\t}\n\n\tif len(msg.ID) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the id for the recipe require to update it\")\n\t}\n\n\tif len(msg.Description) < 20 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"the description should have more than 20 characters\")\n\t}\n\n\treturn nil\n}", "func (msg MsgFund) ValidateBasic() error {\n\tif !msg.Amount.IsValid() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())\n\t}\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"sender %s\", msg.Sender.String())\n\t}\n\tif msg.Recipient.Empty() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, \"recipient %s\", msg.Recipient.String())\n\t}\n\treturn nil\n}", "func (msg MsgClaimHardReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MsgLinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgRedeemTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\treturn nil\n}", "func (m *MsgUnlinkNodeRequest) ValidateBasic() error {\n\tif m.From == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"from cannot be empty\")\n\t}\n\tif _, err := hubtypes.ProvAddressFromBech32(m.From); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\tif m.ID == 0 {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"id cannot be zero\")\n\t}\n\tif m.NodeAddress == \"\" {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, \"node_address cannot be empty\")\n\t}\n\tif _, err := hubtypes.NodeAddressFromBech32(m.NodeAddress); err != nil {\n\t\treturn sdkerrors.Wrap(ErrorInvalidMessage, err.Error())\n\t}\n\n\treturn nil\n}", "func (msg MsgClaimUSDXMintingReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif msg.MultiplierName == \"\" {\n\t\treturn errorsmod.Wrap(ErrInvalidMultiplier, \"multiplier name cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgEthermint) ValidateBasic() sdk.Error {\n\tif msg.Price.Sign() != 1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"price must be positive %s\", msg.Price),\n\t\t)\n\t}\n\n\t// Amount can be 0\n\tif msg.Amount.Sign() == -1 {\n\t\treturn sdk.ConvertError(\n\t\t\tsdkerrors.Wrapf(types.ErrInvalidValue, \"amount cannot be negative %s\", msg.Amount),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgCreatePDV) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Owner.String())\n\t}\n\tif msg.DataType < PDVTypeCookie || msg.DataType > PDVTypeLoginCookie {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid type\")\n\t}\n\tif !cerberusapi.IsAddressValid(msg.Address) {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"invalid address\")\n\t}\n\tif msg.Timestamp == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"Timestamp can not be 0\")\n\t}\n\treturn nil\n}", "func (msg MsgTest) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\tif strings.Contains(msg.Test, \"bad\") {\n\t\treturn sdk.ErrUnauthorized(\"\").TraceSDK(\"bad test\")\n\t}\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn nil\n}", "func (msg MsgCloseBid) ValidateBasic() error {\n\treturn nil\n}", "func (msg MsgHeartbeat) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgBurn) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\treturn nil\n}", "func (msg MsgCreate) ValidateBasic() sdk.Error {\n\tif len(msg.Sender) == 0 {\n\t\treturn sdk.ErrUnknownAddress(msg.Sender.String()).TraceSDK(\"\")\n\t}\n\treturn nil\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (msg MsgCloseOrder) ValidateBasic() error {\n\treturn msg.OrderID.Validate()\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif strings.TrimSpace(msg.Dtag) == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"profile dtag cannot be empty or blank\")\n\t}\n\n\treturn nil\n}", "func (msg MsgAddSupply) ValidateBasic() error {\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (msg MsgLock) ValidateBasic() error {\n\tif strconv.Itoa(msg.EthereumChainID) == \"\" {\n\t\treturn sdkerrors.Wrapf(ErrInvalidEthereumChainID, \"%d\", msg.EthereumChainID)\n\t}\n\n\tif msg.TokenContract.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.TokenContract.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif msg.CosmosSender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.CosmosSender.String())\n\t}\n\n\tif msg.EthereumReceiver.String() == \"\" {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\tif !gethCommon.IsHexAddress(msg.EthereumReceiver.String()) {\n\t\treturn ErrInvalidEthAddress\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseGroup) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgAuctionName) ValidateBasic() sdk.Error {\n\tif msg.Auctor.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Auctor.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.StartingPrice.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Starting price must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgSetShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\tif msg.Rate.GTE(sdk.NewDec(1)) || msg.Rate.LTE(sdk.NewDec(0)) {\n\t\treturn sdk.ErrUnknownRequest(\"Rate can not great than 1 or less than 0!\")\n\t}\n\treturn nil\n}", "func (msg MsgSaveProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\tif len(msg.Moniker) < MinMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot be less than %d characters\", MinMonikerLength))\n\t}\n\n\tif len(msg.Moniker) > MaxMonikerLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile moniker cannot exceed %d characters\", MaxMonikerLength))\n\t}\n\n\tif msg.Name != nil {\n\t\tif len(*msg.Name) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Name) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile name cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Surname != nil {\n\t\tif msg.Surname != nil && len(*msg.Surname) < MinNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot be less than %d characters\", MinNameSurnameLength))\n\t\t}\n\n\t\tif len(*msg.Surname) > MaxNameSurnameLength {\n\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile surname cannot exceed %d characters\", MaxNameSurnameLength))\n\t\t}\n\t}\n\n\tif msg.Bio != nil && len(*msg.Bio) > MaxBioLength {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Profile biography cannot exceed %d characters\", MaxBioLength))\n\t}\n\n\treturn nil\n}", "func (msg MsgSetPauseStatus) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\treturn sdk.ValidateDenom(msg.Denom)\n}", "func (p Params) ValidateBasic() error {\n\tif err := validateMinimumGasPrices(p.MinimumGasPrices); err != nil {\n\t\treturn err\n\t}\n\n\tif err := validateBypassMinFeeMsgTypes(p.BypassMinFeeMsgTypes); err != nil {\n\t\treturn err\n\t}\n\n\treturn validateMaxTotalBypassMinFeeMsgGasUsage(p.MaxTotalBypassMinFeeMsgGasUsage)\n}", "func (msg MsgCompletePurchaseOrder) ValidateBasic() sdkerrors {\r\n\tif msg.PurchaseOrderID == 0 {\r\n\t\treturn ErrUnknownPurchaseOrder(msg.PurchaseOrderID)\r\n\t}\r\n\tif len(msg.Counterparty) == 0 {\r\n\t\treturn sdk.ErrInvalidAddress(\"Invalid address: \" + msg.Counterparty.String())\r\n\t}\r\n\r\n\tif msg.PurchaseOrderStatus != \"COMPLETED\" {\r\n\t\treturn Error(\"The Purchase Order status must be Completed.\")\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (msg MsgClaimSwapReward) ValidateBasic() error {\n\t_, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\treturn errorsmod.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty or invalid\")\n\t}\n\tif err := msg.DenomsToClaim.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgDeleteProfile) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"Invalid creator address: %s\", msg.Creator))\n\t}\n\n\treturn nil\n}", "func (msg MsgCloseBid) ValidateBasic() error {\n\treturn msg.BidID.Validate()\n}", "func (msg MsgCloseBid) ValidateBasic() error {\n\treturn msg.BidID.Validate()\n}", "func (msg MsgDeleteShareHolder) ValidateBasic() sdk.Error {\n\tif msg.Validator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Validator.String())\n\t}\n\tif msg.Delegator.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Delegator.String())\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func (msg MsgConfirmSellerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ConfirmBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (msg MsgCreateBid) ValidateBasic() error {\n\tif err := msg.Order.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sdk.VerifyAddressFormat(msg.Provider); err != nil {\n\t\treturn ErrEmptyProvider\n\t}\n\n\tif msg.Provider.Equals(msg.Order.Owner) {\n\t\treturn ErrSameAccount\n\t}\n\n\treturn nil\n}", "func (m Params) ValidateBasic() error {\n\tif err := validateNominees(m.Nominees); err != nil {\n\t\treturn err\n\t}\n\tif err := validatePostPrice(m.PostPrice); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (msg MsgAuctionBid) ValidateBasic() sdk.Error {\n\tif msg.Buyer.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Buyer.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.Bid.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Bids must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgAddMember) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 || len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (s *SendTx) ValidateBasic() error {\n\tif s.chainID == \"\" {\n\t\treturn errors.New(\"No chain-id specified\")\n\t}\n\tfor _, in := range s.Tx.Inputs {\n\t\tif len(in.Address) != 20 {\n\t\t\treturn errors.Errorf(\"Invalid input address length: %d\", len(in.Address))\n\t\t}\n\t\tif !in.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid input coins %v\", in.Coins)\n\t\t}\n\t\tif in.Coins.IsZero() {\n\t\t\treturn errors.New(\"Input coins cannot be zero\")\n\t\t}\n\t\tif in.Sequence <= 0 {\n\t\t\treturn errors.New(\"Sequence must be greater than 0\")\n\t\t}\n\t}\n\tfor _, out := range s.Tx.Outputs {\n\t\t// we now allow chain/addr, so it can be more than 20 bytes\n\t\tif len(out.Address) < 20 {\n\t\t\treturn errors.Errorf(\"Invalid output address length: %d\", len(out.Address))\n\t\t}\n\t\tif !out.Coins.IsValid() {\n\t\t\treturn errors.Errorf(\"Invalid output coins %v\", out.Coins)\n\t\t}\n\t\tif out.Coins.IsZero() {\n\t\t\treturn errors.New(\"Output coins cannot be zero\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgSetStakeData) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Name cannot be empty\")\n\t}\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Ticker cannot be empty\")\n\t}\n\tif len(msg.Atom) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Atom cannot be empty\")\n\t}\n\tif len(msg.Token) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Stake Token cannot be empty\")\n\t}\n\treturn nil\n}", "func (m *MsgUpdateSellOrders) ValidateBasic() error {\n\tif len(m.Seller) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"seller cannot be empty\")\n\t}\n\n\tif _, err := sdk.AccAddressFromBech32(m.Seller); err != nil {\n\t\treturn sdkerrors.ErrInvalidAddress.Wrapf(\"seller is not a valid address: %s\", err)\n\t}\n\n\tif len(m.Updates) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"updates cannot be empty\")\n\t}\n\n\tfor i, update := range m.Updates {\n\t\tupdateIndex := fmt.Sprintf(\"updates[%d]\", i)\n\n\t\tif update.SellOrderId == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: sell order id cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif len(update.NewQuantity) == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new quantity cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif _, err := math.NewPositiveDecFromString(update.NewQuantity); err != nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new quantity must be a positive decimal\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate panics if coin is nil\n\t\tif update.NewAskPrice == nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price cannot be empty\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate provides inadequate error if coin denom is empty\n\t\tif len(update.NewAskPrice.Denom) == 0 {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: denom cannot be empty\", updateIndex)\n\t\t}\n\n\t\tif err := sdk.ValidateDenom(update.NewAskPrice.Denom); err != nil {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: %s\", updateIndex, err)\n\t\t}\n\n\t\t// sdk.Coin.Validate panics if coin amount is nil\n\t\tif update.NewAskPrice.Amount.IsNil() {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: amount cannot be empty\", updateIndex)\n\t\t}\n\n\t\t// sdk.Coin.Validate provides inadequate error if coin amount is not a positive integer\n\t\tif !update.NewAskPrice.Amount.IsPositive() {\n\t\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"%s: new ask price: amount must be a positive integer\", updateIndex)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg MsgRemoveMember) ValidateBasic() sdk.Error {\n\tif len(msg.NodeID) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"ID cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSetMoniker) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\t//\tif len(msg.Moniker) == 0 || len(msg.Value) == 0 {\n\t//\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t//\t}\n\treturn nil\n}", "func (msg MsgConfirmBuyerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ConfirmBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (msg MsgSellAsset) ValidateBasic() error {\n\taddr, err := sdk.AccAddressFromBech32(msg.Seller)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif addr.Empty() {\n\t\treturn ErrEmptyAddr\n\t}\n\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (msg MsgSetAccData) ValidateBasic() sdk.Error {\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Account Name cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSwap) ValidateBasic() sdk.Error {\n\tif len(msg.SourceTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Source Ticker cannot be empty\")\n\t}\n\tif len(msg.TargetTicker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Target cannot be empty\")\n\t}\n\tif len(msg.Amount) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Amount cannot be empty\")\n\t}\n\tif len(msg.Requester) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Requester cannot be empty\")\n\t}\n\tif len(msg.Destination) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Swap Destination cannot be empty\")\n\t}\n\treturn nil\n}", "func (br BaseReq) ValidateBasic(w http.ResponseWriter) bool {\n\tswitch {\n\tcase len(br.Name) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"name required but not specified\")\n\t\treturn false\n\n\tcase len(br.Password) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"password required but not specified\")\n\t\treturn false\n\n\tcase len(br.ChainID) == 0:\n\t\tWriteErrorResponse(w, http.StatusUnauthorized, \"chainID required but not specified\")\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (msg MsgCreateCoin) ValidateBasic() error {\n\tif msg.Creator.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\n\tif msg.PosminingEnabled {\n\t\ti := 1\n\n\t\tfor i < len(msg.PosminingBalance) - 1 {\n\t\t\tif !msg.PosminingBalance[i].FromAmount.Equal(msg.PosminingBalance[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Posmining coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\n\t\ti = 1\n\n\t\tfor i < len(msg.StructurePosmining) - 1 {\n\t\t\tif !msg.StructurePosmining[i].FromAmount.Equal(msg.StructurePosmining[i-1].ToAmount) {\n\t\t\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"Structure coffs should be the same\")\n\t\t\t}\n\n\t\t\ti -= 1\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p IbcAgreementPacketData) ValidateBasic() error {\r\n\r\n\t// TODO: Validate the packet data\r\n\r\n\treturn nil\r\n}", "func (msg MsgCreateBid) ValidateBasic() error {\n\tif err := msg.Order.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tprovider, err := sdk.AccAddressFromBech32(msg.Provider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\towner, err := sdk.AccAddressFromBech32(msg.Order.Owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif provider.Equals(owner) {\n\t\treturn ErrSameAccount\n\t}\n\n\treturn nil\n}", "func (msg MsgChangeSellerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ChangeBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (msg MsgSetPoolData) ValidateBasic() sdk.Error {\n\tif len(msg.Ticker) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool Ticker cannot be empty\")\n\t}\n\tif len(msg.TokenName) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Pool TokenName cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgCreateBid) ValidateBasic() error {\n\tif err := msg.Order.Validate(); err != nil {\n\t\treturn ErrInvalidOrder\n\t}\n\n\tif msg.Provider.Empty() {\n\t\treturn ErrEmptyProvider\n\t}\n\n\tif msg.Provider.Equals(msg.Order.Owner) {\n\t\treturn ErrSameAccount\n\t}\n\n\treturn nil\n}", "func (msg MsgStake) ValidateBasic() sdk.Error {\n\n\tif msg.PubKey == nil || msg.PubKey.RawString() == \"\" {\n\t\treturn ErrNilValidatorAddr(DefaultCodespace)\n\t}\n\tif msg.Value.LTE(sdk.ZeroInt()) {\n\t\treturn ErrBadDelegationAmount(DefaultCodespace)\n\t}\n\treturn nil\n}", "func (msg MsgBuyName) ValidateBasic() sdk.Error {\n\tif msg.Buyer.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Buyer.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\tif !msg.Bid.IsAllPositive() {\n\t\treturn sdk.ErrInsufficientCoins(\"Bids must be positive\")\n\t}\n\treturn nil\n}", "func (msg MsgInsertRow) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (msg TinyTokenIssueMsg) ValidateBasic() error {\n\n\tif msg.From == nil {\n\t\treturn errors.New(\"sender address cannot be empty\")\n\t}\n\n\tif err := validateIssueMsgMiniTokenSymbol(msg.Symbol); err != nil {\n\t\treturn fmt.Errorf(\"Invalid symbol %v\", msg.Symbol)\n\t}\n\n\tif len(msg.Name) == 0 || len(msg.Name) > MaxMiniTokenNameLength {\n\t\treturn fmt.Errorf(\"token name should have 1 ~ %v characters\", MaxMiniTokenNameLength)\n\t}\n\n\tif len(msg.TokenURI) > MaxTokenURILength {\n\t\treturn fmt.Errorf(\"token seturi should not exceed %v characters\", MaxTokenURILength)\n\t}\n\n\t//if msg.MaxTotalSupply < MiniTokenMinTotalSupply || msg.MaxTotalSupply > MiniTokenMaxTotalSupplyUpperBound {\n\t//\treturn fmt.Errorf(\"max total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, MiniTokenMaxTotalSupplyUpperBound)\n\t//}\n\t//\n\t//if msg.TotalSupply < MiniTokenMinTotalSupply || msg.TotalSupply > msg.MaxTotalSupply {\n\t//\treturn fmt.Errorf(\"total supply should be between %d ~ %d\", MiniTokenMinTotalSupply, msg.MaxTotalSupply)\n\t//}\n\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgSetName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 || len(msg.Value) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name and/or Value cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgIssueTokens) ValidateBasic() error {\n\tif msg.Sender.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"sender address cannot be empty\")\n\t}\n\tif msg.Tokens.IsZero() || !msg.Tokens.IsValid() {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, \"invalid tokens %s\", msg.Tokens)\n\t}\n\tif msg.Receiver.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"receiver address cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgDeleteName) ValidateBasic() sdk.Error {\n\tif msg.Owner.Empty() {\n\t\treturn sdk.ErrInvalidAddress(msg.Owner.String())\n\t}\n\tif len(msg.Name) == 0 {\n\t\treturn sdk.ErrUnknownRequest(\"Name cannot be empty\")\n\t}\n\treturn nil\n}", "func (msg MsgCreateSession) ValidateBasic() error {\n\tif msg.Owner.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, fmt.Sprintf(\"invalid session owner: %s\", msg.Owner))\n\t}\n\n\tif len(strings.TrimSpace(msg.Namespace)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session namespace cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.PubKey)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"signer's public key cannot be empty\")\n\t}\n\n\t// The external signer address doesn't have to exist on Desmos\n\tif len(strings.TrimSpace(msg.ExternalOwner)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session external owner cannot be empty\")\n\t}\n\n\tif len(strings.TrimSpace(msg.Signature)) == 0 {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, \"session signature cannot be empty\")\n\t}\n\n\treturn nil\n}", "func (msg MsgChangeBuyerBids) ValidateBasic() sdk.Error {\n\t_, err := govalidator.ValidateStruct(msg)\n\tif err != nil {\n\t\treturn sdk.ErrInsufficientFunds(err.Error())\n\t}\n\tfor _, in := range msg.ChangeBids {\n\t\t_, err := govalidator.ValidateStruct(in)\n\t\tif err != nil {\n\t\t\treturn sdk.ErrInvalidAddress(err.Error())\n\t\t}\n\t\tif len(in.Negotiation.GetBuyerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetBuyerAddress().String())\n\t\t} else if len(in.Negotiation.GetSellerAddress()) == 0 {\n\t\t\treturn sdk.ErrInvalidAddress(in.Negotiation.GetSellerAddress().String())\n\t\t} else if len(in.Negotiation.GetNegotiationID()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Negotiation ID is wrong\")\n\t\t} else if len(in.Negotiation.GetPegHash()) == 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Peghash is empty\")\n\t\t} else if in.Negotiation.GetBid() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Bid amount should be greater than 0\")\n\t\t} else if in.Negotiation.GetTime() <= 0 {\n\t\t\treturn sdk.ErrUnknownRequest(\"Time should not be 0\")\n\t\t}\n\t}\n\treturn nil\n}", "func (msg MsgSetOracleScriptID) ValidateBasic() error {\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\treturn nil\n}", "func (msg MsgCreateTable) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Fields) ==0 {\n return sdk.ErrUnknownRequest(\"Fields cannot be empty\")\n }\n return nil\n}", "func (m *MsgUpsertTokenRate) ValidateBasic() error {\n\tif m.Denom == \"ukex\" {\n\t\treturn errors.New(\"bond denom rate is read-only\")\n\t}\n\n\tif m.Rate.LTE(sdk.NewDec(0)) { // not positive\n\t\treturn errors.New(\"rate should be positive\")\n\t}\n\n\treturn nil\n}", "func (m *MsgCreateBatch) ValidateBasic() error {\n\tif _, err := sdk.AccAddressFromBech32(m.Issuer); err != nil {\n\t\treturn sdkerrors.ErrInvalidAddress.Wrapf(\"issuer: %s\", err)\n\t}\n\n\tif err := base.ValidateProjectID(m.ProjectId); err != nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"project id: %s\", err)\n\t}\n\n\tif len(m.Issuance) == 0 {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"issuance cannot be empty\")\n\t}\n\n\tfor i, issuance := range m.Issuance {\n\t\tif err := issuance.Validate(); err != nil {\n\t\t\treturn errors.Wrapf(err, \"issuance[%d]\", i)\n\t\t}\n\t}\n\n\t// we allow metadata to be empty for class and project but not for batch\n\tif m.Metadata == \"\" {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrapf(\"metadata cannot be empty\")\n\t}\n\n\tif len(m.Metadata) > base.MaxMetadataLength {\n\t\treturn ecocredit.ErrMaxLimit.Wrapf(\"metadata: max length %d\", base.MaxMetadataLength)\n\t}\n\n\tif m.StartDate == nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"start date cannot be empty\")\n\t}\n\n\tif m.EndDate == nil {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"end date cannot be empty\")\n\t}\n\n\tif m.StartDate.After(*m.EndDate) {\n\t\treturn sdkerrors.ErrInvalidRequest.Wrap(\"start date cannot be after end date\")\n\t}\n\n\t// origin tx is not required when creating a credit batch\n\tif m.OriginTx != nil {\n\t\tif err := m.OriginTx.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p Params) ValidateBasic() error {\n\tif p.CommunityTax.IsNegative() || p.CommunityTax.GT(sdk.OneDec()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"community tax should non-negative and less than one: %s\", p.CommunityTax,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (msg MsgBuyAsset) ValidateBasic() error {\n\taddr, err := sdk.AccAddressFromBech32(msg.Buyer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif addr.Empty() {\n\t\treturn ErrEmptyAddr\n\t}\n\n\tif msg.Denom == \"\" {\n\t\treturn ErrEmptyDenom\n\t}\n\n\tif msg.Amount <= 0 {\n\t\treturn ErrInvalidAmt\n\t}\n\n\treturn nil\n}", "func (out Output) ValidateBasic() sdk.Error {\n\tif len(out.Address) == 0 {\n\t\treturn sdk.ErrInvalidAddress(out.Address.String())\n\t}\n\tif !out.Coins.IsValid() {\n\t\treturn sdk.ErrInvalidCoins(out.Coins.String())\n\t}\n\tif !out.Coins.IsAllPositive() {\n\t\treturn sdk.ErrInvalidCoins(out.Coins.String())\n\t}\n\treturn nil\n}", "func (in Input) ValidateBasic() sdk.Error {\n\tif len(in.Address) == 0 {\n\t\treturn sdk.ErrInvalidAddress(in.Address.String())\n\t}\n\tif !in.Coins.IsValid() {\n\t\treturn sdk.ErrInvalidCoins(in.Coins.String())\n\t}\n\tif !in.Coins.IsAllPositive() {\n\t\treturn sdk.ErrInvalidCoins(in.Coins.String())\n\t}\n\treturn nil\n}", "func (msg MsgCloseDeployment) ValidateBasic() error {\n\tif err := msg.ID.Validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (msg MsgCreateIndex) ValidateBasic() sdk.Error {\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n if len(msg.TableName) == 0 {\n return sdk.ErrUnknownRequest(\"Table name cannot be empty\")\n }\n if len(msg.Field) ==0 {\n return sdk.ErrUnknownRequest(\"Field cannot be empty\")\n }\n return nil\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"create is empty\")\n\t}\n\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution is empty\")\n\t}\n\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solution hash is empty\")\n\t}\n\n\tsolutionHash := sha256.Sum256([]byte(msg.Solution))\n\tsolutionHashString := hex.EncodeToString(solutionHash[:])\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\n\treturn nil\n}", "func (msg MsgRevealSolution) ValidateBasic() error {\n\tif msg.Scavenger.Empty() {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, \"creator can't be empty\")\n\t}\n\tif msg.SolutionHash == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionScavengerHash can't be empty\")\n\t}\n\tif msg.Solution == \"\" {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, \"solutionHash can't be empty\")\n\t}\n\n\tvar solutionHash = sha256.Sum256([]byte(msg.Solution))\n\tvar solutionHashString = hex.EncodeToString(solutionHash[:])\n\n\tif msg.SolutionHash != solutionHashString {\n\t\treturn sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf(\"Hash of solution (%s) doesn't equal solutionHash (%s)\", msg.SolutionHash, solutionHashString))\n\t}\n\treturn nil\n}", "func (p IbcDataInfoPacketData) ValidateBasic() error {\n\n\t// TODO: Validate the packet data\n\n\treturn nil\n}" ]
[ "0.74446213", "0.72229946", "0.7191636", "0.7069034", "0.7055482", "0.69845295", "0.69159067", "0.6840464", "0.6831378", "0.6701209", "0.66747177", "0.6666997", "0.66533583", "0.66428137", "0.6606639", "0.6540865", "0.6534915", "0.6529824", "0.64612293", "0.6450843", "0.6425318", "0.6406522", "0.64055747", "0.6401973", "0.63971514", "0.6392803", "0.63889015", "0.63579047", "0.6347649", "0.63409996", "0.6337792", "0.6334783", "0.6328722", "0.63265854", "0.63002026", "0.6283285", "0.6282037", "0.6256285", "0.6256285", "0.6252586", "0.6246667", "0.62423366", "0.62296396", "0.62274647", "0.62231714", "0.6217388", "0.62083876", "0.62001455", "0.6182176", "0.61821204", "0.61022", "0.61022", "0.6101508", "0.6101508", "0.61007506", "0.6094292", "0.60868895", "0.60779953", "0.6073709", "0.6054594", "0.6032928", "0.6018805", "0.6007053", "0.5998615", "0.59862965", "0.5985881", "0.59831256", "0.59590155", "0.59507823", "0.5946439", "0.5922191", "0.5918779", "0.5906546", "0.59026676", "0.5890609", "0.58813596", "0.5879717", "0.5875866", "0.5874239", "0.5864516", "0.58607286", "0.5856249", "0.5856249", "0.58511233", "0.58181", "0.5772246", "0.57705855", "0.57662845", "0.575824", "0.57574344", "0.5754805", "0.5748919", "0.57331914", "0.57085496", "0.5705274", "0.56940866", "0.5668867", "0.56623286", "0.56542724", "0.5630827" ]
0.8393039
0
GetSigners returns an array containing the signer's account address extracted from the 'From' field of the MsgEndRequest.
func (m *MsgEndRequest) GetSigners() []sdk.AccAddress { from, err := sdk.AccAddressFromBech32(m.From) if err != nil { panic(err) } return []sdk.AccAddress{from} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MsgStartRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgSubscribeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from}\n}", "func (m *MsgCreateRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (m *MsgUpdateDetailsRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.NodeAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgClaim) GetSigners() []sdk.Address {\n\treturn []sdk.Address{sdk.Address(msg.FromAddress)}\n}", "func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(msg.FromAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgEthermint) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.From}\n}", "func (msg MsgFund) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (m *MsgUpdateStatusRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgCreateVestingAccount) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCollectFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgAddRecord) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Org}\n}", "func (msg MsgBurn) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg TinyTokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} }", "func (msg MsgCollectSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgRagnarok) GetSigners() []cosmos.AccAddress {\n\treturn []cosmos.AccAddress{msg.Signer}\n}", "func (msg MsgBlockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (m *MsgLinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgStake) GetSigners() []sdk.AccAddress {\n\taddrs := []sdk.AccAddress{sdk.AccAddress(msg.Address)}\n\treturn addrs\n}", "func (msg MsgOrderRetry) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.From)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (m *MsgUnlinkNodeRequest) GetSigners() []sdk.AccAddress {\n\tfrom, err := hubtypes.ProvAddressFromBech32(m.From)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{from.Bytes()}\n}", "func (msg MsgAddSupply) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgHeartbeat) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCollectWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgAddAdminAccount) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (tx StdTx) GetSigners() []AccAddress {\n\tseen := map[string]bool{}\n\tvar signers []AccAddress\n\tfor _, msg := range tx.GetMsgs() {\n\t\tfor _, addr := range msg.GetSigners() {\n\t\t\tif !seen[addr.String()] {\n\t\t\t\tsigners = append(signers, addr)\n\t\t\t\tseen[addr.String()] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn signers\n}", "func (msg MsgLock) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.CosmosSender}\n}", "func (msg MsgConfirmSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgConfirmBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ConfirmBids))\n\tfor i, in := range msg.ConfirmBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.FromCU}\n}", "func (msg MsgChangeBuyerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetBuyerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgRedeemTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCreateCookbook) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgClaimDelegatorReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgCreatePDV) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgProof) GetSigners() []sdk.Address {\n\tpk, err := crypto.NewPublicKey(msg.Leaf.ServicerPubKey)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"an error occured getting the signer for the proof message, %v\", err))\n\t}\n\treturn []sdk.Address{sdk.Address(pk.Address())}\n}", "func (msg MsgWithdrawalFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgClaimEarnReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgChangeSellerBids) GetSigners() []sdk.AccAddress {\n\taddrs := make([]sdk.AccAddress, len(msg.ChangeBids))\n\tfor i, in := range msg.ChangeBids {\n\t\taddrs[i] = in.Negotiation.GetSellerAddress()\n\t}\n\treturn addrs\n}", "func (msg MsgClaimSavingsReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgWithdrawalSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgDeleteName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgFulfillTrade) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgSetShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (msg MsgUnblockAddress) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCompletePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgBuyName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Buyer}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\tprovider, err := sdk.AccAddressFromBech32(msg.Provider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{provider}\n}", "func (msg MsgCreateIndex) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSysTransferFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgWithdrawal) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgUpdateRecipe) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgSetMoniker) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgWithdrawalWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgLeave) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Signer}\n}", "func (msg MsgClaimUSDXMintingReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (msg MsgDeleteShareHolder) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Validator.Bytes())}\n}", "func (msg MsgSysTransferSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSellAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Seller)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgSysTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgBuyAsset) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Buyer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCloseGroup) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgAuctionName) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgAddMember) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgCancelPurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgSaveProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgCreateTable) GetSigners() []sdk.AccAddress {\n return []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgSetOracleScriptID) GetSigners() []sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(msg.Addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCreateSession) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgConfirmedDeposit) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\treturn []sdk.CUAddress{msg.From}\n}", "func (msg MsgClaimHardReward) GetSigners() []sdk.AccAddress {\n\tsender, err := sdk.AccAddressFromBech32(msg.Sender)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{sender}\n}", "func (m *MsgCreateBatch) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(m.Issuer)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCloseOrder) GetSigners() []sdk.AccAddress {\n\towner, err := sdk.AccAddressFromBech32(msg.OrderID.Owner)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{owner}\n}", "func (msg MsgUpdateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgSysTransferWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSetAccData) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg MsgFinancePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Party)}\r\n}", "func (msg MsgCreateDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}", "func (msg MsgAuctionReveal) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Auctor}\n}", "func (msg MsgOpcuAssetTransferFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgOpcuAssetTransfer) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgCancelWithdrawal) GetSigners() []sdk.CUAddress {\n\taddr, err := sdk.CUAddressFromBase58(msg.FromCU)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgDeleteProfile) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Creator}\n}", "func (msg MsgCreatePurchaseOrder) GetSigners() []sdk.AccAddress {\r\n\treturn []sdk.AccAddress{sdk.AccAddress(msg.Counterparty)}\r\n}", "func (msg MsgCreatePermanentLockedAccount) GetSigners() []sdk.AccAddress {\n\tfrom, _ := sdk.AccAddressFromBech32(msg.FromAddress)\n\treturn []sdk.AccAddress{from}\n}", "func (msg MsgOpcuAssetTransferSignFinish) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (msg MsgSwap) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Owner}\n}", "func (msg CreateZoneMsg) GetSigners() []sdk.AccAddress {\n\ttxHash := utils.ToEthSignedMessageHash(msg.TxHash())\n\n\tpubKey, err := crypto.SigToPub(txHash, msg.Signature[:])\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn []sdk.AccAddress{sdk.AccAddress(crypto.PubkeyToAddress(*pubKey).Bytes())}\n\n}", "func (msg MsgIssueTokens) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Sender}\n}", "func (msg MsgCloseBid) GetSigners() []sdk.AccAddress {\n\tprovider, err := sdk.AccAddressFromBech32(msg.BidID.Provider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn []sdk.AccAddress{provider}\n}", "func (msg MsgOpcuAssetTransferWaitSign) GetSigners() []sdk.CUAddress {\n\t// delegator is first signer so delegator pays fees\n\taddr, err := sdk.CUAddressFromBase58(msg.Validator)\n\tif err != nil {\n\t\treturn []sdk.CUAddress{}\n\t}\n\treturn []sdk.CUAddress{addr}\n}", "func (m *MsgUpdateSellOrders) GetSigners() []sdk.AccAddress {\n\taddr, _ := sdk.AccAddressFromBech32(m.Seller)\n\treturn []sdk.AccAddress{addr}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgCreateBid) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.Provider}\n}", "func (msg MsgCloseDeployment) GetSigners() []sdk.AccAddress {\n\treturn []sdk.AccAddress{msg.ID.Owner}\n}" ]
[ "0.8144936", "0.78425986", "0.78235567", "0.7621545", "0.7563626", "0.75396353", "0.7493757", "0.74259067", "0.74168015", "0.74130875", "0.7390196", "0.7369486", "0.7354489", "0.73101485", "0.7292086", "0.7284197", "0.72758603", "0.72133327", "0.7195004", "0.71929777", "0.7172949", "0.7161107", "0.7147462", "0.7138422", "0.7112635", "0.70818496", "0.7081296", "0.707401", "0.7071198", "0.70607144", "0.70593816", "0.7054046", "0.7050723", "0.70467335", "0.7042891", "0.70426315", "0.7042589", "0.7039901", "0.70255125", "0.7017849", "0.7015002", "0.7013271", "0.7012668", "0.7010441", "0.6996594", "0.69933736", "0.6983801", "0.6983801", "0.6976", "0.6976", "0.6972489", "0.696634", "0.6960795", "0.69509697", "0.69457644", "0.693658", "0.69363904", "0.69305027", "0.6906931", "0.69052756", "0.6900957", "0.68775135", "0.6865788", "0.6864745", "0.68628484", "0.6855089", "0.6849552", "0.68454033", "0.6831002", "0.6831002", "0.6830605", "0.6829339", "0.68251854", "0.68180764", "0.681592", "0.6800072", "0.67729515", "0.67663276", "0.6760577", "0.67564", "0.6747209", "0.67431724", "0.6738215", "0.673148", "0.6730084", "0.6723129", "0.6718322", "0.6718322", "0.6716495", "0.6710279", "0.6700522", "0.6695954", "0.66915834", "0.6689057", "0.6683758", "0.66755074", "0.6669071", "0.6667822", "0.6667822", "0.66470796" ]
0.85278934
0
New initializes a new Cluster from the given client REST config.
func New(config *rest.Config) (*Cluster, error) { clientSet, err := kubernetes.NewForConfig(config) if err != nil { return nil, fmt.Errorf("kubernetes.NewForConfig: %w", err) } return &Cluster{clientSet}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewCluster(config string, channels ...string) (*client, error) {\n\t// parse the url provided\n\toptions, err := redis.ParseURL(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the Redis client from failover options\n\tqueue := redis.NewFailoverClient(failoverFromOptions(options))\n\n\t// setup queue with proper configuration\n\terr = setupQueue(queue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the client object\n\tclient := &client{\n\t\tQueue: queue,\n\t\tOptions: options,\n\t}\n\n\treturn client, nil\n}", "func NewForConfig(c *rest.Config) (*ClusterClientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(&configShallowCopy, httpClient)\n}", "func New(kubeconfig string, clusterContextOptions ...string) (*Client, error) {\n\tvar clusterCtxName string\n\tif len(clusterContextOptions) > 0 {\n\t\tclusterCtxName = clusterContextOptions[0]\n\t}\n\n\t// creating cfg for each client type because each\n\t// setup needs its own cfg default which may not be compatible\n\tdynCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := dynamic.NewForConfig(dynCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiscoCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdisco, err := discovery.NewDiscoveryClientForConfig(discoCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := restmapper.GetAPIGroupResources(disco)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmapper := restmapper.NewDiscoveryRESTMapper(resources)\n\n\trestCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsetCoreDefaultConfig(restCfg)\n\trestc, err := rest.RESTClientFor(restCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{Client: client, Disco: disco, CoreRest: restc, Mapper: mapper}, nil\n}", "func NewClient() (*Client, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttypes := runtime.NewScheme()\n\tschemeBuilder := runtime.NewSchemeBuilder(\n\t\tfunc(scheme *runtime.Scheme) error {\n\t\t\treturn nil\n\t\t})\n\n\terr = schemeBuilder.AddToScheme(types)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := newClientForAPI(config, v1alpha1.GroupVersion, types)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{\n\t\tclient: client,\n\t}, err\n}", "func New(createCRD bool, namespace string) *Cluster {\n\t\n\tclientset := utils.MustNewKubeClient(); \n\treturn &Cluster{\n\t\tlogger: logrus.WithField(\"pkg\", \"controller\"),\n\t\tnamespace: namespace,\n\t\tkubeClientset: clientset,\n\t\tcreateCustomResource: createCRD,\n\t}\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOpt) (*Cluster, error) {\n\tif args == nil || args.BrokerNodeGroupInfo == nil {\n\t\treturn nil, errors.New(\"missing required argument 'BrokerNodeGroupInfo'\")\n\t}\n\tif args == nil || args.ClusterName == nil {\n\t\treturn nil, errors.New(\"missing required argument 'ClusterName'\")\n\t}\n\tif args == nil || args.KafkaVersion == nil {\n\t\treturn nil, errors.New(\"missing required argument 'KafkaVersion'\")\n\t}\n\tif args == nil || args.NumberOfBrokerNodes == nil {\n\t\treturn nil, errors.New(\"missing required argument 'NumberOfBrokerNodes'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"brokerNodeGroupInfo\"] = nil\n\t\tinputs[\"clientAuthentication\"] = nil\n\t\tinputs[\"clusterName\"] = nil\n\t\tinputs[\"configurationInfo\"] = nil\n\t\tinputs[\"encryptionInfo\"] = nil\n\t\tinputs[\"enhancedMonitoring\"] = nil\n\t\tinputs[\"kafkaVersion\"] = nil\n\t\tinputs[\"numberOfBrokerNodes\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t} else {\n\t\tinputs[\"brokerNodeGroupInfo\"] = args.BrokerNodeGroupInfo\n\t\tinputs[\"clientAuthentication\"] = args.ClientAuthentication\n\t\tinputs[\"clusterName\"] = args.ClusterName\n\t\tinputs[\"configurationInfo\"] = args.ConfigurationInfo\n\t\tinputs[\"encryptionInfo\"] = args.EncryptionInfo\n\t\tinputs[\"enhancedMonitoring\"] = args.EnhancedMonitoring\n\t\tinputs[\"kafkaVersion\"] = args.KafkaVersion\n\t\tinputs[\"numberOfBrokerNodes\"] = args.NumberOfBrokerNodes\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"bootstrapBrokers\"] = nil\n\tinputs[\"bootstrapBrokersTls\"] = nil\n\tinputs[\"currentVersion\"] = nil\n\tinputs[\"zookeeperConnectString\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:msk/cluster:Cluster\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{s: s}, nil\n}", "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func NewCluster(driverName, name, addr string, configGetter ConfigGetter, persistStore PersistentStore) (*Cluster, error) {\n\trpcClient, err := types.NewClient(driverName, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{\n\t\tDriver: rpcClient,\n\t\tDriverName: driverName,\n\t\tName: name,\n\t\tConfigGetter: configGetter,\n\t\tPersistStore: persistStore,\n\t}, nil\n}", "func New(config LoadAgentClusterConfig, ltConfig loadtest.Config, log *mlog.Logger) (*LoadAgentCluster, error) {\n\tif log == nil {\n\t\treturn nil, errors.New(\"logger should not be nil\")\n\t}\n\tif err := defaults.Validate(config); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not validate configuration: %w\", err)\n\t}\n\tagents := make([]*client.Agent, len(config.Agents))\n\terrMap := make(map[*client.Agent]*errorTrack)\n\tfor i := 0; i < len(agents); i++ {\n\t\tagent, err := client.New(config.Agents[i].Id, config.Agents[i].ApiURL, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cluster: failed to create api client: %w\", err)\n\t\t}\n\t\tagents[i] = agent\n\t\terrMap[agent] = &errorTrack{}\n\n\t\t// We check if the agent has already been created.\n\t\tif _, err := agent.Status(); err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := createAgent(agent, ltConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &LoadAgentCluster{\n\t\tagents: agents,\n\t\tconfig: config,\n\t\tltConfig: ltConfig,\n\t\terrMap: errMap,\n\t\tlog: log,\n\t}, nil\n}", "func New(clusterDefinition *v1alpha1.Cassandra) (*Cluster, error) {\n\tcluster := &Cluster{}\n\tif err := CopyInto(cluster, clusterDefinition); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cluster, nil\n}", "func New(endpoint string) (*Client, error) {\n\tservers, err := clusterNodes(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tss := new(memcache.ServerList)\n\tif err := ss.SetServers(servers...); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tClient: memcache.NewFromSelector(ss),\n\t\tServerList: ss,\n\t\tEndpoint: endpoint,\n\t}\n\n\treturn client, nil\n}", "func newInClusterClient(endpoint string) (*clientWrapper, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create in-cluster configuration: %w\", err)\n\t}\n\n\tif endpoint != \"\" {\n\t\tconfig.Host = endpoint\n\t}\n\n\treturn createClientFromConfig(config)\n}", "func newK8sCluster(c config.Config) (*k8sCluster, error) {\n\tvar kubeconfig *string\n\tif home := homedir.HomeDir(); home != \"\" {\n\t\tkubeconfig = flag.String(\"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolue path to the kubeconfig file\")\n\t} else {\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolue path to the kubeconfig file\")\n\t}\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &k8sCluster{\n\t\tconfig: c,\n\t\tmutex: sync.Mutex{},\n\t\tpods: make(map[string]string),\n\t\tclientset: clientset,\n\t}, nil\n}", "func New(cfg Config) (*Cluster, error) {\n\tcluster := &Cluster{\n\t\tID: cfg.ID,\n\t\tName: cfg.Name,\n\t}\n\n\tdiscoargs := buildPFlagSlice(cfg.DiscoveryFlagsByImpl[cfg.DiscoveryImpl])\n\n\tdisco, err := discovery.New(cfg.DiscoveryImpl, cluster.ToProto(), discoargs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating discovery impl (%s): %w\", cfg.DiscoveryImpl, err)\n\t}\n\n\tcluster.Discovery = disco\n\n\tprotocluster := cluster.ToProto()\n\n\tvtsqlargs := buildPFlagSlice(cfg.VtSQLFlags)\n\n\tvtsqlCfg, err := vtsql.Parse(protocluster, disco, vtsqlargs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating vtsql connection config: %w\", err)\n\t}\n\n\tvtctldargs := buildPFlagSlice(cfg.VtctldFlags)\n\n\tvtctldCfg, err := vtctldclient.Parse(protocluster, disco, vtctldargs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating vtctldclient proxy config: %w\", err)\n\t}\n\n\tcluster.DB = vtsql.New(vtsqlCfg)\n\tcluster.Vtctld = vtctldclient.New(vtctldCfg)\n\n\tif cfg.TabletFQDNTmplStr != \"\" {\n\t\tcluster.TabletFQDNTmpl, err = template.New(cluster.ID + \"-tablet-fqdn\").Parse(cfg.TabletFQDNTmplStr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse tablet fqdn template %s: %w\", cfg.TabletFQDNTmplStr, err)\n\t\t}\n\t}\n\n\treturn cluster, nil\n}", "func NewCluster(client ExtendedClient, applier Applier, sshKeyRing ssh.KeyRing, logger log.Logger, allowedNamespaces map[string]struct{}, imageIncluder cluster.Includer, resourceExcludeList []string) *Cluster {\n\tif imageIncluder == nil {\n\t\timageIncluder = cluster.AlwaysInclude\n\t}\n\n\tc := &Cluster{\n\t\tclient: client,\n\t\tapplier: applier,\n\t\tlogger: logger,\n\t\tsshKeyRing: sshKeyRing,\n\t\tallowedNamespaces: allowedNamespaces,\n\t\tloggedAllowedNS: map[string]bool{},\n\t\timageIncluder: imageIncluder,\n\t\tresourceExcludeList: resourceExcludeList,\n\t}\n\n\treturn c\n}", "func NewFromCluster(client clientset.Interface, certificatesDir string) (*Client, error) {\n\t// Discover at least one etcd endpoint to connect to by inspecting the existing etcd pods\n\n\t// Get the list of etcd endpoints\n\tendpoints, err := getEtcdEndpoints(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklog.V(1).Infof(\"etcd endpoints read from pods: %s\", strings.Join(endpoints, \",\"))\n\n\t// Creates an etcd client\n\tetcdClient, err := New(\n\t\tendpoints,\n\t\tfilepath.Join(certificatesDir, constants.EtcdCACertName),\n\t\tfilepath.Join(certificatesDir, constants.EtcdHealthcheckClientCertName),\n\t\tfilepath.Join(certificatesDir, constants.EtcdHealthcheckClientKeyName),\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating etcd client for %v endpoints\", endpoints)\n\t}\n\n\t// synchronizes client's endpoints with the known endpoints from the etcd membership.\n\terr = etcdClient.Sync()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error syncing endpoints with etcd\")\n\t}\n\tklog.V(1).Infof(\"update etcd endpoints: %s\", strings.Join(etcdClient.Endpoints, \",\"))\n\n\treturn etcdClient, nil\n}", "func New(c *Config) Client {\n\treturn newClient(c)\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOpt) (*Cluster, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"applyImmediately\"] = nil\n\t\tinputs[\"availabilityZones\"] = nil\n\t\tinputs[\"backupRetentionPeriod\"] = nil\n\t\tinputs[\"clusterIdentifier\"] = nil\n\t\tinputs[\"clusterIdentifierPrefix\"] = nil\n\t\tinputs[\"engine\"] = nil\n\t\tinputs[\"engineVersion\"] = nil\n\t\tinputs[\"finalSnapshotIdentifier\"] = nil\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = nil\n\t\tinputs[\"iamRoles\"] = nil\n\t\tinputs[\"kmsKeyArn\"] = nil\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = nil\n\t\tinputs[\"neptuneSubnetGroupName\"] = nil\n\t\tinputs[\"port\"] = nil\n\t\tinputs[\"preferredBackupWindow\"] = nil\n\t\tinputs[\"preferredMaintenanceWindow\"] = nil\n\t\tinputs[\"replicationSourceIdentifier\"] = nil\n\t\tinputs[\"skipFinalSnapshot\"] = nil\n\t\tinputs[\"snapshotIdentifier\"] = nil\n\t\tinputs[\"storageEncrypted\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t\tinputs[\"vpcSecurityGroupIds\"] = nil\n\t} else {\n\t\tinputs[\"applyImmediately\"] = args.ApplyImmediately\n\t\tinputs[\"availabilityZones\"] = args.AvailabilityZones\n\t\tinputs[\"backupRetentionPeriod\"] = args.BackupRetentionPeriod\n\t\tinputs[\"clusterIdentifier\"] = args.ClusterIdentifier\n\t\tinputs[\"clusterIdentifierPrefix\"] = args.ClusterIdentifierPrefix\n\t\tinputs[\"engine\"] = args.Engine\n\t\tinputs[\"engineVersion\"] = args.EngineVersion\n\t\tinputs[\"finalSnapshotIdentifier\"] = args.FinalSnapshotIdentifier\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = args.IamDatabaseAuthenticationEnabled\n\t\tinputs[\"iamRoles\"] = args.IamRoles\n\t\tinputs[\"kmsKeyArn\"] = args.KmsKeyArn\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = args.NeptuneClusterParameterGroupName\n\t\tinputs[\"neptuneSubnetGroupName\"] = args.NeptuneSubnetGroupName\n\t\tinputs[\"port\"] = args.Port\n\t\tinputs[\"preferredBackupWindow\"] = args.PreferredBackupWindow\n\t\tinputs[\"preferredMaintenanceWindow\"] = args.PreferredMaintenanceWindow\n\t\tinputs[\"replicationSourceIdentifier\"] = args.ReplicationSourceIdentifier\n\t\tinputs[\"skipFinalSnapshot\"] = args.SkipFinalSnapshot\n\t\tinputs[\"snapshotIdentifier\"] = args.SnapshotIdentifier\n\t\tinputs[\"storageEncrypted\"] = args.StorageEncrypted\n\t\tinputs[\"tags\"] = args.Tags\n\t\tinputs[\"vpcSecurityGroupIds\"] = args.VpcSecurityGroupIds\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"clusterMembers\"] = nil\n\tinputs[\"clusterResourceId\"] = nil\n\tinputs[\"endpoint\"] = nil\n\tinputs[\"hostedZoneId\"] = nil\n\tinputs[\"readerEndpoint\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:neptune/cluster:Cluster\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{s: s}, nil\n}", "func newClusterNetwork(c *Client) *clusterNetwork {\n\treturn &clusterNetwork{\n\t\tr: c,\n\t}\n}", "func NewClusterClient(transport http.RoundTripper, path string) *ClusterClient {\n\treturn &ClusterClient{\n\t\ttransport: transport,\n\t\tpath: path,\n\t}\n}", "func New(config Config) (*TenantCluster, error) {\n\tif config.CertsSearcher == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.CertsSearcher must not be empty\", config)\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.Logger must not be empty\", config)\n\t}\n\n\tif config.CertID == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"%T.CertID must not be empty\", config)\n\t}\n\n\tt := &TenantCluster{\n\t\tcertsSearcher: config.CertsSearcher,\n\t\tlogger: config.Logger,\n\n\t\tcertID: config.CertID,\n\t}\n\n\treturn t, nil\n}", "func NewCluster(conf *ClusterConfig) *Cluster {\n\tc := &Cluster{\n\t\tDialTimeout: conf.DialTimeout,\n\t\tReadTimeout: conf.ReadTimeout,\n\t\tWriteTimeout: conf.WriteTimeout,\n\t\tAddressPicker: nil,\n\t\ttcpKeepAlive: defaultTCPKeepAlive,\n\t\ttcpKeepAlivePeriod: defaultTCPKeepAlivePeriod,\n\t\ttcpLinger: defaultTCPLinger,\n\t\ttcpNoDelay: defaultTCPNoDelay,\n\t}\n\tif conf.PoolConfig != nil {\n\t\tif conf.UseAsyncPool {\n\t\t\tc.connpool = NewAsyncConnPool(conf.PoolConfig)\n\t\t} else {\n\t\t\tc.connpool = NewSyncConnPool(conf.PoolConfig)\n\t\t}\n\t}\n\treturn c\n}", "func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*ClusterClientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tif configShallowCopy.Burst <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0\")\n\t\t}\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\n\tcache := kcpclient.NewCache(c, httpClient, &kcpclient.Constructor[metadata.Interface]{\n\t\tNewForConfigAndClient: metadata.NewForConfigAndClient,\n\t})\n\tif _, err := cache.Cluster(logicalcluster.Name(\"root\").Path()); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClusterClientset{clientCache: cache}, nil\n}", "func New(c Config) pkg.HelmClient {\n\treturn &Client{\n\t\tconf: &c,\n\t\tcli: httpclient.NewHttpClient(),\n\t}\n}", "func NewCluster(config *Config, loggers []Logger) *Cluster {\n\tcluster := &Cluster{config: config, loggers: loggers}\n\treturn cluster\n}", "func NewCluster(cfg config.StorageClusterConfig, dialer ConnectionDialer) (*Cluster, error) {\n\tif err := cfg.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tserverCount := int64(len(cfg.Servers))\n\tavailableServerCount := serverCount\n\n\tfor _, server := range cfg.Servers {\n\t\tif server.State == config.StorageServerStateOnline {\n\t\t\tcontinue\n\t\t}\n\t\tif server.State != config.StorageServerStateRIP {\n\t\t\treturn nil, ErrServerStateNotSupported\n\t\t}\n\t\tavailableServerCount--\n\t}\n\tif availableServerCount == 0 {\n\t\treturn nil, ErrNoServersAvailable\n\t}\n\n\tif dialer == nil {\n\t\tdialer = stdConnDialer\n\t}\n\n\treturn &Cluster{\n\t\tservers: cfg.Servers,\n\t\tserverCount: serverCount,\n\t\tavailableServerCount: availableServerCount,\n\t\tdialer: dialer,\n\t}, nil\n}", "func New(conf *liverpc.ClientConfig) *Client {\n\tif conf == nil {\n\t\tconf = &liverpc.ClientConfig{}\n\t}\n\tconf.AppID = DiscoveryAppId\n\tvar realCli = liverpc.NewClient(conf)\n\tcli := &Client{cli: realCli}\n\tcli.clientInit(realCli)\n\treturn cli\n}", "func NewCluster(path string, n int) *Cluster {\n\tc := &Cluster{}\n\n\t// Construct a list of temporary peers.\n\tpeers := make([]string, n)\n\tfor i := range peers {\n\t\tpeers[i] = \"127.0.0.1:0\"\n\t}\n\n\t// Create new stores with temporary peers.\n\tfor i := 0; i < n; i++ {\n\t\tconfig := NewConfig(filepath.Join(path, strconv.Itoa(i)))\n\t\tconfig.Peers = peers\n\t\ts := NewStore(config)\n\t\tc.Stores = append(c.Stores, s)\n\t}\n\n\treturn c\n}", "func New(cfg client.Config) (client.Client, error) {\n\treturn client.New(cfg)\n}", "func NewClient(config *Config) *Client {\n\treturn &Client{\n\t\tchanged: make(chan struct{}),\n\t\tclosing: make(chan struct{}),\n\t\tcacheData: &Data{},\n\t\tlogger: log.New(os.Stderr, \"[metaclient] \", log.LstdFlags),\n\t\tpath: config.Dir,\n\t\tretentionAutoCreate: config.RetentionAutoCreate,\n\t\tconfig: config,\n\t}\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOption) (*Cluster, error) {\n\tif args == nil {\n\t\targs = &ClusterArgs{}\n\t}\n\n\tvar resource Cluster\n\terr := ctx.RegisterRemoteComponentResource(\"eks:index:Cluster\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewCluster(name string, nameSpaces, chartName, chartVersion, values string) (*Cluster, error) {\n\tvar spec MapStringInterface\n\terr := yaml.Unmarshal([]byte(values), &spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcluster := &Cluster{\n\t\tUuid: uuid.NewV4().String(),\n\t\tName: name,\n\t\tNameSpace: nameSpaces,\n\t\tRevision: 0,\n\t\tStatus: ClusterStatusPending,\n\t\tChartName: chartName,\n\t\tChartVersion: chartVersion,\n\t\tValues: values,\n\t\tSpec: spec,\n\t}\n\n\treturn cluster, nil\n}", "func newConfig() (*rest.Config, error) {\n // try in cluster config first, it should fail quickly on lack of env vars\n cfg, err := inClusterConfig()\n if err != nil {\n cfg, err = clientcmd.BuildConfigFromFlags(\"\", clientcmd.RecommendedHomeFile)\n if err != nil {\n return nil, errors.Wrap(err, \"failed to get InClusterConfig and Config from kube_config\")\n }\n }\n return cfg, nil\n}", "func NewCluster(closing chan bool) *Cluster {\n\tcluster := &Cluster{\n\t\tname: getLocalPeerName(),\n\t\tactions: make(chan func()),\n\t\tclosing: closing,\n\t\tstate: newSubscriptionState(),\n\t\tmembers: new(sync.Map),\n\t}\n\n\t// Get the cluster binding address\n\tlistenAddr, err := parseAddr(config.Conf.Broker.Cluster.ListenAddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Get the advertised address\n\tadvertiseAddr, err := parseAddr(config.Conf.Broker.Cluster.AdvertiseAddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create a new router\n\trouter, err := mesh.NewRouter(mesh.Config{\n\t\tHost: listenAddr.IP.String(),\n\t\tPort: listenAddr.Port,\n\t\tProtocolMinVersion: mesh.ProtocolMinVersion,\n\t\tPassword: []byte(config.Conf.Broker.Cluster.Passphrase),\n\t\tConnLimit: 128,\n\t\tPeerDiscovery: true,\n\t\tTrustedSubnets: []*net.IPNet{},\n\t}, cluster.name, advertiseAddr.String(), mesh.NullOverlay{}, logging.Discard)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create a new gossip layer\n\tgossip, err := router.NewGossip(\"cluster\", cluster)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//Store the gossip and the router\n\tcluster.gossip = gossip\n\tcluster.router = router\n\treturn cluster\n}", "func New(ctx context.Context, tenantClusterKubernetesClient tenantcluster.Client) (Client, error) {\n\treturnedSecret, err := tenantClusterKubernetesClient.GetSecret(ctx, defaultCredentialsSecretSecretName, defaultCredentialsSecretSecretNamespace)\n\tif err != nil {\n\t\tif apimachineryerrors.IsNotFound(err) {\n\t\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %s/%s: %v not found\", defaultCredentialsSecretSecretNamespace, defaultCredentialsSecretSecretName, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\tplatformCredentials, ok := returnedSecret.Data[platformCredentialsKey]\n\tif !ok {\n\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %v did not contain key %v\",\n\t\t\tdefaultCredentialsSecretSecretName, platformCredentials)\n\t}\n\n\tclientConfig, err := clientcmd.NewClientConfigFromBytes(platformCredentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClientConfig, err := clientConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubernetesClient, err := kubernetes.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{\n\t\tkubernetesClient: kubernetesClient,\n\t\tdynamicClient: dynamicClient,\n\t}, nil\n}", "func NewCluster() *Cluster {\n\treturn &Cluster{}\n}", "func NewCluster() *Cluster {\n\treturn &Cluster{}\n}", "func NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(&configShallowCopy, httpClient)\n}", "func NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\n\tif configShallowCopy.UserAgent == \"\" {\n\t\tconfigShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\n\t// share the transport between all clients\n\thttpClient, err := rest.HTTPClientFor(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewForConfigAndClient(&configShallowCopy, httpClient)\n}", "func New(cfg *ClientConfig) *Client {\n\treturn &Client{\n\t\tservice: cfg.Service,\n\t\tuser: cfg.User,\n\t}\n}", "func New(c *rest.Config) (*DiscoveryClient, error) {\n\tdc, err := discovery.NewDiscoveryClientForConfig(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DiscoveryClient{\n\t\tDiscoveryInterface: dc,\n\t}, nil\n}", "func New(nodes []string, opts ...Option) (*Client, error) {\n\tvar options Options\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tconf := api.DefaultConfig()\n\n\tconf.Scheme = options.Scheme\n\n\tif len(nodes) > 0 {\n\t\tconf.Address = nodes[0]\n\t}\n\n\ttlsConfig := api.TLSConfig{}\n\tif options.TLS.ClientCert != \"\" && options.TLS.ClientKey != \"\" {\n\t\ttlsConfig.CertFile = options.TLS.ClientCert\n\t\ttlsConfig.KeyFile = options.TLS.ClientKey\n\t}\n\n\tif options.TLS.ClientCaKeys != \"\" {\n\t\ttlsConfig.CAFile = options.TLS.ClientCaKeys\n\t}\n\n\tconf.TLSConfig = tlsConfig\n\n\tclient, err := api.NewClient(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{client.KV()}, nil\n}", "func New(ctx context.Context, config Config) (*Client, error) {\n\terr := config.checkAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tc := &Client{Config: config}\n\tclient, err := c.connect(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tc.client = client\n\tc.addTerminationHandler()\n\treturn c, nil\n}", "func NewCluster() *Cluster {\n\treturn &Cluster{proxies: make(map[string]*httputil.ReverseProxy)}\n}", "func NewCluster(ctx context.Context, o Options) (cluster *Cluster, err error) {\n\tif err := o.applyDefaults(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to apply defaults to options: %w\", err)\n\t}\n\n\tcontainer, err := k3s.RunContainer(ctx)\n\tdefer func() {\n\t\t// We don't want to leak the cluster here, and we can't really be sure how\n\t\t// many resources exist, even if ClusterRun fails. If we never set our\n\t\t// cluster return argument, we'll delete the k3s cluster. This also\n\t\t// gracefully handles panics.\n\t\tif cluster == nil && container != nil {\n\t\t\t_ = container.Terminate(ctx)\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to run cluster: %w\", err)\n\t}\n\n\trawConfig, err := container.GetKubeConfig(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get kubeconfig: %w\", err)\n\t}\n\trestCfg, err := clientcmd.RESTConfigFromKubeConfig(rawConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse kubeconfig: %w\", err)\n\t}\n\n\tkubeClient, err := client.New(restCfg, client.Options{\n\t\tScheme: o.Scheme,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate client: %w\", err)\n\t}\n\n\treturn &Cluster{\n\t\tk3sContainer: container,\n\t\trestConfig: restCfg,\n\t\tkubeClient: kubeClient,\n\t}, nil\n}", "func newRESTClusterService(hostPortStr string) clusterService {\n\treturn clusterService(\n\t\tnewRESTDiscoveryService(fmt.Sprintf(cdsRestEndpointTemplate, hostPortStr)),\n\t)\n}", "func (af *flight) NewCluster(rconf *platform.RuntimeConfig) (platform.Cluster, error) {\n\tbc, err := platform.NewBaseCluster(af.BaseFlight, rconf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tac := &cluster{\n\t\tBaseCluster: bc,\n\t\tflight: af,\n\t}\n\n\tif !rconf.NoSSHKeyInMetadata {\n\t\tac.sshKey = af.SSHKey\n\t}\n\n\tac.ResourceGroup, err = af.api.CreateResourceGroup(\"kola-cluster\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tac.StorageAccount, err = af.api.CreateStorageAccount(ac.ResourceGroup)\n\tif err != nil {\n\t\tif e := af.api.TerminateResourceGroup(ac.ResourceGroup); e != nil {\n\t\t\tplog.Errorf(\"Deleting resource group %v: %v\", ac.ResourceGroup, e)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t_, err = af.api.PrepareNetworkResources(ac.ResourceGroup)\n\tif err != nil {\n\t\tif e := af.api.TerminateResourceGroup(ac.ResourceGroup); e != nil {\n\t\t\tplog.Errorf(\"Deleting resource group %v: %v\", ac.ResourceGroup, e)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\taf.AddCluster(ac)\n\n\treturn ac, nil\n}", "func newClient(origin, ignoreDestCSV, excludeSecretsCSV string) (*client, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load in-cluster config: %s\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load clientset: %s\", err)\n\t}\n\n\tsv := strings.Split(ignoreDestCSV, \",\")\n\tignoreDests := map[string]int{\n\t\torigin: 0, // ignore origin\n\t}\n\tfor _, dest := range sv {\n\t\tignoreDests[dest] = 0 // meaningless value\n\t}\n\n\tes := strings.Split(excludeSecretsCSV, \",\")\n\texcludeSecrets := make(map[string]struct{}, len(es))\n\tfor _, secret := range es {\n\t\texcludeSecrets[secret] = struct{}{}\n\t}\n\n\treturn &client{\n\t\tclientset: clientset,\n\t\torigin: origin,\n\t\tignoreDests: ignoreDests,\n\t\texcludeSecrets: excludeSecrets,\n\t}, nil\n}", "func New(config model.Config) (model.Client, error) {\n\tconfig, err := validateConfig(config)\n\tif err != nil {\n\t\tWriteLogFile(err)\n\t\treturn nil, err\n\t}\n\tc := client{config}\n\tconn, err := connect(c.Host) // test connection\n\tif err != nil {\n\t\tWriteLogFile(err)\n\t\treturn nil, err\n\t}\n\tif err = conn.Bind(c.ROUser.Name, c.ROUser.Password); err != nil {\n\t\tWriteLogFile(err)\n\t\treturn nil, err\n\t}\n\tconn.Close()\n\treturn c, err\n}", "func NewCluster(config Config) (*Cluster, error) {\n\tlogger := logrus.New()\n\tlogger.Out = config.LogOutput\n\tlogger.Level = logrus.Level(config.LogLevel)\n\n\tif config.SerfConfig == nil {\n\t\treturn nil, fmt.Errorf(\"Config.SerfConfig cannot be nil\")\n\t}\n\tif config.SerfConfig.EventCh != nil {\n\t\treturn nil, fmt.Errorf(\"SerfConfig.EventCh must be nil (try using Config.SerfEvents instead)\")\n\t}\n\n\tmemberMap := make(map[string]*serf.Member)\n\n\tring := &ring{\n\t\tdistribution: config.PartitionDistribution,\n\t\tpartitionCount: config.Partitions,\n\t\tmembers: make([]*serf.Member, 0, 0),\n\t}\n\n\tserfEvents := make(chan serf.Event, 256)\n\tconfig.SerfConfig.EventCh = serfEvents\n\tnodeSerf, err := serf.Create(config.SerfConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create serf: %v\", err)\n\t}\n\n\texit := make(chan bool)\n\n\tcluster := &Cluster{\n\t\texit: exit,\n\t\tconfig: config,\n\t\tmemberMap: memberMap,\n\t\tring: ring,\n\t\tserfEvents: serfEvents,\n\t\tSerf: nodeSerf,\n\t\tlogger: logger,\n\t}\n\n\treturn cluster, nil\n}", "func NewCluster(name string, newGroup NewGroup, raftBind, raftDir string) *Cluster {\n\tslots := make(map[int]*Slot, SlotNum)\n\tfor i := 0; i < SlotNum; i++ {\n\t\tslots[i] = NewSlot(i, SlotStateOffline, nil, nil)\n\t}\n\treturn &Cluster{\n\t\tname: name,\n\t\tslots: slots,\n\t\tnewGroup: newGroup,\n\t\tgroups: make(map[int]Group),\n\t\traftBind: raftBind,\n\t\traftDir: raftDir,\n\t}\n}", "func New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.autoscalingV1alpha1 = autoscalingv1alpha1.New(c)\n\tcs.clusterV1alpha1 = clusterv1alpha1.New(c)\n\tcs.configV1alpha1 = configv1alpha1.New(c)\n\tcs.networkingV1alpha1 = networkingv1alpha1.New(c)\n\tcs.policyV1alpha1 = policyv1alpha1.New(c)\n\tcs.searchV1alpha1 = searchv1alpha1.New(c)\n\tcs.workV1alpha1 = workv1alpha1.New(c)\n\tcs.workV1alpha2 = workv1alpha2.New(c)\n\n\tcs.DiscoveryClient = discovery.NewDiscoveryClient(c)\n\treturn &cs\n}", "func NewForConfig(config clientcmd.ClientConfig) (client *Client, err error) {\n\tif config == nil {\n\t\t// initialize client-go clients\n\t\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\t\tconfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\t}\n\n\tclient = new(Client)\n\tclient.KubeConfig = config\n\n\tclient.KubeClientConfig, err = client.KubeConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, errorMsg)\n\t}\n\n\tclient.KubeClient, err = kubernetes.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Namespace, _, err = client.KubeConfig.Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.OperatorClient, err = operatorsclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.DynamicClient, err = dynamic.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.appsClient, err = appsclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.serviceCatalogClient, err = servicecatalogclienset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.discoveryClient, err = discovery.NewDiscoveryClientForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.checkIngressSupports = true\n\n\tclient.userClient, err = userclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.projectClient, err = projectclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.routeClient, err = routeclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func NewClient(config *core.Config) (c *Client, err error) {\n\t// create client\n\tc = &Client{\n\t\tconfig: config,\n\t\tdone: make(chan bool, 2),\n\t}\n\n\t// create cipher\n\tif c.cipher, err = core.NewCipher(c.config.Cipher, c.config.Passwd); err != nil {\n\t\tlogln(\"core: failed to initialize cipher:\", err)\n\t\treturn\n\t}\n\n\t// create managed net\n\tif c.net, err = nat.NewNetFromCIDR(DefaultClientSubnet); err != nil {\n\t\tlogln(\"nat: failed to create managed subnet:\", err)\n\t\treturn\n\t}\n\n\t// assign a localIP\n\tif c.localIP, err = c.net.Take(); err != nil {\n\t\tlogln(\"nat: faield to assign a localIP:\", err)\n\t\treturn\n\t}\n\n\treturn\n}", "func NewCluster(contextName string) (*cluster.Cluster, error) {\n\tcfgPath, err := getKubeConfigPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg, err := clientcmd.LoadFromFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot load kubectl config at %q: %w\", cfgPath, err)\n\t}\n\tif contextName == \"\" {\n\t\tcontextName = cfg.CurrentContext\n\t\tlog.Infof(\"Using default kubectl context: %q\", contextName)\n\t}\n\trestClient, err := clientcmd.NewNonInteractiveClientConfig(*cfg, contextName, nil, clientcmd.NewDefaultClientConfigLoadingRules()).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create REST client: %w\", err)\n\t}\n\treturn cluster.New(restClient)\n}", "func New(config *rest.Config, options Options) (c Client, err error) {\n\tc, err = newClient(config, options)\n\tif err == nil && options.DryRun != nil && *options.DryRun {\n\t\tc = NewDryRunClient(c)\n\t}\n\treturn c, err\n}", "func New(kubeConfig *rest.Config, scheme *runtime.Scheme, mapper meta.RESTMapper) (Config, error) {\n\tif kubeConfig == nil {\n\t\treturn nil, errors.NewInputError(\"New config\", \"kubeConfig\", nil)\n\t}\n\n\tif scheme == nil {\n\t\treturn nil, errors.NewInputError(\"New config\", \"scheme\", nil)\n\t}\n\n\tc, err := client.New(kubeConfig, client.Options{\n\t\tScheme: scheme,\n\t\tMapper: mapper,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigMapNamespace := constants.InteroperatorNamespace\n\n\treturn &config{\n\t\tc: c,\n\t\tnamespace: configMapNamespace,\n\t}, nil\n}", "func NewNODES(config configuration.CONFIGURATION) *NODES_IMPL {\r\n client := new(NODES_IMPL)\r\n client.config = config\r\n return client\r\n}", "func New(cfg *Config) *Client {\n\treturn &Client{\n\t\tcfg: cfg,\n\t}\n}", "func New(context *contexter.Context) (*Client) {\n return &Client {\n urlBaseIndex: 0,\n\t\tcontext: context,\n }\n}", "func NewWithConfig(conf Config) (Client, error) {\n\tvar err error\n\tvar c client\n\n\tclusters := strings.Split(conf.Hosts, \",\")\n\tclusterConfig := gocql.NewCluster(clusters...)\n\tclusterConfig.Consistency = gocql.LocalOne\n\tclusterConfig.ProtoVersion = 3\n\tclusterConfig.Keyspace = conf.Keyspace\n\tclusterConfig.Port = conf.Port\n\n\tif c.driver, err = clusterConfig.CreateSession(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func NewClient() (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tinCluster := os.Getenv(\"IN_CLUSTER\")\n\tif inCluster == \"true\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\thome := homedir.HomeDir()\n\t\tp := filepath.Join(home, \".kube\", \"config\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", p)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func NewCluster(sessionManager *SessionManager, channelManager *ChannelManager) *Cluster {\n\tc := &Cluster{\n\t\tsessionManager: sessionManager,\n\t\tchannelManager: channelManager,\n\t}\n\n\treturn c\n}", "func NewCluster() *ClusterBuilder {\n\treturn &ClusterBuilder{}\n}", "func New() *Cluster {\n\treturn &Cluster{\n\t\tmembers: make(map[string]time.Time),\n\t}\n}", "func NewCluster(peers map[uint64]string) *Cluster {\n\treturn &Cluster{\n\t\tmembers: peers,\n\t}\n}", "func New(\n\tnodes node.ServiceNodes,\n\topts Options,\n) (Cluster, error) {\n\tif err := opts.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcluster := &svcCluster{\n\t\tlogger: opts.InstrumentOptions().Logger(),\n\t\topts: opts,\n\t\tknownNodes: nodes,\n\t\tusedNodes: make(idToNodeMap, len(nodes)),\n\t\tspares: make([]node.ServiceNode, 0, len(nodes)),\n\t\tsparesByID: make(map[string]node.ServiceNode, len(nodes)),\n\t\tplacementSvc: opts.PlacementService(),\n\t\tstatus: ClusterStatusUninitialized,\n\t}\n\tcluster.addSparesWithLock(nodes)\n\n\treturn cluster, nil\n}", "func NewCluster(opts Options) *Cluster {\n\topts.setDefaults()\n\n\tq := &Cluster{\n\t\tweb: opts.Web,\n\t\tsetups: map[int]setup{},\n\t\tkeys: nil,\n\t\tcfg: opts.Config,\n\t\tcdnCfg: opts.CDNConfig,\n\t\tdomains: map[int]string{},\n\t\tready: tdsync.NewReady(),\n\t\tcommon: tgtest.NewDispatcher(),\n\t\tlog: opts.Logger,\n\t\trandom: opts.Random,\n\t\tprotocol: opts.Protocol,\n\t}\n\tconfig.NewService(&q.cfg, &q.cdnCfg).Register(q.common)\n\tq.common.Fallback(q.fallback())\n\n\treturn q\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOption) (*Cluster, error) {\n\tif args == nil {\n\t\targs = &ClusterArgs{}\n\t}\n\n\tvar resource Cluster\n\terr := ctx.RegisterResource(\"aws:elasticache/cluster:Cluster\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewClient(logger log.Logger) (Client, error) {\n\tclient, err := k8s.NewInClusterClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k8sclient{\n\t\tclient: client,\n\t\tlogger: logger,\n\t}, nil\n}", "func New(kubeconfig string) (*Instance, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\n\tif len(kubeconfig) > 0 {\n\t\tlogrus.Debugf(\"using kubeconfig: %s to create k8s client\", kubeconfig)\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tlogrus.Debugf(\"will use in-cluster config to create k8s client\")\n\t\tcfg, err = rest.InClusterConfig()\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Instance{\n\t\tkubeClient: kubeClient,\n\t\tk8sOps: core.Instance(),\n\t}, nil\n}", "func NewCluster() *Cluster {\n\tthis := Cluster{}\n\treturn &this\n}", "func NewClient(host, token, nodeName string, insecure, UseAPIOnCacheIssues bool) (*Client, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif host != \"\" && token != \"\" {\n\t\tconfig = &rest.Config{\n\t\t\tHost: host,\n\t\t\tBearerToken: token,\n\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\tInsecure: insecure,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{Clientset: client, nodeName: nodeName, useAPIOnCacheIssues: UseAPIOnCacheIssues}, nil\n}", "func New(base string) *Client {\n\n\tLogger.Debug(\"Creating Marathon Client with baseURL = %s\", base)\n\tbaseURL, err := url.Parse(base)\n\tif len(base) == 0 || err != nil {\n\t\tLogger.Debug(\"Invalid baseURL\")\n\t\treturn nil\n\t}\n\n\t_client := &Client{}\n\treturn _client.New(baseURL)\n}", "func (c *Config) New() (*vela.Client, error) {\n\tlogrus.Trace(\"creating new Vela client from plugin configuration\")\n\n\t// create the app string\n\tappID := fmt.Sprintf(\"%s; %s\", c.AppName, c.AppVersion)\n\n\t// create Vela client from configuration\n\tclient, err := vela.NewClient(c.Server, appID, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check if a token is provided for authentication\n\tif len(c.Token) > 0 {\n\t\tlogrus.Debugf(\"setting authentication token for Vela\")\n\n\t\t// set the token for authentication in the Vela client\n\t\tclient.Authentication.SetPersonalAccessTokenAuth(c.Token)\n\t}\n\n\treturn client, nil\n}", "func New(t time.Duration, inCluster bool) (*KubeAPI, error) {\n\tvar api KubeAPI\n\tapi.Timeout = t\n\tapi.InCluster = inCluster\n\tvar err error\n\n\tif api.InCluster {\n\t\tapi.Config, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn &api, err\n\t\t}\n\t} else {\n\t\tkubeconfig := filepath.Join(homeDir(), \".kube\", \"config\")\n\t\tapi.Config, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\n\tapi.Client, err = kubernetes.NewForConfig(api.Config)\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\treturn &api, nil\n}", "func newKrakenClusters(c *SamsungV1alpha1Client, namespace string) *krakenClusters {\n\treturn &krakenClusters{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrapper, error) {\n\tif endpoint == \"\" {\n\t\treturn nil, errors.New(\"endpoint missing for external cluster client\")\n\t}\n\n\tconfig := &rest.Config{\n\t\tHost: endpoint,\n\t\tBearerToken: token,\n\t}\n\n\tif caFilePath != \"\" {\n\t\tcaData, err := os.ReadFile(caFilePath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read CA file %s: %w\", caFilePath, err)\n\t\t}\n\n\t\tconfig.TLSClientConfig = rest.TLSClientConfig{CAData: caData}\n\t}\n\n\treturn createClientFromConfig(config)\n}", "func NewCluster(hosts []string, opts ...WrapOption) *ClusterConfig {\n\treturn &ClusterConfig{\n\t\tClusterConfig: gocql.NewCluster(hosts...),\n\t\thosts: hosts,\n\t\topts: opts,\n\t}\n}", "func (c *ClustersController) Create(ctx *app.CreateClustersContext) error {\n\tclustr := repository.Cluster{\n\t\tName: ctx.Payload.Data.Name,\n\t\tType: ctx.Payload.Data.Type,\n\t\tURL: ctx.Payload.Data.APIURL,\n\t\tAppDNS: ctx.Payload.Data.AppDNS,\n\t\tSAToken: ctx.Payload.Data.ServiceAccountToken,\n\t\tSAUsername: ctx.Payload.Data.ServiceAccountUsername,\n\t\tAuthClientID: ctx.Payload.Data.AuthClientID,\n\t\tAuthClientSecret: ctx.Payload.Data.AuthClientSecret,\n\t\tAuthDefaultScope: ctx.Payload.Data.AuthClientDefaultScope,\n\t}\n\tif ctx.Payload.Data.ConsoleURL != nil {\n\t\tclustr.ConsoleURL = *ctx.Payload.Data.ConsoleURL\n\t}\n\tif ctx.Payload.Data.LoggingURL != nil {\n\t\tclustr.LoggingURL = *ctx.Payload.Data.LoggingURL\n\t}\n\tif ctx.Payload.Data.MetricsURL != nil {\n\t\tclustr.MetricsURL = *ctx.Payload.Data.MetricsURL\n\t}\n\tif ctx.Payload.Data.CapacityExhausted != nil {\n\t\tclustr.CapacityExhausted = *ctx.Payload.Data.CapacityExhausted\n\t}\n\tif ctx.Payload.Data.TokenProviderID != nil {\n\t\tclustr.TokenProviderID = *ctx.Payload.Data.TokenProviderID\n\t}\n\tclusterSvc := c.app.ClusterService()\n\terr := clusterSvc.CreateOrSaveCluster(ctx, &clustr)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"error\": err,\n\t\t}, \"error while creating new cluster configuration\")\n\t\treturn app.JSONErrorResponse(ctx, err)\n\t}\n\tctx.ResponseData.Header().Set(\"Location\", app.ClustersHref(clustr.ClusterID.String()))\n\treturn ctx.Created()\n}", "func NewCluster(n int) Cluster {\n\tcs := make([]*Node, 0, n)\n\tpeers := make([]string, 0, n)\n\n\tport := 26257\n\thttp := 8080\n\tfor i := 0; i < n; i++ {\n\t\taddr := net.JoinHostPort(\"localhost\", strconv.Itoa(port+i))\n\t\tpeers = append(peers, addr)\n\t\tcs = append(cs, &Node{\n\t\t\tID: strconv.Itoa(i + 1),\n\t\t\tAddr: addr,\n\t\t\tHttpaddr: net.JoinHostPort(\"localhost\", strconv.Itoa(http+i)),\n\t\t})\n\t}\n\tfor i := range cs {\n\t\tcs[i].Peers = peers\n\t}\n\treturn cs\n}", "func New(c rest.Interface) *ConfigV1Client {\n\treturn &ConfigV1Client{c}\n}", "func (api *clusterAPI) Create(obj *cluster.Cluster) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Cluster().Create(context.Background(), obj)\n\t\tif err != nil && strings.Contains(err.Error(), \"AlreadyExists\") {\n\t\t\t_, err = apicl.ClusterV1().Cluster().Update(context.Background(), obj)\n\n\t\t}\n\t\treturn err\n\t}\n\n\tapi.ct.handleClusterEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Created})\n\treturn nil\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}", "func NewClient(config ClientConfig) (Client, error) {\n\tvar restConfig *rest.Config\n\tif config.Server == \"\" && config.Kubeconfig == \"\" {\n\t\t// If no API server address or kubeconfig was provided, assume we are running\n\t\t// inside a pod. Try to connect to the API server through its\n\t\t// Service environment variables, using the default Service\n\t\t// Account Token.\n\t\tvar err error\n\t\tif restConfig, err = rest.InClusterConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tvar err error\n\t\trestConfig, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: config.Kubeconfig},\n\t\t\t&clientcmd.ConfigOverrides{\n\t\t\t\tAuthInfo: clientcmdapi.AuthInfo{\n\t\t\t\t\tClientCertificate: config.ClientCertificate,\n\t\t\t\t\tClientKey: config.ClientKey,\n\t\t\t\t\tToken: config.Token,\n\t\t\t\t\tUsername: config.Username,\n\t\t\t\t\tPassword: config.Password,\n\t\t\t\t},\n\t\t\t\tClusterInfo: clientcmdapi.Cluster{\n\t\t\t\t\tServer: config.Server,\n\t\t\t\t\tInsecureSkipTLSVerify: config.Insecure,\n\t\t\t\t\tCertificateAuthority: config.CertificateAuthority,\n\t\t\t\t},\n\t\t\t\tContext: clientcmdapi.Context{\n\t\t\t\t\tCluster: config.Cluster,\n\t\t\t\t\tAuthInfo: config.User,\n\t\t\t\t},\n\t\t\t\tCurrentContext: config.Context,\n\t\t\t},\n\t\t).ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Infof(\"kubernetes: targeting api server %s\", restConfig.Host)\n\n\tc, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsc, err := snapshot.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmc, err := mayaclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcsc, err := csisnapshot.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc, err := cstorclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &client{\n\t\tquit: make(chan struct{}),\n\t\tclient: c,\n\t\tsnapshotClient: sc,\n\t\tmayaClient: mc,\n\t\tcsiSnapshotClient: csc,\n\t\tcstorClient: cc,\n\t}\n\n\tresult.podStore = NewEventStore(result.triggerPodWatches, cache.MetaNamespaceKeyFunc)\n\tresult.runReflectorUntil(\"pods\", result.podStore)\n\n\tresult.serviceStore = result.setupStore(\"services\")\n\tresult.nodeStore = result.setupStore(\"nodes\")\n\tresult.namespaceStore = result.setupStore(\"namespaces\")\n\tresult.deploymentStore = result.setupStore(\"deployments\")\n\tresult.daemonSetStore = result.setupStore(\"daemonsets\")\n\tresult.jobStore = result.setupStore(\"jobs\")\n\tresult.statefulSetStore = result.setupStore(\"statefulsets\")\n\tresult.cronJobStore = result.setupStore(\"cronjobs\")\n\tresult.persistentVolumeStore = result.setupStore(\"persistentvolumes\")\n\tresult.persistentVolumeClaimStore = result.setupStore(\"persistentvolumeclaims\")\n\tresult.storageClassStore = result.setupStore(\"storageclasses\")\n\tresult.volumeSnapshotStore = result.setupStore(\"volumesnapshots\")\n\tresult.volumeSnapshotDataStore = result.setupStore(\"volumesnapshotdatas\")\n\tresult.diskStore = result.setupStore(\"disks\")\n\tresult.storagePoolClaimStore = result.setupStore(\"storagepoolclaims\")\n\tresult.cStorvolumeStore = result.setupStore(\"cstorvolumes\")\n\tresult.cStorvolumeReplicaStore = result.setupStore(\"cstorvolumereplicas\")\n\tresult.cStorPoolStore = result.setupStore(\"cstorpools\")\n\tresult.blockDeviceStore = result.setupStore(\"blockdevices\")\n\tresult.blockDeviceClaimStore = result.setupStore(\"blockdeviceclaims\")\n\tresult.cStorPoolClusterStore = result.setupStore(\"cstorpoolclusters\")\n\tresult.cStorPoolInstanceStore = result.setupStore(\"cstorpoolinstances\")\n\tresult.csiVolumeSnapshotStore = result.setupStore(\"csivolumesnapshots\")\n\tresult.volumeSnapshotClassStore = result.setupStore(\"volumesnapshotclasses\")\n\tresult.volumeSnapshotContentStore = result.setupStore(\"volumesnapshotcontents\")\n\n\treturn result, nil\n}", "func (a ClustersAPI) Create(cluster httpmodels.CreateReq) (httpmodels.CreateResp, error) {\n\tvar createResp httpmodels.CreateResp\n\n\tresp, err := a.Client.performQuery(http.MethodPost, \"/clusters/create\", cluster, nil)\n\tif err != nil {\n\t\treturn createResp, err\n\t}\n\n\terr = json.Unmarshal(resp, &createResp)\n\treturn createResp, err\n}", "func New(cfg Config) (*Client, error) {\n\tif cfg.Transport == nil {\n\t\tcfg.Transport = http.DefaultTransport\n\t}\n\n\tif cfg.CACert != nil {\n\t\thttpTransport, ok := cfg.Transport.(*http.Transport)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unable to set CA certificate for transport of type %T\", cfg.Transport)\n\t\t}\n\n\t\thttpTransport = httpTransport.Clone()\n\t\thttpTransport.TLSClientConfig.RootCAs = x509.NewCertPool()\n\n\t\tif ok := httpTransport.TLSClientConfig.RootCAs.AppendCertsFromPEM(cfg.CACert); !ok {\n\t\t\treturn nil, errors.New(\"unable to add CA certificate\")\n\t\t}\n\n\t\tcfg.Transport = httpTransport\n\t}\n\n\tif len(cfg.RetryOnStatus) == 0 {\n\t\tcfg.RetryOnStatus = defaultRetryOnStatus[:]\n\t}\n\n\tif cfg.MaxRetries == 0 {\n\t\tcfg.MaxRetries = defaultMaxRetries\n\t}\n\n\tvar conns []*Connection\n\tfor _, u := range cfg.URLs {\n\t\tconns = append(conns, &Connection{URL: u})\n\t}\n\n\tclient := Client{\n\t\turls: cfg.URLs,\n\t\tusername: cfg.Username,\n\t\tpassword: cfg.Password,\n\t\theader: cfg.Header,\n\n\t\tsigner: cfg.Signer,\n\n\t\tretryOnStatus: cfg.RetryOnStatus,\n\t\tdisableRetry: cfg.DisableRetry,\n\t\tenableRetryOnTimeout: cfg.EnableRetryOnTimeout,\n\t\tmaxRetries: cfg.MaxRetries,\n\t\tretryBackoff: cfg.RetryBackoff,\n\t\tdiscoverNodesInterval: cfg.DiscoverNodesInterval,\n\n\t\tcompressRequestBody: cfg.CompressRequestBody,\n\n\t\ttransport: cfg.Transport,\n\t\tlogger: cfg.Logger,\n\t\tselector: cfg.Selector,\n\t\tpoolFunc: cfg.ConnectionPoolFunc,\n\t}\n\n\tif client.poolFunc != nil {\n\t\tclient.pool = client.poolFunc(conns, client.selector)\n\t} else {\n\t\tclient.pool, _ = NewConnectionPool(conns, client.selector)\n\t}\n\n\tif cfg.EnableDebugLogger {\n\t\tdebugLogger = &debuggingLogger{Output: os.Stdout}\n\t}\n\n\tif cfg.EnableMetrics {\n\t\tclient.metrics = &metrics{responses: make(map[int]int)}\n\t\t// TODO(karmi): Type assertion to interface\n\t\tif pool, ok := client.pool.(*singleConnectionPool); ok {\n\t\t\tpool.metrics = client.metrics\n\t\t}\n\t\tif pool, ok := client.pool.(*statusConnectionPool); ok {\n\t\t\tpool.metrics = client.metrics\n\t\t}\n\t}\n\n\tif client.discoverNodesInterval > 0 {\n\t\ttime.AfterFunc(client.discoverNodesInterval, func() {\n\t\t\tclient.scheduleDiscoverNodes(client.discoverNodesInterval)\n\t\t})\n\t}\n\n\treturn &client, nil\n}", "func New(appName string) (Client, error) {\n\tvar c Config\n\tvar err error\n\n\tif err = config.ParseEnv(appName, &c); err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithConfig(c)\n}", "func FromKubeConfig(ctx context.Context, kubeConfigList, contextName string, initialNamespace string, options RESTConfigOptions) (*Cluster, error) {\n\tchain := strings.Deduplicate(filepath.SplitList(kubeConfigList))\n\n\trules := &clientcmd.ClientConfigLoadingRules{\n\t\tPrecedence: chain,\n\t}\n\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif contextName != \"\" {\n\t\toverrides.CurrentContext = contextName\n\t}\n\tcc := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n\tconfig, err := cc.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar defaultNamespace string\n\n\tif initialNamespace == \"\" {\n\t\tdefaultNamespace, _, err = cc.Namespace()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdefaultNamespace = initialNamespace\n\t}\n\n\tlogger := internalLog.From(ctx)\n\tlogger.With(\"client-qps\", options.QPS, \"client-burst\", options.Burst).\n\t\tDebugf(\"initializing REST client configuration\")\n\n\tconfig = withConfigDefaults(config, options)\n\n\treturn newCluster(ctx, cc, config, defaultNamespace)\n}", "func Client() (*Cluster, error) {\n\trestConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttprclient, err := k8s.TPRClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Cluster{Interface: clientset, TPRClient: tprclient}, nil\n}", "func NewClusterClient(conf config.Config) (Client, error) {\n\tname := \"ecs\"\n\tif conf.IsSet(\"cluster_client\") {\n\t\tname = conf.GetString(\"cluster_client\")\n\t}\n\n\tswitch name {\n\tcase \"ecs\":\n\t\tecsc := &ECSClusterClient{}\n\t\tif err := ecsc.Initialize(conf); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"problem initializing ECSClusterClient\")\n\t\t}\n\t\treturn ecsc, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"No Client named [%s] was found\", name)\n\t}\n}", "func New(urls []string, prefix string) *Client {\n\treturn &Client{prefix + routesPath, etcd.NewClient(urls), 0}\n}", "func New(httpClient *http.Client, config Config) (*Client, error) {\n\tc := NewClient(httpClient)\n\tc.Config = config\n\n\tbaseURL, err := url.Parse(\"https://\" + config.Host)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.BaseURL = baseURL\n\treturn c, nil\n}", "func NewClient(config *Config) Client {\n\tendpoint := net.JoinHostPort(config.Hostname, strconv.Itoa(config.port()))\n\tif !strings.Contains(endpoint, \"//\") {\n\t\tendpoint = \"http://\" + endpoint\n\t}\n\n\topts := &jsonrpc.RPCClientOpts{\n\t\tCustomHeaders: map[string]string{\n\t\t\t\"Authorization\": \"Basic \" + base64.StdEncoding.EncodeToString([]byte(config.Username+\":\"+config.Password)),\n\t\t},\n\t}\n\n\treturn &client{\n\t\tRPCClient: jsonrpc.NewClientWithOpts(endpoint, opts),\n\t}\n}", "func NewForConfig(c *rest.Config) (*Clientset, error) {\n\tconfigShallowCopy := *c\n\tif configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {\n\t\tconfigShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)\n\t}\n\tvar cs Clientset\n\tvar err error\n\tcs.agentV1alpha1, err = agentv1alpha1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcs.pipelineV1alpha1, err = pipelinev1alpha1.NewForConfig(&configShallowCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to create the DiscoveryClient: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn &cs, nil\n}", "func NewClusterClient(hosts healthcheck.List, config *tls.Config) Client {\n\treturn &clusterClient{hosts, config}\n}", "func NewClient(log logr.Logger, config *rest.Config) (*Client, error) {\n\tdiscoveryClient, err := discovery.NewDiscoveryClientForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{\n\t\tdiscovery: discoveryClient,\n\t\tlog: log,\n\t\ttimeout: defaultTimeout,\n\t}, nil\n}", "func NewClient(kubeconfig, configContext string) (*Client, error) {\n\tconfig, err := defaultRestConfig(kubeconfig, configContext)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClient, err := rest.RESTClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{config, restClient}, nil\n}" ]
[ "0.69069743", "0.6764772", "0.6615479", "0.65609705", "0.65607715", "0.65508825", "0.6533828", "0.65318906", "0.6451317", "0.64191175", "0.63777333", "0.63484955", "0.6340651", "0.6332518", "0.63142836", "0.630872", "0.6305923", "0.62963", "0.6283601", "0.6281496", "0.6268112", "0.62440073", "0.62429357", "0.6237434", "0.6230555", "0.620241", "0.6179988", "0.6176131", "0.617178", "0.61522084", "0.61399895", "0.61156946", "0.61041397", "0.61001545", "0.6095836", "0.60731494", "0.607129", "0.607129", "0.6060129", "0.6060129", "0.6054413", "0.60529894", "0.6035807", "0.60347366", "0.6031195", "0.6023469", "0.60223424", "0.60146457", "0.6012098", "0.6005632", "0.6003259", "0.59978575", "0.59909135", "0.598721", "0.5986499", "0.59802085", "0.59775925", "0.5968567", "0.59624755", "0.5958557", "0.59377253", "0.5930312", "0.59299505", "0.59244156", "0.59216905", "0.59197354", "0.5918647", "0.59052956", "0.5900108", "0.58988446", "0.58969426", "0.5894204", "0.5891151", "0.5890853", "0.58876866", "0.5881868", "0.588161", "0.58803093", "0.58715683", "0.58644974", "0.58636856", "0.5852649", "0.58524776", "0.5851195", "0.5849064", "0.58459735", "0.584524", "0.58407575", "0.58370113", "0.583614", "0.58359426", "0.5826454", "0.5826108", "0.58246297", "0.5818693", "0.58162796", "0.58152133", "0.58136535", "0.5798913", "0.5789009" ]
0.7721838
0
CreateDaemonset creates a daemonset with default options.
func (c *Cluster) CreateDaemonset(ctx context.Context, ds *appsv1.DaemonSet) (*appsv1.DaemonSet, error) { if ds.GetObjectMeta().GetNamespace() == "" { ds.SetNamespace(NamespaceDefault) } return c.client.AppsV1().DaemonSets(ds.GetNamespace()).Create(ctx, ds, v1.CreateOptions{}) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateDaemonSet(client *rancher.Client, clusterName, daemonSetName, namespace string, template corev1.PodTemplateSpec) (*appv1.DaemonSet, error) {\n\tdynamicClient, err := client.GetDownStreamClusterClient(clusterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabels := map[string]string{}\n\tlabels[\"workload.user.cattle.io/workloadselector\"] = fmt.Sprintf(\"apps.daemonset-%v-%v\", namespace, daemonSetName)\n\n\ttemplate.ObjectMeta = metav1.ObjectMeta{\n\t\tLabels: labels,\n\t}\n\ttemplate.Spec.RestartPolicy = corev1.RestartPolicyAlways\n\tdaemonSet := &appv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: daemonSetName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: template,\n\t\t},\n\t}\n\n\tdaemonSetResource := dynamicClient.Resource(DaemonSetGroupVersionResource).Namespace(namespace)\n\n\tunstructuredResp, err := daemonSetResource.Create(context.TODO(), unstructured.MustToUnstructured(daemonSet), metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewDaemonSet := &appv1.DaemonSet{}\n\terr = scheme.Scheme.Convert(unstructuredResp, newDaemonSet, unstructuredResp.GroupVersionKind())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn daemonSet, nil\n}", "func CreateDaemonSet(name string) *appsv1.DaemonSet {\n\tmaxUnavailable := intstr.FromInt(1)\n\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: genTypeMeta(gvk.DaemonSet),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tRevisionHistoryLimit: conversion.PtrInt32(10),\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tStatus: appsv1.DaemonSetStatus{\n\t\t\tCurrentNumberScheduled: 1,\n\t\t\tDesiredNumberScheduled: 1,\n\t\t\tNumberAvailable: 1,\n\t\t\tNumberReady: 1,\n\t\t\tUpdatedNumberScheduled: 1,\n\t\t},\n\t}\n}", "func createDaemonSet(client k8sclient.Interface, module *protos.Module) error {\n\tdsConfig := createDaemonSetObject(module)\n\td, err := client.ExtensionsV1beta1().DaemonSets(defaultNS).Create(dsConfig)\n\tif err == nil {\n\t\tlog.Infof(\"Created DaemonSet %+v\", d)\n\t} else if errors.IsAlreadyExists(err) {\n\t\tlog.Infof(\"DaemonSet %+v already exists\", dsConfig)\n\t} else {\n\t\tlog.Errorf(\"Failed to create DaemonSet %+v with error: %v\", dsConfig, err)\n\t}\n\n\treturn err\n}", "func CreateOrUpdateDaemonSet(client clientset.Interface, ds *extensions.DaemonSet) error {\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Create(ds); err != nil {\n if !apierrors.IsAlreadyExists(err) {\n return fmt.Errorf(\"unable to create daemonset: %v\", err)\n }\n\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Update(ds); err != nil {\n return fmt.Errorf(\"unable to update daemonset: %v\", err)\n }\n }\n return nil\n}", "func CreateDaemonSet(client kubernetes.Interface, daemonsetName string, namespace string) (*v1beta1.DaemonSet, error) {\n\tlogrus.Infof(\"Creating DaemonSet\")\n\tdaemonsetClient := client.ExtensionsV1beta1().DaemonSets(namespace)\n\tdaemonset, err := daemonsetClient.Create(GetDaemonSet(namespace, daemonsetName))\n\ttime.Sleep(10 * time.Second)\n\treturn daemonset, err\n}", "func CreateDaemonSet(daemonSetName, namespace, containerName, imageWithVersion string, timeout time.Duration) (*v1core.PodList, error) {\n\n\trebootDaemonSet := createDaemonSetsTemplate(daemonSetName, namespace, containerName, imageWithVersion)\n\n\tif doesDaemonSetExist(daemonSetName, namespace) {\n\t\terr := DeleteDaemonSet(daemonSetName, namespace)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to delete %s daemonset because: %s\", daemonSetName, err)\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Creating daemonset %s\", daemonSetName)\n\t_, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Create(context.TODO(), rebootDaemonSet, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = WaitDaemonsetReady(namespace, daemonSetName, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Deamonset is ready\")\n\n\tvar ptpPods *v1core.PodList\n\tptpPods, err = daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\tif err != nil {\n\t\treturn ptpPods, err\n\t}\n\tlogrus.Infof(\"Successfully created daemonset %s\", daemonSetName)\n\treturn ptpPods, nil\n}", "func createDaemonSetObject(cr *hostpathprovisionerv1alpha1.HostPathProvisioner, provisionerImage, namespace string) *appsv1.DaemonSet {\n\tvolumeType := corev1.HostPathDirectoryOrCreate\n\tlabels := map[string]string{\n\t\t\"k8s-app\": cr.Name,\n\t}\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"DaemonSet\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": cr.Name,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tServiceAccountName: cr.Name + \"-admin\",\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: cr.Name,\n\t\t\t\t\t\t\tImage: provisionerImage,\n\t\t\t\t\t\t\tImagePullPolicy: cr.Spec.ImagePullPolicy,\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"USE_NAMING_PREFIX\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.UseNamingPrefix,\n\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\t\tName: \"NODE_NAME\",\n\t\t\t\t\t\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\t\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\t\t\t\t\t\tFieldPath: \"spec.nodeName\",\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\t{\n\t\t\t\t\t\t\t\t\tName: \"PV_DIR\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"pv-volume\",\n\t\t\t\t\t\t\t\t\tMountPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTerminationMessagePath: \"/dev/termination-log\",\n\t\t\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"pv-volume\", // Has to match VolumeMounts in containers\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\tPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t\tType: &volumeType,\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 makeDaemonsets(dsc *Checker, orphan bool) error {\n\n\tif orphan {\n\t\tdsc.hostname = \"ORPHANED-TEST\"\n\t}\n\n\tcheckRunTime := strconv.Itoa(int(CheckRunTime))\n\thostname := getHostname()\n\n\tterminationGracePeriod := int64(1)\n\ttestDS := Checker{\n\t\tNamespace: Namespace,\n\t\tDaemonSetName: daemonSetBaseName + \"-\" + hostname + \"-\" + checkRunTime,\n\t\thostname: hostname,\n\t}\n\n\ttestDS.DaemonSet = &appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: testDS.DaemonSetName,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t\t\t},\n\t\t\t\t\tName: testDS.DaemonSetName,\n\t\t\t\t},\n\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\tTerminationGracePeriodSeconds: &terminationGracePeriod,\n\t\t\t\t\tTolerations: []apiv1.Toleration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"node-role.kubernetes.io/master\",\n\t\t\t\t\t\t\tEffect: \"NoSchedule\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContainers: []apiv1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"sleep\",\n\t\t\t\t\t\t\tImage: \"gcr.io/google_containers/pause:0.8.0\",\n\t\t\t\t\t\t\tResources: apiv1.ResourceRequirements{\n\t\t\t\t\t\t\t\tRequests: apiv1.ResourceList{\n\t\t\t\t\t\t\t\t\tapiv1.ResourceCPU: resource.MustParse(\"0\"),\n\t\t\t\t\t\t\t\t\tapiv1.ResourceMemory: resource.MustParse(\"0\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tdaemonSetClient := dsc.getDaemonSetClient()\n\t_, err := daemonSetClient.Create(testDS.DaemonSet)\n\treturn err\n}", "func NewDaemonSetControl(config DSConfig) (*DSControl, error) {\n\terr := config.checkAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &DSControl{\n\t\tDSConfig: config,\n\t\tFieldLogger: log.WithFields(log.Fields{\n\t\t\t\"daemonset\": formatMeta(config.ObjectMeta),\n\t\t}),\n\t}, nil\n}", "func (r *reconciler) createLogsDaemonSet(\n\tctx context.Context,\n\tl log.Logger,\n\td config.Deployment,\n\ts assets.SecretStore,\n) error {\n\tname := fmt.Sprintf(\"%s-logs\", d.Agent.Name)\n\tds, err := generateLogsDaemonSet(r.config, name, d)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate DaemonSet: %w\", err)\n\t}\n\tkey := types.NamespacedName{Namespace: ds.Namespace, Name: ds.Name}\n\n\tif len(d.Logs) == 0 {\n\n\t\tvar ds apps_v1.DaemonSet\n\t\terr := r.Client.Get(ctx, key, &ds)\n\t\tif k8s_errors.IsNotFound(err) || !isManagedResource(&ds) {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn fmt.Errorf(\"failed to find stale DaemonSet %s: %w\", key, err)\n\t\t}\n\n\t\terr = r.Client.Delete(ctx, &ds)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete stale DaemonSet %s: %w\", key, err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlevel.Info(l).Log(\"msg\", \"reconciling logs daemonset\", \"ds\", key)\n\terr = clientutil.CreateOrUpdateDaemonSet(ctx, r.Client, ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to reconcile statefulset governing service: %w\", err)\n\t}\n\treturn nil\n}", "func (c *Vrouter) CreateDS(ds *appsv1.DaemonSet,\n\tcommonConfiguration *PodConfiguration,\n\tinstanceType string,\n\trequest reconcile.Request,\n\tscheme *runtime.Scheme,\n\treconcileClient client.Client) error {\n\tfoundDS := &appsv1.DaemonSet{}\n\terr := reconcileClient.Get(context.TODO(), types.NamespacedName{Name: request.Name + \"-\" + instanceType + \"-daemonset\", Namespace: request.Namespace}, foundDS)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\tds.Spec.Template.ObjectMeta.Labels[\"version\"] = \"1\"\n\t\t\terr = reconcileClient.Create(context.TODO(), ds)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (c *component) daemonset() *appsv1.DaemonSet {\n\tmaxUnavailable := intstr.FromInt(1)\n\n\tannots := map[string]string{}\n\n\tif c.config.envoyConfigMap != nil {\n\t\tannots[EnvoyConfigMapName] = rmeta.AnnotationHash(c.config.envoyConfigMap)\n\t}\n\n\tif c.config.ModSecurityConfigMap != nil {\n\t\tannots[ModSecurityRulesetHashAnnotation] = rmeta.AnnotationHash(c.config.ModSecurityConfigMap.Data)\n\t}\n\n\tpodTemplate := corev1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tAnnotations: annots,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tHostIPC: true,\n\t\t\tHostNetwork: true,\n\t\t\tServiceAccountName: APLName,\n\t\t\tDNSPolicy: corev1.DNSClusterFirstWithHostNet,\n\t\t\t// Absence of l7 daemonset pod on a node will break the annotated services connectivity, so we tolerate all.\n\t\t\tTolerations: rmeta.TolerateAll,\n\t\t\tImagePullSecrets: secret.GetReferenceList(c.config.PullSecrets),\n\t\t\tContainers: c.containers(),\n\t\t\tVolumes: c.volumes(),\n\t\t},\n\t}\n\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"DaemonSet\", APIVersion: \"apps/v1\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ApplicationLayerDaemonsetName,\n\t\t\tNamespace: common.CalicoNamespace,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: podTemplate,\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func CalicoDaemonSet(repo string) string {\n\treturn calicoCommon(repo, \"node\")\n\n}", "func DS(namespace, name string, containerImages ...string) kapisext.DaemonSet {\n\treturn kapisext.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t\tSelfLink: \"/ds/\" + name,\n\t\t},\n\t\tSpec: kapisext.DaemonSetSpec{\n\t\t\tTemplate: kapi.PodTemplateSpec{\n\t\t\t\tSpec: PodSpec(containerImages...),\n\t\t\t},\n\t\t},\n\t}\n}", "func (c *Vrouter) PrepareDaemonSet(ds *appsv1.DaemonSet,\n\tcommonConfiguration *PodConfiguration,\n\trequest reconcile.Request,\n\tscheme *runtime.Scheme,\n\tclient client.Client) error {\n\tinstanceType := \"vrouter\"\n\tSetDSCommonConfiguration(ds, commonConfiguration)\n\tds.SetName(request.Name + \"-\" + instanceType + \"-daemonset\")\n\tds.SetNamespace(request.Namespace)\n\tds.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Selector.MatchLabels = map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name}\n\tds.Spec.Template.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Template.Spec.Affinity = &corev1.Affinity{\n\t\tPodAntiAffinity: &corev1.PodAntiAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{{\n\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchExpressions: []metav1.LabelSelectorRequirement{{\n\t\t\t\t\t\tKey: instanceType,\n\t\t\t\t\t\tOperator: \"Exists\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tTopologyKey: \"kubernetes.io/hostname\",\n\t\t\t}},\n\t\t},\n\t}\n\terr := controllerutil.SetControllerReference(c, ds, scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewDaemonSetPrepuller(client clientset.Interface, waiter apiclient.Waiter, cfg *kubeadmapi.ClusterConfiguration) *DaemonSetPrepuller {\n\treturn &DaemonSetPrepuller{\n\t\tclient: client,\n\t\tcfg: cfg,\n\t\twaiter: waiter,\n\t}\n}", "func DaemonSetName(name string) string {\n\treturn DNSLengthName(DaemonSetPrefix, \"%s-%s\", DaemonSetPrefix, name)\n}", "func createDaemonSetPatch(daemonSet *appsv1.DaemonSet, labels map[string]string, annotations map[string]string) ([]byte, error) {\n\tvar patch []k8s.PatchOperation\n\tpatch = append(patch, k8s.GenerateSpecTemplateAnnotationPatch(daemonSet.Spec.Template.Annotations, annotations)...)\n\tpatch = append(patch, k8s.GenerateMetadataLabelsPatch(daemonSet.Labels, labels)...)\n\treturn json.Marshal(patch)\n}", "func expectedDaemonSet(instance *sfv1alpha1.SplunkForwarder) *appsv1.DaemonSet {\n\tvar expectedRunAsUID int64 = 0\n\tvar expectedIsPrivContainer bool = true\n\tvar expectedTerminationGracePeriodSeconds int64 = 10\n\n\tuseVolumeSecret := !instance.Spec.UseHeavyForwarder\n\tvar sfImage string\n\tif instance.Spec.ImageDigest == \"\" {\n\t\tsfImage = image + \":\" + imageTag\n\t} else {\n\t\tsfImage = image + \"@\" + imageDigest\n\t}\n\n\treturn &appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName + \"-ds\",\n\t\t\tNamespace: instanceNamespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": instanceName,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": \"10\",\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"name\": \"splunk-forwarder\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: \"splunk-forwarder\",\n\t\t\t\t\tNamespace: instanceNamespace,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": \"splunk-forwarder\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"beta.kubernetes.io/os\": \"linux\",\n\t\t\t\t\t},\n\n\t\t\t\t\tServiceAccountName: \"default\",\n\t\t\t\t\tTolerations: []corev1.Toleration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tTerminationGracePeriodSeconds: &expectedTerminationGracePeriodSeconds,\n\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"splunk-uf\",\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullAlways,\n\t\t\t\t\t\t\tImage: sfImage,\n\t\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tContainerPort: 8089,\n\t\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResources: corev1.ResourceRequirements{},\n\t\t\t\t\t\t\tTerminationMessagePath: \"/dev/termination-log\",\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"SPLUNK_ACCEPT_LICENSE\",\n\t\t\t\t\t\t\t\t\tValue: \"yes\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t {\n\t\t\t\t\t\t Name: \"HOSTNAME\",\n\t\t\t\t\t\t ValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\t\t FieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\t\t FieldPath: \"spec.nodeName\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t },\n\n\t\t\t\t\t\t\tVolumeMounts: GetVolumeMounts(instance),\n\n\t\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\t\tPrivileged: &expectedIsPrivContainer,\n\t\t\t\t\t\t\t\tRunAsUser: &expectedRunAsUID,\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\tVolumes: GetVolumes(true, useVolumeSecret, instanceName),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewPortsetCreateDefault(code int) *PortsetCreateDefault {\n\treturn &PortsetCreateDefault{\n\t\t_statusCode: code,\n\t}\n}", "func DeleteDaemonSet(daemonSetName, namespace string) error {\n\tconst (\n\t\tTimeout = 5 * time.Minute\n\t)\n\n\tlogrus.Infof(\"Deleting daemonset %s\", daemonSetName)\n\tdeletePolicy := metav1.DeletePropagationForeground\n\n\tif err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Delete(context.TODO(), daemonSetName, metav1.DeleteOptions{\n\t\tPropagationPolicy: &deletePolicy,\n\t}); err != nil {\n\t\tlogrus.Infof(\"The daemonset (%s) deletion is unsuccessful due to %+v\", daemonSetName, err.Error())\n\t}\n\n\tfor start := time.Now(); time.Since(start) < Timeout; {\n\n\t\tpods, err := daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pods, err: %s\", err)\n\t\t}\n\n\t\tif len(pods.Items) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tlogrus.Infof(\"Successfully cleaned up daemonset %s\", daemonSetName)\n\treturn nil\n}", "func MockDaemonSet() appsv1.DaemonSet {\n\tp := MockPod()\n\treturn appsv1.DaemonSet{\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n}", "func (s *K8sSvc) CreateReplicaSet(ctx context.Context, opts *containersvc.CreateServiceOptions) error {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\t// set replicaset resource limits and requests\n\tres := s.createResource(opts)\n\tglog.Infoln(\"create replicaset resource\", res, \"requuid\", requuid, opts.Common)\n\n\t// set env\n\tenvs := make([]corev1.EnvVar, len(opts.Envkvs))\n\tfor i, e := range opts.Envkvs {\n\t\tenvs[i] = corev1.EnvVar{\n\t\t\tName: e.Name,\n\t\t\tValue: e.Value,\n\t\t}\n\t}\n\n\tlabels := make(map[string]string)\n\tlabels[serviceNameLabel] = opts.Common.ServiceName\n\tlabels[serviceUUIDLabel] = opts.Common.ServiceUUID\n\n\treplicaset := &appsv1.ReplicaSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: opts.Common.ServiceName,\n\t\t\tNamespace: s.namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.ReplicaSetSpec{\n\t\t\tReplicas: utils.Int32Ptr(int32(opts.Replicas)),\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tNamespace: s.namespace,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: opts.Common.ServiceName,\n\t\t\t\t\t\t\tImage: opts.Common.ContainerImage,\n\t\t\t\t\t\t\tResources: res,\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullAlways,\n\t\t\t\t\t\t\tEnv: envs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyAlways,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// set port exposing\n\tif len(opts.PortMappings) != 0 {\n\t\tglog.Infoln(\"expose port\", opts.PortMappings, \"requuid\", requuid, opts.Common)\n\n\t\tports := make([]corev1.ContainerPort, len(opts.PortMappings))\n\t\tfor i, p := range opts.PortMappings {\n\t\t\tports[i] = corev1.ContainerPort{\n\t\t\t\tContainerPort: int32(p.ContainerPort),\n\t\t\t}\n\t\t\tif opts.ExternalDNS {\n\t\t\t\t// TODO current needs to expose the host port for ExternalDNS, so replicas could talk with each other.\n\t\t\t\t// refactor it when using the k8s external dns project.\n\t\t\t\tports[i].HostPort = int32(p.HostPort)\n\t\t\t}\n\t\t}\n\n\t\treplicaset.Spec.Template.Spec.Containers[0].Ports = ports\n\n\t\t// use host network by default for better performance.\n\t\t// k8s requires \"If this option is set, the ports that will be used must be specified.\"\n\t\treplicaset.Spec.Template.Spec.HostNetwork = true\n\t}\n\n\t_, err := s.cliset.AppsV1beta2().ReplicaSets(s.namespace).Create(replicaset)\n\treturn err\n}", "func (c *FakeExtendedDaemonSetReplicaSets) Create(extendedDaemonSetReplicaSet *v1alpha1.ExtendedDaemonSetReplicaSet) (result *v1alpha1.ExtendedDaemonSetReplicaSet, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewCreateAction(extendeddaemonsetreplicasetsResource, c.ns, extendedDaemonSetReplicaSet), &v1alpha1.ExtendedDaemonSetReplicaSet{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.ExtendedDaemonSetReplicaSet), err\n}", "func CreateStatefulSet(ns string, ss *apps.StatefulSet, c clientset.Interface) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tframework.Logf(fmt.Sprintf(\"Creating statefulset %v/%v with %d replicas and selector %+v\",\n\t\tss.Namespace, ss.Name, *(ss.Spec.Replicas), ss.Spec.Selector))\n\t_, err := c.AppsV1().StatefulSets(ns).Create(ctx, ss, metav1.CreateOptions{})\n\tframework.ExpectNoError(err)\n\tfss.WaitForRunningAndReady(c, *ss.Spec.Replicas, ss)\n}", "func (c *FakeExportedServiceSets) Create(ctx context.Context, exportedServiceSet *federationv1.ExportedServiceSet, opts v1.CreateOptions) (result *federationv1.ExportedServiceSet, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewCreateAction(exportedservicesetsResource, c.ns, exportedServiceSet), &federationv1.ExportedServiceSet{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*federationv1.ExportedServiceSet), err\n}", "func createClientset() *kubernetes.Clientset {\n\tkubeconfig := getKubeConfig()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\n\treturn clientset\n}", "func CreateClientset(kubeconfig string) (*kubernetes.Clientset, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create config object from kube-config file: %q (error: %v)\",\n\t\t\tkubeconfig, err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create clientset object (error: %v)\", err)\n\t}\n\n\treturn clientset, nil\n}", "func BuildDaemonForFluentd(instance *operatorv1alpha1.AuditLogging) *appsv1.DaemonSet {\n\treqLogger := log.WithValues(\"dameonForFluentd\", \"Entry\", \"instance.Name\", instance.Name)\n\tmetaLabels := LabelsForMetadata(FluentdName)\n\tselectorLabels := LabelsForSelector(FluentdName, instance.Name)\n\tpodLabels := LabelsForPodMetadata(FluentdName, instance.Name)\n\tannotations := annotationsForMetering(FluentdName)\n\tcommonVolumes = BuildCommonVolumes(instance)\n\tfluentdMainContainer.VolumeMounts = BuildCommonVolumeMounts(instance)\n\n\tvar tag, imageRegistry string\n\tif instance.Spec.Fluentd.ImageRegistry != \"\" || instance.Spec.Fluentd.ImageTag != \"\" {\n\t\tif instance.Spec.Fluentd.ImageRegistry != \"\" {\n\t\t\timageRegistry = instance.Spec.Fluentd.ImageRegistry\n\t\t} else {\n\t\t\timageRegistry = defaultImageRegistry\n\t\t}\n\t\tif instance.Spec.Fluentd.ImageTag != \"\" {\n\t\t\ttag = instance.Spec.Fluentd.ImageTag\n\t\t} else {\n\t\t\ttag = defaultFluentdImageTag\n\t\t}\n\t\tfluentdMainContainer.Image = imageRegistry + defaultFluentdImageName + \":\" + tag\n\t}\n\n\tif instance.Spec.Fluentd.PullPolicy != \"\" {\n\t\tswitch instance.Spec.Fluentd.PullPolicy {\n\t\tcase \"Always\":\n\t\t\tfluentdMainContainer.ImagePullPolicy = corev1.PullAlways\n\t\tcase \"PullNever\":\n\t\t\tfluentdMainContainer.ImagePullPolicy = corev1.PullNever\n\t\tcase \"IfNotPresent\":\n\t\t\tfluentdMainContainer.ImagePullPolicy = corev1.PullIfNotPresent\n\t\tdefault:\n\t\t\treqLogger.Info(\"Trying to update PullPolicy\", \"NOT SUPPORTED\", instance.Spec.Fluentd.PullPolicy)\n\t\t}\n\t}\n\n\tdaemon := &appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: FluentdDaemonSetName,\n\t\t\tNamespace: InstanceNamespace,\n\t\t\tLabels: metaLabels,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: selectorLabels,\n\t\t\t},\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDaemonSetStrategyType,\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &intstr.IntOrString{\n\t\t\t\t\t\tType: intstr.Int,\n\t\t\t\t\t\tIntVal: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tMinReadySeconds: 5,\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: podLabels,\n\t\t\t\t\tAnnotations: annotations,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tServiceAccountName: FluentdDaemonSetName + ServiceAcct,\n\t\t\t\t\tTerminationGracePeriodSeconds: &seconds30,\n\t\t\t\t\t// NodeSelector: {},\n\t\t\t\t\tTolerations: commonTolerations,\n\t\t\t\t\tVolumes: commonVolumes,\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\tfluentdMainContainer,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn daemon\n}", "func GetDaemonSet(namespace string, daemonsetName string) *v1beta1.DaemonSet {\n\treturn &v1beta1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: daemonsetName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tconstants.ConfigmapUpdateOnChangeAnnotation: daemonsetName,\n\t\t\t\tconstants.SecretUpdateOnChangeAnnotation: daemonsetName},\n\t\t},\n\t\tSpec: v1beta1.DaemonSetSpec{\n\t\t\tUpdateStrategy: v1beta1.DaemonSetUpdateStrategy{\n\t\t\t\tType: v1beta1.RollingUpdateDaemonSetStrategyType,\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\"secondLabel\": \"temp\"},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tImage: \"tutum/hello-world\",\n\t\t\t\t\t\t\tName: daemonsetName,\n\t\t\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"BUCKET_NAME\",\n\t\t\t\t\t\t\t\t\tValue: \"test\",\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 DSList(dss ...kapisext.DaemonSet) kapisext.DaemonSetList {\n\treturn kapisext.DaemonSetList{\n\t\tItems: dss,\n\t}\n}", "func DaemonSetObjectWrapper(create DaemonSetCreator) ObjectCreator {\n\treturn func(existing runtime.Object) (runtime.Object, error) {\n\t\tif existing != nil {\n\t\t\treturn create(existing.(*appsv1.DaemonSet))\n\t\t}\n\t\treturn create(&appsv1.DaemonSet{})\n\t}\n}", "func CreateStatefulSet(client kubernetes.Interface, statefulsetName string, namespace string) (*v1_beta1.StatefulSet, error) {\n\tlogrus.Infof(\"Creating StatefulSet\")\n\tstatefulsetClient := client.AppsV1beta1().StatefulSets(namespace)\n\tstatefulset, err := statefulsetClient.Create(GetStatefulSet(namespace, statefulsetName))\n\ttime.Sleep(10 * time.Second)\n\treturn statefulset, err\n}", "func ApplyDaemonSetv1(ctx context.Context, client appsclientv1.DaemonSetsGetter, required *appsv1.DaemonSet, reconciling bool) (*appsv1.DaemonSet, bool, error) {\n\texisting, err := client.DaemonSets(required.Namespace).Get(ctx, required.Name, metav1.GetOptions{})\n\tif apierrors.IsNotFound(err) {\n\t\tklog.V(2).Infof(\"DaemonSet %s/%s not found, creating\", required.Namespace, required.Name)\n\t\tactual, err := client.DaemonSets(required.Namespace).Create(ctx, required, metav1.CreateOptions{})\n\t\treturn actual, true, err\n\t}\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\t// if we only create this resource, we have no need to continue further\n\tif IsCreateOnly(required) {\n\t\treturn nil, false, nil\n\t}\n\n\tmodified := pointer.Bool(false)\n\tresourcemerge.EnsureDaemonSet(modified, existing, *required)\n\tif !*modified {\n\t\treturn existing, false, nil\n\t}\n\n\tif reconciling {\n\t\tklog.V(2).Infof(\"Updating DaemonSet %s/%s due to diff: %v\", required.Namespace, required.Name, cmp.Diff(existing, required))\n\t}\n\n\tactual, err := client.DaemonSets(required.Namespace).Update(ctx, existing, metav1.UpdateOptions{})\n\treturn actual, true, err\n}", "func getDSClient() v1.DaemonSetInterface {\n\tlog.Debug(\"Creating Daemonset client.\")\n\treturn client.AppsV1().DaemonSets(checkNamespace)\n}", "func (s S) WithDaemonSets(d []appsv1.DaemonSet) S {\n\ts.daemonSets = d\n\treturn s\n}", "func createStatefulSetWithOneReplica(client clientset.Interface, manifestPath string, namespace string) *appsv1.StatefulSet {\n\tmkpath := func(file string) string {\n\t\treturn filepath.Join(manifestPath, file)\n\t}\n\tstatefulSet, err := manifest.StatefulSetFromManifest(mkpath(\"statefulset.yaml\"), namespace)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tservice, err := manifest.SvcFromManifest(mkpath(\"service.yaml\"))\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t_, err = client.CoreV1().Services(namespace).Create(service)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t*statefulSet.Spec.Replicas = 1\n\t_, err = client.AppsV1().StatefulSets(namespace).Create(statefulSet)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\treturn statefulSet\n}", "func GetDaemonSetDetail(client k8sClient.Interface, metricClient metricapi.MetricClient,\n\tnamespace, name string) (*DaemonSetDetail, error) {\n\n\tlog.Printf(\"Getting details of %s daemon set in %s namespace\", name, namespace)\n\tdaemonSet, err := client.AppsV1beta2().DaemonSets(namespace).Get(name, metaV1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpodList, err := GetDaemonSetPods(client, metricClient, ds.DefaultDataSelectWithMetrics, name, namespace)\n\tnonCriticalErrors, criticalError := errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tpodInfo, err := getDaemonSetPodInfo(client, daemonSet)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tserviceList, err := GetDaemonSetServices(client, ds.DefaultDataSelect, namespace, name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\teventList, err := event.GetResourceEvents(client, ds.DefaultDataSelect, daemonSet.Namespace, daemonSet.Name)\n\tnonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tdaemonSetDetail := &DaemonSetDetail{\n\t\tObjectMeta: api.NewObjectMeta(daemonSet.ObjectMeta),\n\t\tTypeMeta: api.NewTypeMeta(api.ResourceKindDaemonSet),\n\t\tLabelSelector: daemonSet.Spec.Selector,\n\t\tPodInfo: *podInfo,\n\t\tPodList: *podList,\n\t\tServiceList: *serviceList,\n\t\tEventList: *eventList,\n\t\tErrors: nonCriticalErrors,\n\t}\n\n\tfor _, container := range daemonSet.Spec.Template.Spec.Containers {\n\t\tdaemonSetDetail.ContainerImages = append(daemonSetDetail.ContainerImages, container.Image)\n\t}\n\n\tfor _, initContainer := range daemonSet.Spec.Template.Spec.InitContainers {\n\t\tdaemonSetDetail.InitContainerImages = append(daemonSetDetail.InitContainerImages, initContainer.Image)\n\t}\n\n\treturn daemonSetDetail, nil\n}", "func NewReplicaSet() ReplicaSet {\n\treturn ReplicaSet{Instances: make([]string, 0, ReplicaSetMaxSize)}\n}", "func (ipset *IPSet) Create(setName string, createOptions ...string) (*Set, error) {\n\t// Populate Set map if needed\n\tif ipset.Get(setName) == nil {\n\t\tipset.Sets[setName] = &Set{\n\t\t\tName: setName,\n\t\t\tOptions: createOptions,\n\t\t\tParent: ipset,\n\t\t}\n\t}\n\n\t// Determine if set with the same name is already active on the system\n\tsetIsActive, err := ipset.Sets[setName].IsActive()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to determine if ipset set %s exists: %s\",\n\t\t\tsetName, err)\n\t}\n\n\t// Create set if missing from the system\n\tif !setIsActive {\n\t\tif ipset.isIpv6 {\n\t\t\t// Add \"family inet6\" option and a \"inet6:\" prefix for IPv6 sets.\n\t\t\targs := []string{\"create\", \"-exist\", ipset.Sets[setName].name()}\n\t\t\targs = append(args, createOptions...)\n\t\t\targs = append(args, \"family\", \"inet6\")\n\t\t\tif _, err := ipset.run(args...); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create ipset set on system: %s\", err)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := ipset.run(append([]string{\"create\", \"-exist\", setName},\n\t\t\t\tcreateOptions...)...)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create ipset set on system: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn ipset.Sets[setName], nil\n}", "func DeleteDaemonSet(client kubernetes.Interface, namespace string, daemonsetName string) error {\n\tlogrus.Infof(\"Deleting DaemonSet %s\", daemonsetName)\n\tdaemonsetError := client.ExtensionsV1beta1().DaemonSets(namespace).Delete(daemonsetName, &metav1.DeleteOptions{})\n\ttime.Sleep(10 * time.Second)\n\treturn daemonsetError\n}", "func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.Store, authzMiddleware *authorization.Middleware) (daemon *Daemon, err error) {\n\t// Verify platform-specific requirements.\n\t// TODO(thaJeztah): this should be called before we try to create the daemon; perhaps together with the config validation.\n\tif err := checkSystem(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tregistryService, err := registry.NewService(config.ServiceOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure that we have a correct root key limit for launching containers.\n\tif err := modifyRootKeyLimit(); err != nil {\n\t\tlog.G(ctx).Warnf(\"unable to modify root key limit, number of containers could be limited by this quota: %v\", err)\n\t}\n\n\t// Ensure we have compatible and valid configuration options\n\tif err := verifyDaemonSettings(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Do we have a disabled network?\n\tconfig.DisableBridge = isBridgeNetworkDisabled(config)\n\n\t// Setup the resolv.conf\n\tsetupResolvConf(config)\n\n\tidMapping, err := setupRemappedRoot(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trootIDs := idMapping.RootPair()\n\tif err := setMayDetachMounts(); err != nil {\n\t\tlog.G(ctx).WithError(err).Warn(\"Could not set may_detach_mounts kernel parameter\")\n\t}\n\n\t// set up the tmpDir to use a canonical path\n\ttmp, err := prepareTempDir(config.Root)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to get the TempDir under %s: %s\", config.Root, err)\n\t}\n\trealTmp, err := fileutils.ReadSymlinkedDirectory(tmp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to get the full path to the TempDir (%s): %s\", tmp, err)\n\t}\n\tif isWindows {\n\t\tif err := system.MkdirAll(realTmp, 0); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to create the TempDir (%s): %s\", realTmp, err)\n\t\t}\n\t\tos.Setenv(\"TEMP\", realTmp)\n\t\tos.Setenv(\"TMP\", realTmp)\n\t} else {\n\t\tos.Setenv(\"TMPDIR\", realTmp)\n\t}\n\n\tif err := initRuntimesDir(config); err != nil {\n\t\treturn nil, err\n\t}\n\trts, err := setupRuntimes(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := &Daemon{\n\t\tPluginStore: pluginStore,\n\t\tstartupDone: make(chan struct{}),\n\t}\n\tcfgStore := &configStore{\n\t\tConfig: *config,\n\t\tRuntimes: rts,\n\t}\n\td.configStore.Store(cfgStore)\n\n\t// TEST_INTEGRATION_USE_SNAPSHOTTER is used for integration tests only.\n\tif os.Getenv(\"TEST_INTEGRATION_USE_SNAPSHOTTER\") != \"\" {\n\t\td.usesSnapshotter = true\n\t} else {\n\t\td.usesSnapshotter = config.Features[\"containerd-snapshotter\"]\n\t}\n\n\t// Ensure the daemon is properly shutdown if there is a failure during\n\t// initialization\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t// Use a fresh context here. Passed context could be cancelled.\n\t\t\tif err := d.Shutdown(context.Background()); err != nil {\n\t\t\t\tlog.G(ctx).Error(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err := d.setGenericResources(&cfgStore.Config); err != nil {\n\t\treturn nil, err\n\t}\n\t// set up SIGUSR1 handler on Unix-like systems, or a Win32 global event\n\t// on Windows to dump Go routine stacks\n\tstackDumpDir := cfgStore.Root\n\tif execRoot := cfgStore.GetExecRoot(); execRoot != \"\" {\n\t\tstackDumpDir = execRoot\n\t}\n\td.setupDumpStackTrap(stackDumpDir)\n\n\tif err := d.setupSeccompProfile(&cfgStore.Config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the default isolation mode (only applicable on Windows)\n\tif err := d.setDefaultIsolation(&cfgStore.Config); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting default isolation mode: %v\", err)\n\t}\n\n\tif err := configureMaxThreads(&cfgStore.Config); err != nil {\n\t\tlog.G(ctx).Warnf(\"Failed to configure golang's threads limit: %v\", err)\n\t}\n\n\t// ensureDefaultAppArmorProfile does nothing if apparmor is disabled\n\tif err := ensureDefaultAppArmorProfile(); err != nil {\n\t\tlog.G(ctx).Errorf(err.Error())\n\t}\n\n\tdaemonRepo := filepath.Join(cfgStore.Root, \"containers\")\n\tif err := idtools.MkdirAllAndChown(daemonRepo, 0o710, idtools.Identity{\n\t\tUID: idtools.CurrentIdentity().UID,\n\t\tGID: rootIDs.GID,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif isWindows {\n\t\t// Note that permissions (0o700) are ignored on Windows; passing them to\n\t\t// show intent only. We could consider using idtools.MkdirAndChown here\n\t\t// to apply an ACL.\n\t\tif err = os.Mkdir(filepath.Join(cfgStore.Root, \"credentialspecs\"), 0o700); err != nil && !errors.Is(err, os.ErrExist) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\td.registryService = registryService\n\tdlogger.RegisterPluginGetter(d.PluginStore)\n\n\tmetricsSockPath, err := d.listenMetricsSock(&cfgStore.Config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tregisterMetricsPluginCallback(d.PluginStore, metricsSockPath)\n\n\tbackoffConfig := backoff.DefaultConfig\n\tbackoffConfig.MaxDelay = 3 * time.Second\n\tconnParams := grpc.ConnectParams{\n\t\tBackoff: backoffConfig,\n\t}\n\tgopts := []grpc.DialOption{\n\t\t// WithBlock makes sure that the following containerd request\n\t\t// is reliable.\n\t\t//\n\t\t// NOTE: In one edge case with high load pressure, kernel kills\n\t\t// dockerd, containerd and containerd-shims caused by OOM.\n\t\t// When both dockerd and containerd restart, but containerd\n\t\t// will take time to recover all the existing containers. Before\n\t\t// containerd serving, dockerd will failed with gRPC error.\n\t\t// That bad thing is that restore action will still ignore the\n\t\t// any non-NotFound errors and returns running state for\n\t\t// already stopped container. It is unexpected behavior. And\n\t\t// we need to restart dockerd to make sure that anything is OK.\n\t\t//\n\t\t// It is painful. Add WithBlock can prevent the edge case. And\n\t\t// n common case, the containerd will be serving in shortly.\n\t\t// It is not harm to add WithBlock for containerd connection.\n\t\tgrpc.WithBlock(),\n\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\tgrpc.WithConnectParams(connParams),\n\t\tgrpc.WithContextDialer(dialer.ContextDialer),\n\n\t\t// TODO(stevvooe): We may need to allow configuration of this on the client.\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),\n\t\tgrpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),\n\t}\n\n\tif cfgStore.ContainerdAddr != \"\" {\n\t\td.containerdClient, err = containerd.New(cfgStore.ContainerdAddr, containerd.WithDefaultNamespace(cfgStore.ContainerdNamespace), containerd.WithDialOpts(gopts), containerd.WithTimeout(60*time.Second))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to dial %q\", cfgStore.ContainerdAddr)\n\t\t}\n\t}\n\n\tcreatePluginExec := func(m *plugin.Manager) (plugin.Executor, error) {\n\t\tvar pluginCli *containerd.Client\n\n\t\tif cfgStore.ContainerdAddr != \"\" {\n\t\t\tpluginCli, err = containerd.New(cfgStore.ContainerdAddr, containerd.WithDefaultNamespace(cfgStore.ContainerdPluginNamespace), containerd.WithDialOpts(gopts), containerd.WithTimeout(60*time.Second))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"failed to dial %q\", cfgStore.ContainerdAddr)\n\t\t\t}\n\t\t}\n\n\t\tvar (\n\t\t\tshim string\n\t\t\tshimOpts interface{}\n\t\t)\n\t\tif runtime.GOOS != \"windows\" {\n\t\t\tshim, shimOpts, err = rts.Get(\"\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn pluginexec.New(ctx, getPluginExecRoot(&cfgStore.Config), pluginCli, cfgStore.ContainerdPluginNamespace, m, shim, shimOpts)\n\t}\n\n\t// Plugin system initialization should happen before restore. Do not change order.\n\td.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{\n\t\tRoot: filepath.Join(cfgStore.Root, \"plugins\"),\n\t\tExecRoot: getPluginExecRoot(&cfgStore.Config),\n\t\tStore: d.PluginStore,\n\t\tCreateExecutor: createPluginExec,\n\t\tRegistryService: registryService,\n\t\tLiveRestoreEnabled: cfgStore.LiveRestoreEnabled,\n\t\tLogPluginEvent: d.LogPluginEvent, // todo: make private\n\t\tAuthzMiddleware: authzMiddleware,\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"couldn't create plugin manager\")\n\t}\n\n\td.defaultLogConfig, err = defaultLogConfig(&cfgStore.Config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to set log opts\")\n\t}\n\tlog.G(ctx).Debugf(\"Using default logging driver %s\", d.defaultLogConfig.Type)\n\n\td.volumes, err = volumesservice.NewVolumeService(cfgStore.Root, d.PluginStore, rootIDs, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if Devices cgroup is mounted, it is hard requirement for container security,\n\t// on Linux.\n\t//\n\t// Important: we call getSysInfo() directly here, without storing the results,\n\t// as networking has not yet been set up, so we only have partial system info\n\t// at this point.\n\t//\n\t// TODO(thaJeztah) add a utility to only collect the CgroupDevicesEnabled information\n\tif runtime.GOOS == \"linux\" && !userns.RunningInUserNS() && !getSysInfo(&cfgStore.Config).CgroupDevicesEnabled {\n\t\treturn nil, errors.New(\"Devices cgroup isn't mounted\")\n\t}\n\n\td.id, err = loadOrCreateID(filepath.Join(cfgStore.Root, \"engine-id\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.repository = daemonRepo\n\td.containers = container.NewMemoryStore()\n\tif d.containersReplica, err = container.NewViewDB(); err != nil {\n\t\treturn nil, err\n\t}\n\td.execCommands = container.NewExecStore()\n\td.statsCollector = d.newStatsCollector(1 * time.Second)\n\n\td.EventsService = events.New()\n\td.root = cfgStore.Root\n\td.idMapping = idMapping\n\n\td.linkIndex = newLinkIndex()\n\n\t// On Windows we don't support the environment variable, or a user supplied graphdriver\n\t// Unix platforms however run a single graphdriver for all containers, and it can\n\t// be set through an environment variable, a daemon start parameter, or chosen through\n\t// initialization of the layerstore through driver priority order for example.\n\tdriverName := os.Getenv(\"DOCKER_DRIVER\")\n\tif isWindows {\n\t\tdriverName = \"windowsfilter\"\n\t} else if driverName != \"\" {\n\t\tlog.G(ctx).Infof(\"Setting the storage driver from the $DOCKER_DRIVER environment variable (%s)\", driverName)\n\t} else {\n\t\tdriverName = cfgStore.GraphDriver\n\t}\n\n\tif d.UsesSnapshotter() {\n\t\tif os.Getenv(\"TEST_INTEGRATION_USE_SNAPSHOTTER\") != \"\" {\n\t\t\tlog.G(ctx).Warn(\"Enabling containerd snapshotter through the $TEST_INTEGRATION_USE_SNAPSHOTTER environment variable. This should only be used for testing.\")\n\t\t}\n\t\tlog.G(ctx).Info(\"Starting daemon with containerd snapshotter integration enabled\")\n\n\t\t// FIXME(thaJeztah): implement automatic snapshotter-selection similar to graph-driver selection; see https://github.com/moby/moby/issues/44076\n\t\tif driverName == \"\" {\n\t\t\tdriverName = containerd.DefaultSnapshotter\n\t\t}\n\n\t\t// Configure and validate the kernels security support. Note this is a Linux/FreeBSD\n\t\t// operation only, so it is safe to pass *just* the runtime OS graphdriver.\n\t\tif err := configureKernelSecuritySupport(&cfgStore.Config, driverName); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\td.imageService = ctrd.NewService(ctrd.ImageServiceConfig{\n\t\t\tClient: d.containerdClient,\n\t\t\tContainers: d.containers,\n\t\t\tSnapshotter: driverName,\n\t\t\tRegistryHosts: d.RegistryHosts,\n\t\t\tRegistry: d.registryService,\n\t\t\tEventsService: d.EventsService,\n\t\t\tRefCountMounter: snapshotter.NewMounter(config.Root, driverName, idMapping),\n\t\t})\n\t} else {\n\t\tlayerStore, err := layer.NewStoreFromOptions(layer.StoreOptions{\n\t\t\tRoot: cfgStore.Root,\n\t\t\tMetadataStorePathTemplate: filepath.Join(cfgStore.Root, \"image\", \"%s\", \"layerdb\"),\n\t\t\tGraphDriver: driverName,\n\t\t\tGraphDriverOptions: cfgStore.GraphOptions,\n\t\t\tIDMapping: idMapping,\n\t\t\tPluginGetter: d.PluginStore,\n\t\t\tExperimentalEnabled: cfgStore.Experimental,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Configure and validate the kernels security support. Note this is a Linux/FreeBSD\n\t\t// operation only, so it is safe to pass *just* the runtime OS graphdriver.\n\t\tif err := configureKernelSecuritySupport(&cfgStore.Config, layerStore.DriverName()); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\timageRoot := filepath.Join(cfgStore.Root, \"image\", layerStore.DriverName())\n\t\tifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, \"imagedb\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// We have a single tag/reference store for the daemon globally. However, it's\n\t\t// stored under the graphdriver. On host platforms which only support a single\n\t\t// container OS, but multiple selectable graphdrivers, this means depending on which\n\t\t// graphdriver is chosen, the global reference store is under there. For\n\t\t// platforms which support multiple container operating systems, this is slightly\n\t\t// more problematic as where does the global ref store get located? Fortunately,\n\t\t// for Windows, which is currently the only daemon supporting multiple container\n\t\t// operating systems, the list of graphdrivers available isn't user configurable.\n\t\t// For backwards compatibility, we just put it under the windowsfilter\n\t\t// directory regardless.\n\t\trefStoreLocation := filepath.Join(imageRoot, `repositories.json`)\n\t\trs, err := refstore.NewReferenceStore(refStoreLocation)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Couldn't create reference store repository: %s\", err)\n\t\t}\n\t\td.ReferenceStore = rs\n\n\t\timageStore, err := image.NewImageStore(ifs, layerStore)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdistributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, \"distribution\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\timgSvcConfig := images.ImageServiceConfig{\n\t\t\tContainerStore: d.containers,\n\t\t\tDistributionMetadataStore: distributionMetadataStore,\n\t\t\tEventsService: d.EventsService,\n\t\t\tImageStore: imageStore,\n\t\t\tLayerStore: layerStore,\n\t\t\tMaxConcurrentDownloads: config.MaxConcurrentDownloads,\n\t\t\tMaxConcurrentUploads: config.MaxConcurrentUploads,\n\t\t\tMaxDownloadAttempts: config.MaxDownloadAttempts,\n\t\t\tReferenceStore: rs,\n\t\t\tRegistryService: registryService,\n\t\t\tContentNamespace: config.ContainerdNamespace,\n\t\t}\n\n\t\t// containerd is not currently supported with Windows.\n\t\t// So sometimes d.containerdCli will be nil\n\t\t// In that case we'll create a local content store... but otherwise we'll use containerd\n\t\tif d.containerdClient != nil {\n\t\t\timgSvcConfig.Leases = d.containerdClient.LeasesService()\n\t\t\timgSvcConfig.ContentStore = d.containerdClient.ContentStore()\n\t\t} else {\n\t\t\timgSvcConfig.ContentStore, imgSvcConfig.Leases, err = d.configureLocalContentStore(config.ContainerdNamespace)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// TODO: imageStore, distributionMetadataStore, and ReferenceStore are only\n\t\t// used above to run migration. They could be initialized in ImageService\n\t\t// if migration is called from daemon/images. layerStore might move as well.\n\t\td.imageService = images.NewImageService(imgSvcConfig)\n\n\t\tlog.G(ctx).Debugf(\"Max Concurrent Downloads: %d\", imgSvcConfig.MaxConcurrentDownloads)\n\t\tlog.G(ctx).Debugf(\"Max Concurrent Uploads: %d\", imgSvcConfig.MaxConcurrentUploads)\n\t\tlog.G(ctx).Debugf(\"Max Download Attempts: %d\", imgSvcConfig.MaxDownloadAttempts)\n\t}\n\n\tgo d.execCommandGC()\n\n\tif err := d.initLibcontainerd(ctx, &cfgStore.Config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := d.restore(cfgStore); err != nil {\n\t\treturn nil, err\n\t}\n\tclose(d.startupDone)\n\n\tinfo := d.SystemInfo()\n\tfor _, w := range info.Warnings {\n\t\tlog.G(ctx).Warn(w)\n\t}\n\n\tengineInfo.WithValues(\n\t\tdockerversion.Version,\n\t\tdockerversion.GitCommit,\n\t\tinfo.Architecture,\n\t\tinfo.Driver,\n\t\tinfo.KernelVersion,\n\t\tinfo.OperatingSystem,\n\t\tinfo.OSType,\n\t\tinfo.OSVersion,\n\t\tinfo.ID,\n\t).Set(1)\n\tengineCpus.Set(float64(info.NCPU))\n\tengineMemory.Set(float64(info.MemTotal))\n\n\tlog.G(ctx).WithFields(log.Fields{\n\t\t\"version\": dockerversion.Version,\n\t\t\"commit\": dockerversion.GitCommit,\n\t\t\"graphdriver\": d.ImageService().StorageDriver(),\n\t}).Info(\"Docker daemon\")\n\n\treturn d, nil\n}", "func createSet(dsGraph *constellation.Config) (set.Set, set.Set) {\n\n\t// Create sets to hold services and relationships - used to find differences between old and new using intersection and difference operations\n\tretSetServices := set.NewSet()\n\tretSetRelationships := set.NewSet()\n\n\t//Store all services in the services set\n\tfor _, v := range dsGraph.Services {\n\t\tretSetServices.Add(v.ID)\n\t}\n\n\t//Store relationships in the relationship set\n\tfor _, v := range dsGraph.Relationships {\n\t\tretSetRelationships.Add(v.From + \"|\" + v.To)\n\t}\n\n\treturn retSetServices, retSetRelationships\n}", "func GetDaemonSetName(name string) string {\n\treturn DaemonSetPrefix + \"-\" + name\n}", "func (in *BcsDaemonset) DeepCopy() *BcsDaemonset {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsDaemonset)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewSharedSecretSetCreateWithDefaults() *SharedSecretSetCreate {\n\tthis := SharedSecretSetCreate{}\n\treturn &this\n}", "func NewPortsetCreateCreated() *PortsetCreateCreated {\n\treturn &PortsetCreateCreated{}\n}", "func ReconcileDaemonSets(ctx context.Context, namedGetters []NamedDaemonSetCreatorGetter, namespace string, client ctrlruntimeclient.Client, objectModifiers ...ObjectModifier) error {\n\tfor _, get := range namedGetters {\n\t\tname, create := get()\n\t\tcreate = DefaultDaemonSet(create)\n\t\tcreateObject := DaemonSetObjectWrapper(create)\n\t\tcreateObject = createWithNamespace(createObject, namespace)\n\t\tcreateObject = createWithName(createObject, name)\n\n\t\tfor _, objectModifier := range objectModifiers {\n\t\t\tcreateObject = objectModifier(createObject)\n\t\t}\n\n\t\tif err := EnsureNamedObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, createObject, client, &appsv1.DaemonSet{}, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to ensure DaemonSet %s/%s: %v\", namespace, name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (k *k8sService) deleteDaemonSet(name string) error {\n\terr := k.client.ExtensionsV1beta1().DaemonSets(defaultNS).Delete(name, nil)\n\tif err == nil {\n\t\tlog.Infof(\"Deleted DaemonSet %v\", name)\n\t} else if errors.IsNotFound(err) {\n\t\tlog.Infof(\"DaemonSet %v not found\", name)\n\t\terr = nil\n\t} else {\n\t\tlog.Errorf(\"Failed to delete DaemonSet %v with error: %v\", name, err)\n\t}\n\treturn err\n}", "func (c *FakeDaemonstools) Create(ctx context.Context, daemonstool *v1beta1.Daemonstool, opts v1.CreateOptions) (result *v1beta1.Daemonstool, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewCreateAction(daemonstoolsResource, c.ns, daemonstool), &v1beta1.Daemonstool{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1beta1.Daemonstool), err\n}", "func CreateStatefulSet(name string) *appsv1.StatefulSet {\n\treturn &appsv1.StatefulSet{\n\t\tTypeMeta: genTypeMeta(gvk.StatefulSet),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t}\n}", "func (s S) DaemonSets() []appsv1.DaemonSet {\n\treturn s.daemonSets\n}", "func NewDaemon(opts Options, store *store.Store) (*Daemon, error) {\n\trsaKey, err := util.GenerateRSAKey(util.DefaultRSAKeySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := util.GenRSAPublicKeyFile(rsaKey, util.DefaultRSAKeyPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Daemon{\n\t\topts: &opts,\n\t\tbuilders: make(map[string]builder.Builder),\n\t\tentities: make(map[string]string),\n\t\tlocalStore: store,\n\t\tkey: rsaKey,\n\t}, nil\n}", "func New(ops ...Option) *Daemon {\n\tf := int32(15)\n\td := &Daemon{\n\t\tBasePath: \".\",\n\t\tExtention: \".go\",\n\t\tExcluded: []string{},\n\t\tFrequency: f,\n\t\tfrequency: time.Duration(time.Duration(f) * time.Second),\n\n\t\tcmdMux: &sync.Mutex{},\n\t\tCommand: \"echo \\\"Hello world\\\"\",\n\n\t\tdoneMux: &sync.Mutex{},\n\t\tdoneChan: make(chan struct{}),\n\t}\n\n\tfor _, o := range ops {\n\t\to(d)\n\t}\n\n\treturn d\n}", "func (c *Client) CreateDeploySet(args *CreateDeploySetArgs) (*CreateDeploySetResult, error) {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn nil, jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn CreateDeploySet(c, args.ClientToken, body)\n}", "func buildPrePullDaemonSet(component, image string) *apps.DaemonSet {\n\tvar gracePeriodSecs int64\n\treturn &apps.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: addPrepullPrefix(component),\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tSpec: apps.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: component,\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tCommand: []string{\"/bin/sleep\", \"3600\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\tconstants.LabelNodeRoleMaster: \"\",\n\t\t\t\t\t},\n\t\t\t\t\tTolerations: []v1.Toleration{constants.MasterToleration},\n\t\t\t\t\tTerminationGracePeriodSeconds: &gracePeriodSecs,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func ValidateDaemonSet(ds *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(&ds.ObjectMeta, true, ValidateDaemonSetName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDaemonSetSpec(&ds.Spec, nil, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}", "func (r *reconciler) createNodeResolverDaemonSet(daemonset *appsv1.DaemonSet) error {\n\tif err := r.client.Create(context.TODO(), daemonset); err != nil {\n\t\treturn fmt.Errorf(\"failed to create node resolver daemonset %s/%s: %v\", daemonset.Namespace, daemonset.Name, err)\n\t}\n\tlogrus.Infof(\"created node resolver daemonset: %s/%s\", daemonset.Namespace, daemonset.Name)\n\treturn nil\n}", "func (c *ClientSetClient) PatchDaemonSet(namespace, name, jsonPatch string) (*appsv1.DaemonSet, error) {\n\tctx := context.TODO()\n\treturn c.clientset.AppsV1().DaemonSets(namespace).Patch(ctx, name, types.StrategicMergePatchType, []byte(jsonPatch), metav1.PatchOptions{})\n}", "func makeTestDaemonWithMinerAndStart(t *testing.T) *th.TestDaemon {\n\tdaemon := th.NewDaemon(\n\t\tt,\n\t\tth.WithMiner(fixtures.TestMiners[0]),\n\t\tth.KeyFile(fixtures.KeyFilePaths()[0]),\n\t).Start()\n\treturn daemon\n}", "func CommonDaemonSets(controllersCount int, selfHostedKubeletDisabled bool) []Workload {\n\tbase := []Workload{\n\t\t{\n\t\t\tName: \"calico-node\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"pod-checkpointer\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-proxy\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t}\n\n\tif !selfHostedKubeletDisabled {\n\t\tbase = append(base, Workload{\n\t\t\tName: \"kubelet\",\n\t\t\tNamespace: \"kube-system\",\n\t\t})\n\t}\n\n\tif controllersCount == 1 {\n\t\treturn base\n\t}\n\n\treturn append(base, []Workload{\n\t\t{\n\t\t\tName: \"kube-apiserver\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"coredns\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-controller-manager\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-scheduler\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t}...)\n}", "func CreateSet(values ...interface{}) map[interface{}]struct{} {\n\treturn make(map[interface{}]struct{})\n}", "func inheritDaemonsetLabels(service *apistructs.Service, daemonset *appsv1.DaemonSet) error {\n\tif daemonset == nil {\n\t\treturn nil\n\t}\n\n\tif daemonset.Labels == nil {\n\t\tdaemonset.Labels = make(map[string]string)\n\t}\n\n\tif daemonset.Spec.Template.Labels == nil {\n\t\tdaemonset.Spec.Template.Labels = make(map[string]string)\n\t}\n\n\thasHostPath := serviceHasHostpath(service)\n\n\terr := setPodLabelsFromService(hasHostPath, service.Labels, daemonset.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\tfor lk, lv := range daemonset.Labels {\n\t\tif lk == apistructs.AlibabaECILabel && lv == \"true\" {\n\t\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: ECI not support daemonset, do not set lables %s='true' for daemonset\", daemonset.Name, daemonset.Namespace, lk)\n\t\t}\n\t}\n\n\terr = setPodLabelsFromService(hasHostPath, service.Labels, daemonset.Spec.Template.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\terr = setPodLabelsFromService(hasHostPath, service.DeploymentLabels, daemonset.Spec.Template.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.DeploymentLabels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\tfor lk, lv := range daemonset.Spec.Template.Labels {\n\t\tif lk == apistructs.AlibabaECILabel && lv == \"true\" {\n\t\t\treturn errors.Errorf(\"error in service.DeploymentLabels: for daemonset %v in namesapce %v with error: ECI not support daemonset, do not set lables %s='true' for daemonset.\\n\", daemonset.Name, daemonset.Namespace, lk)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *quarksStatefulSets) Create(ctx context.Context, quarksStatefulSet *v1alpha1.QuarksStatefulSet, opts v1.CreateOptions) (result *v1alpha1.QuarksStatefulSet, err error) {\n\tresult = &v1alpha1.QuarksStatefulSet{}\n\terr = c.client.Post().\n\t\tNamespace(c.ns).\n\t\tResource(\"quarksstatefulsets\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tBody(quarksStatefulSet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func (c client) CreateStatefulSet(sts appsv1.StatefulSet) error {\n\treturn c.Create(context.TODO(), &sts)\n}", "func (cli *SetWrapper) Create() error {\n\treturn cli.set.Create()\n}", "func NewEavAttributeSetManagementV1CreatePostDefault(code int) *EavAttributeSetManagementV1CreatePostDefault {\n\treturn &EavAttributeSetManagementV1CreatePostDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (suite *PouchDaemonSuite) TestDaemonInvalideArgs(c *check.C) {\n\tdcfg, err := StartDefaultDaemon(nil, \"--config=xxx\")\n\tdcfg.KillDaemon()\n\tc.Assert(err, check.NotNil)\n}", "func (c *Client) DaemonSetsCleaner(namespace string, dryRun bool, directories []string) error {\n\tvar left []string\n\n\tclusterDaemonsets, err := c.ListDaemonSets(namespace)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tfor _, value := range clusterDaemonsets.Items {\n\t\tleft = append(left, value.Name)\n\t}\n\n\tobjectsToDelete := Except(left, \"DaemonSet\", directories)\n\n\tfor _, item := range objectsToDelete {\n\t\tfor _, daemonset := range clusterDaemonsets.Items {\n\t\t\tif item == daemonset.Name {\n\t\t\t\tif dryRun {\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t\tcolor.Yellow(\" Deleting DaemonSet %s [dry-run]\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t} else {\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tcolor.Red(\" Deleting DaemonSet %s\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tif err := c.DeleteDaemonSet(daemonset); err != nil {\n\t\t\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateAppReplicaSet(name string) *appsv1.ReplicaSet {\n\treturn &appsv1.ReplicaSet{\n\t\tTypeMeta: genTypeMeta(gvk.AppReplicaSet),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t}\n}", "func GetDaemonSetContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.DaemonSet).Spec.Template.Spec.Containers\n}", "func createStatefulSetService(name string, labels map[string]string) *v1.Service {\n\theadlessService := &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: labels,\n\t\t},\n\t}\n\theadlessService.Spec.Ports = []v1.ServicePort{\n\t\t{Port: 80, Name: \"http\", Protocol: v1.ProtocolTCP},\n\t}\n\theadlessService.Spec.ClusterIP = \"None\"\n\treturn headlessService\n}", "func NewSet(root *cobra.Command) {\n\troot.AddCommand(setCmd)\n\n\t// Here you will define your flags and configuration settings.\n\n\t// Cobra supports Persistent Flags which will work for this command\n\t// and all subcommands, e.g.:\n\t// listCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t// Cobra supports local flags which will only run when this command\n\t// is called directly, e.g.:\n\t// listCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}", "func createDefaultDC(ctx context.Context, p *gtm, defaultID int, domainName string) (*Datacenter, error) {\n\n\tif defaultID != MapDefaultDC && defaultID != Ipv4DefaultDC && defaultID != Ipv6DefaultDC {\n\t\treturn nil, fmt.Errorf(\"Invalid default datacenter id provided for creation\")\n\t}\n\t// check if already exists\n\tdc, err := p.GetDatacenter(ctx, defaultID, domainName)\n\tif err == nil {\n\t\treturn dc, err\n\t}\n\tapiError, ok := err.(*Error)\n\t//if !strings.Contains(err.Error(), \"not found\") || !strings.Contains(err.Error(), \"Datacenter\") {\n\tif !ok || apiError.StatusCode != http.StatusNotFound {\n\t\treturn nil, err\n\t}\n\n\tdefaultURL := fmt.Sprintf(\"/config-gtm/v1/domains/%s/datacenters/\", domainName)\n\tswitch defaultID {\n\tcase MapDefaultDC:\n\t\tdefaultURL += \"default-datacenter-for-maps\"\n\tcase Ipv4DefaultDC:\n\t\tdefaultURL += \"datacenter-for-ip-version-selector-ipv4\"\n\tcase Ipv6DefaultDC:\n\t\tdefaultURL += \"datacenter-for-ip-version-selector-ipv6\"\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, defaultURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Default Datacenter request: %w\", err)\n\t}\n\n\tvar dcresp DatacenterResponse\n\tsetVersionHeader(req, schemaVersion)\n\tresp, err := p.Exec(req, &dcresp, \"\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Default Datacenter request failed: %w\", err)\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\treturn nil, p.Error(resp)\n\t}\n\n\treturn dcresp.Resource, nil\n\n}", "func (operator *AccessOperator) CreateConfigSet(cxt context.Context, option *accessserver.CreateConfigSetReq) (string, error) {\n\tif option == nil {\n\t\treturn \"\", fmt.Errorf(\"Lost create new ConfigSet info\")\n\t}\n\tgrpcOptions := []grpc.CallOption{\n\t\tgrpc.WaitForReady(true),\n\t}\n\toption.Seq = pkgcommon.Sequence()\n\tresponse, err := operator.Client.CreateConfigSet(cxt, option, grpcOptions...)\n\tif err != nil {\n\t\tlogger.V(3).Infof(\"CreateConfigSet: post new ConfigSet [%s] failed, %s\", option.Name, err.Error())\n\t\treturn \"\", err\n\t}\n\tif response.ErrCode != common.ErrCode_E_OK {\n\t\tlogger.V(3).Infof(\n\t\t\t\"CreateConfigSet: post new configset [%s] successfully, but response failed: %s\",\n\t\t\toption.Name, response.ErrMsg,\n\t\t)\n\t\treturn \"\", fmt.Errorf(\"%s\", response.ErrMsg)\n\t}\n\tif len(response.Cfgsetid) == 0 {\n\t\tlogger.V(3).Infof(\"CreateConfigSet: BSCP system error, No ConfigSetID response\")\n\t\treturn \"\", fmt.Errorf(\"Lost ConfigSetID from configuraiotn platform\")\n\t}\n\treturn response.Cfgsetid, nil\n}", "func NewDaemon(config *Config) (daemon *Daemon, err error) {\n\t// Ensure we have compatible and valid configuration options\n\tif err := verifyDaemonSettings(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Verify the platform is supported as a daemon\n\tif !platformSupported {\n\t\treturn nil, errSystemNotSupported\n\t}\n\t// Validate platform-specific requirements\n\tif err := checkSystem(config.Root); err != nil {\n\t\treturn nil, err\n\t}\n\t// set up SIGUSR1 handler on Unix-like systems, or a Win32 global event\n\t// on Windows to dump Go routine stacks\n\tsetupDumpStackTrap()\n\n\td := &Daemon{configStore: config}\n\t// Ensure the daemon is properly shutdown if there is a failure during\n\t// initialization\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := d.Shutdown(); err != nil {\n\t\t\t\tlogrus.Error(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err := configureMaxThreads(config); err != nil {\n\t\tlogrus.Warnf(\"Failed to configure golang's threads limit: %v\", err)\n\t}\n\n\tpubkey, err := api.LoadSignPubKey(filepath.Join(cfg.GetCertPath(),\n\t\tcfg.DefaultRsaSignFile))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.pubKey = pubkey\n\n\teventsService := events.New()\n\td.EventsService = eventsService\n\n\tif err := d.restore(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func WaitForDaemonSet(t *testing.T, kubeclient kubernetes.Interface, namespace, name string, retryInterval, timeout time.Duration) error {\n\tstart := time.Now()\n\terr := wait.Poll(retryInterval, timeout, func() (done bool, err error) {\n\t\tctxWithTimeout, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\n\t\tdaemonset, err := kubeclient.AppsV1().DaemonSets(namespace).Get(ctxWithTimeout, name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tt.Logf(\"Waiting for availability of %s daemonset\\n\", name)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tif daemonset.Status.NumberReady > 0 && daemonset.Status.NumberReady == daemonset.Status.DesiredNumberScheduled {\n\t\t\treturn true, nil\n\t\t}\n\t\tt.Logf(\"Waiting for full availability of %s daemonsets (%d/%d)\\n\", name, daemonset.Status.NumberReady, daemonset.Status.DesiredNumberScheduled)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Logf(\"Failed waiting for daemonset %s after %s\\n\", name, time.Since(start))\n\t\treturn err\n\t}\n\tt.Logf(\"DaemonSet %s available after %s\\n\", name, time.Since(start))\n\treturn nil\n}", "func NewDaemon(\n\tconfig *Config,\n\tsqsClient SQSClient,\n\tsnsClient SNSClient,\n\tasgClient AutoscalingClient,\n\tmetadata *ec2metadata.EC2Metadata,\n\tlogger *logrus.Logger,\n) *Daemon {\n\tdaemon := &Daemon{\n\t\tinstanceID: config.InstanceID,\n\t\tlogger: logger,\n\t}\n\tif config.SpotListener {\n\t\tdaemon.AddListener(NewSpotListener(config.InstanceID, metadata, config.SpotListenerInterval))\n\t}\n\tif config.SNSTopic != \"\" {\n\t\tqueue := NewQueue(\n\t\t\tfmt.Sprintf(\"lifecycled-%s\", config.InstanceID),\n\t\t\tconfig.SNSTopic,\n\t\t\tsqsClient,\n\t\t\tsnsClient,\n\t\t)\n\t\tdaemon.AddListener(NewAutoscalingListener(config.InstanceID, queue, asgClient, config.AutoscalingHeartbeatInterval))\n\t}\n\treturn daemon\n}", "func CreateNewStatefulSet(k8sClient kubernetes.Interface, namespace string,\n\tsvc *appsv1.StatefulSet) error {\n\t_, err := k8sClient.AppsV1().\n\t\tStatefulSets(namespace).\n\t\tCreate(svc)\n\treturn err\n}", "func ReconcileDaemonSet(c client.Client, hdfs hdfsv1.HDFS, expected v1.DaemonSet) (v1.DaemonSet, error) {\n\n\t//create kind instance\n\tvar reconciled v1.DaemonSet\n\terr := ReconcileResource(Params{\n\t\tClient: c,\n\t\tOwner: &hdfs,\n\t\tExpected: &expected,\n\t\tReconciled: &reconciled,\n\t})\n\n\treturn reconciled, err\n}", "func TestRollingUpdateDaemonSetExistingPodAdoption(t *testing.T) {\n\tserver, closeFn, dc, informers, clientset := setup(t)\n\tdefer closeFn()\n\n\ttearDownFn := setupGC(t, server)\n\tdefer tearDownFn()\n\n\tns := framework.CreateTestingNamespace(\"rolling-update-daemonset-existing-pod-adoption-test\", server, t)\n\tdefer framework.DeleteTestingNamespace(ns, server, t)\n\n\tdsClient := clientset.AppsV1().DaemonSets(ns.Name)\n\tpodClient := clientset.CoreV1().Pods(ns.Name)\n\tnodeClient := clientset.CoreV1().Nodes()\n\tpodInformer := informers.Core().V1().Pods().Informer()\n\tcontrollerRevisionClient := clientset.AppsV1().ControllerRevisions(ns.Name)\n\tstopCh := make(chan struct{})\n\tdefer close(stopCh)\n\tinformers.Start(stopCh)\n\tgo dc.Run(5, stopCh)\n\n\t// Step 1: create a RollingUpdate DaemonSet\n\tdsName := \"daemonset\"\n\tds := newDaemonSet(dsName, ns.Name)\n\tds.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds, err := dsClient.Create(ds)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName, err)\n\t}\n\n\tnodeName := \"single-node\"\n\tnode := newNode(nodeName, nil)\n\t_, err = nodeClient.Create(node)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create node %q: %v\", nodeName, err)\n\t}\n\n\t// Validate everything works correctly (include marking daemon pod as ready)\n\tvalidateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t)\n\tvalidateDaemonSetStatus(dsClient, ds.Name, ds.Namespace, 1, t)\n\n\t// Step 2: delete daemonset and orphan its pods\n\tdeleteDaemonSetAndOrphanPods(dsClient, podClient, controllerRevisionClient, podInformer, ds, t)\n\n\t// Step 3: create 2rd daemonset to adopt the pods (no restart) as long as template matches\n\tdsName2 := \"daemonset-adopt-template-matches\"\n\tds2 := newDaemonSet(dsName2, ns.Name)\n\tds2.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds2, err = dsClient.Create(ds2)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName2, err)\n\t}\n\tif !apiequality.Semantic.DeepEqual(ds2.Spec.Template, ds.Spec.Template) {\n\t\tt.Fatalf(\".spec.template of new daemonset %q and old daemonset %q are not the same\", dsName2, dsName)\n\t}\n\n\t// Wait for pods and history to be adopted by 2nd daemonset\n\twaitDaemonSetAdoption(podClient, controllerRevisionClient, podInformer, ds2, ds.Name, t)\n\tvalidateDaemonSetStatus(dsClient, ds2.Name, ds2.Namespace, 1, t)\n}", "func (k *API) DaemonSets(namespace string) (*v1.DaemonSetList, error) {\n\tdaemonSets, err := k.Client.AppsV1().DaemonSets(namespace).List(context.Background(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn daemonSets, nil\n}", "func NewDeviceSet(root string, doInit bool, options []string, uidMaps, gidMaps []idtools.IDMap) (*DeviceSet, error) {\n\tdevicemapper.SetDevDir(\"/dev\")\n\n\tdevices := &DeviceSet{\n\t\troot: root,\n\t\tmetaData: metaData{Devices: make(map[string]*devInfo)},\n\t\tdataLoopbackSize: defaultDataLoopbackSize,\n\t\tmetaDataLoopbackSize: defaultMetaDataLoopbackSize,\n\t\tbaseFsSize: defaultBaseFsSize,\n\t\toverrideUdevSyncCheck: defaultUdevSyncOverride,\n\t\tdoBlkDiscard: true,\n\t\tthinpBlockSize: defaultThinpBlockSize,\n\t\tdeviceIDMap: make([]byte, deviceIDMapSz),\n\t\tdeletionWorkerTicker: time.NewTicker(time.Second * 30),\n\t\tuidMaps: uidMaps,\n\t\tgidMaps: gidMaps,\n\t\tminFreeSpacePercent: defaultMinFreeSpacePercent,\n\t}\n\n\tversion, err := devicemapper.GetDriverVersion()\n\tif err != nil {\n\t\t// Can't even get driver version, assume not supported\n\t\treturn nil, graphdriver.ErrNotSupported\n\t}\n\n\tif err := determineDriverCapabilities(version); err != nil {\n\t\treturn nil, graphdriver.ErrNotSupported\n\t}\n\n\tif driverDeferredRemovalSupport && devicemapper.LibraryDeferredRemovalSupport {\n\t\t// enable deferred stuff by default\n\t\tenableDeferredDeletion = true\n\t\tenableDeferredRemoval = true\n\t}\n\n\tfoundBlkDiscard := false\n\tvar lvmSetupConfig directLVMConfig\n\ttestMode := false\n\tfor _, option := range options {\n\t\tkey, val, err := parsers.ParseKeyValueOpt(option)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tkey = strings.ToLower(key)\n\t\tswitch key {\n\t\tcase \"dm.basesize\":\n\t\t\tsize, err := units.RAMInBytes(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tuserBaseSize = true\n\t\t\tdevices.baseFsSize = uint64(size)\n\t\tcase \"dm.loopdatasize\":\n\t\t\tsize, err := units.RAMInBytes(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdevices.dataLoopbackSize = size\n\t\tcase \"dm.loopmetadatasize\":\n\t\t\tsize, err := units.RAMInBytes(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdevices.metaDataLoopbackSize = size\n\t\tcase \"dm.fs\":\n\t\t\tif val != ext4 && val != xfs {\n\t\t\t\treturn nil, fmt.Errorf(\"devmapper: Unsupported filesystem %s\", val)\n\t\t\t}\n\t\t\tdevices.filesystem = val\n\t\tcase \"dm.mkfsarg\":\n\t\t\tdevices.mkfsArgs = append(devices.mkfsArgs, val)\n\t\tcase \"dm.mountopt\", \"devicemapper.mountopt\":\n\t\t\tdevices.mountOptions = joinMountOptions(devices.mountOptions, val)\n\t\tcase \"dm.metadatadev\":\n\t\t\tdevices.metadataDevice = val\n\t\tcase \"dm.metadata_size\":\n\t\t\tdevices.metaDataSize = val\n\t\tcase \"dm.datadev\":\n\t\t\tdevices.dataDevice = val\n\t\tcase \"dm.thinpooldev\":\n\t\t\tdevices.thinPoolDevice = strings.TrimPrefix(val, \"/dev/mapper/\")\n\t\tcase \"dm.blkdiscard\":\n\t\t\tfoundBlkDiscard = true\n\t\t\tdevices.doBlkDiscard, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase \"dm.blocksize\":\n\t\t\tsize, err := units.RAMInBytes(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// convert to 512b sectors\n\t\t\tdevices.thinpBlockSize = uint32(size) >> 9\n\t\tcase \"dm.override_udev_sync_check\":\n\t\t\tdevices.overrideUdevSyncCheck, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase \"dm.use_deferred_removal\":\n\t\t\tenableDeferredRemoval, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase \"dm.use_deferred_deletion\":\n\t\t\tenableDeferredDeletion, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\tcase \"dm.metaDataSize\":\n\t\t\tlvmSetupConfig.MetaDataSize = val\n\t\tcase \"dm.min_free_space\":\n\t\t\tif !strings.HasSuffix(val, \"%\") {\n\t\t\t\treturn nil, fmt.Errorf(\"devmapper: Option dm.min_free_space requires %% suffix\")\n\t\t\t}\n\n\t\t\tvalstring := strings.TrimSuffix(val, \"%\")\n\t\t\tminFreeSpacePercent, err := strconv.ParseUint(valstring, 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif minFreeSpacePercent >= 100 {\n\t\t\t\treturn nil, fmt.Errorf(\"devmapper: Invalid value %v for option dm.min_free_space\", val)\n\t\t\t}\n\n\t\t\tdevices.minFreeSpacePercent = uint32(minFreeSpacePercent)\n\t\tcase \"dm.xfs_nospace_max_retries\":\n\t\t\t_, err := strconv.ParseUint(val, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdevices.xfsNospaceRetries = val\n\t\tcase \"dm.directlvm_device\":\n\t\t\tlvmSetupConfig.Device = val\n\t\tcase \"dm.directlvm_device_force\":\n\t\t\tlvmSetupConfigForce, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase \"dm.thinp_percent\":\n\t\t\tper, err := strconv.ParseUint(strings.TrimSuffix(val, \"%\"), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not parse `dm.thinp_percent=%s`: %w\", val, err)\n\t\t\t}\n\t\t\tif per >= 100 {\n\t\t\t\treturn nil, errors.New(\"dm.thinp_percent must be greater than 0 and less than 100\")\n\t\t\t}\n\t\t\tlvmSetupConfig.ThinpPercent = per\n\t\tcase \"dm.thinp_metapercent\":\n\t\t\tper, err := strconv.ParseUint(strings.TrimSuffix(val, \"%\"), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not parse `dm.thinp_metapercent=%s`: %w\", val, err)\n\t\t\t}\n\t\t\tif per >= 100 {\n\t\t\t\treturn nil, errors.New(\"dm.thinp_metapercent must be greater than 0 and less than 100\")\n\t\t\t}\n\t\t\tlvmSetupConfig.ThinpMetaPercent = per\n\t\tcase \"dm.thinp_autoextend_percent\":\n\t\t\tper, err := strconv.ParseUint(strings.TrimSuffix(val, \"%\"), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not parse `dm.thinp_autoextend_percent=%s`: %w\", val, err)\n\t\t\t}\n\t\t\tif per > 100 {\n\t\t\t\treturn nil, errors.New(\"dm.thinp_autoextend_percent must be greater than 0 and less than 100\")\n\t\t\t}\n\t\t\tlvmSetupConfig.AutoExtendPercent = per\n\t\tcase \"dm.thinp_autoextend_threshold\":\n\t\t\tper, err := strconv.ParseUint(strings.TrimSuffix(val, \"%\"), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not parse `dm.thinp_autoextend_threshold=%s`: %w\", val, err)\n\t\t\t}\n\t\t\tif per > 100 {\n\t\t\t\treturn nil, errors.New(\"dm.thinp_autoextend_threshold must be greater than 0 and less than 100\")\n\t\t\t}\n\t\t\tlvmSetupConfig.AutoExtendThreshold = per\n\t\tcase \"dm.libdm_log_level\":\n\t\t\tlevel, err := strconv.ParseInt(val, 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not parse `dm.libdm_log_level=%s`: %w\", val, err)\n\t\t\t}\n\t\t\tif level < devicemapper.LogLevelFatal || level > devicemapper.LogLevelDebug {\n\t\t\t\treturn nil, fmt.Errorf(\"dm.libdm_log_level must be in range [%d,%d]\", devicemapper.LogLevelFatal, devicemapper.LogLevelDebug)\n\t\t\t}\n\t\t\t// Register a new logging callback with the specified level.\n\t\t\tdevicemapper.LogInit(devicemapper.DefaultLogger{\n\t\t\t\tLevel: int(level),\n\t\t\t})\n\t\tcase \"test\":\n\t\t\ttestMode, err = strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"devmapper: Unknown option %s\", key)\n\t\t}\n\t}\n\n\tif !testMode {\n\t\tif err := validateLVMConfig(lvmSetupConfig); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdevices.lvmSetupConfig = lvmSetupConfig\n\n\t// By default, don't do blk discard hack on raw devices, its rarely useful and is expensive\n\tif !foundBlkDiscard && (devices.dataDevice != \"\" || devices.thinPoolDevice != \"\") {\n\t\tdevices.doBlkDiscard = false\n\t}\n\n\tif err := devices.initDevmapper(doInit); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn devices, nil\n}", "func UpdateDaemonSet(client *kubernetes.Clientset, namespace string, resource interface{}) error {\n\tdaemonSet := resource.(appsv1.DaemonSet)\n\t_, err := client.AppsV1().DaemonSets(namespace).Update(context.TODO(), &daemonSet, metav1.UpdateOptions{})\n\treturn err\n}", "func (in *DaemonsetRef) DeepCopy() *DaemonsetRef {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DaemonsetRef)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func New(opts ...Option) (Daemon, error) {\n\tp := &policyd{\n\t\trolePolicies: gache.New(),\n\t\tetagCache: gache.New(),\n\t}\n\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\tif err := opt(p); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"error create policyd\")\n\t\t}\n\t}\n\n\treturn p, nil\n}", "func CreateDataset(cmd *cobra.Command, args []string) error {\n\n\tclient, err := auth.GetClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Parse all flags\n\n\tvar fields []model.FieldPost\n\terr = flags.ParseFlag(cmd.Flags(), \"fields\", &fields)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"fields\": ` + err.Error())\n\t}\n\tvar idDefault string\n\tid := &idDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"id\", &id)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"id\": ` + err.Error())\n\t}\n\tvar moduleDefault string\n\tmodule := &moduleDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"module\", &module)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"module\": ` + err.Error())\n\t}\n\tvar name string\n\terr = flags.ParseFlag(cmd.Flags(), \"name\", &name)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"name\": ` + err.Error())\n\t}\n\t// Form the request body\n\tgenerated_request_body := model.DatasetPost{\n\n\t\tFields: fields,\n\t\tId: id,\n\t\tModule: module,\n\t\tName: name,\n\t}\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\tresp, err := client.SearchService.CreateDataset(generated_request_body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonx.Pprint(cmd, resp)\n\treturn nil\n}", "func DefineCreateDefaults(opts *entities.ContainerCreateOptions) {\n\topts.LogDriver = LogDriver()\n\topts.CgroupsMode = cgroupConfig()\n\topts.MemorySwappiness = -1\n\topts.ImageVolume = podmanConfig.ContainersConfDefaultsRO.Engine.ImageVolumeMode\n\topts.Pull = policy()\n\topts.ReadWriteTmpFS = true\n\topts.SdNotifyMode = define.SdNotifyModeContainer\n\topts.StopTimeout = podmanConfig.ContainersConfDefaultsRO.Engine.StopTimeout\n\topts.Systemd = \"true\"\n\topts.Timezone = podmanConfig.ContainersConfDefaultsRO.TZ()\n\topts.Umask = podmanConfig.ContainersConfDefaultsRO.Umask()\n\topts.Ulimit = ulimits()\n\topts.SeccompPolicy = \"default\"\n\topts.Volume = volumes()\n}", "func NewSharedSecretSetCreate(contentProviderId int32, name string) *SharedSecretSetCreate {\n\tthis := SharedSecretSetCreate{}\n\tthis.ContentProviderId = contentProviderId\n\tthis.Name = name\n\treturn &this\n}", "func (dsl *DaemonSetLock) GetDaemonSet(sleep, timeout time.Duration) (*v1.DaemonSet, error) {\n\tvar ds *v1.DaemonSet\n\tvar lastError error\n\terr := wait.PollImmediate(sleep, timeout, func() (bool, error) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tif ds, lastError = dsl.client.AppsV1().DaemonSets(dsl.namespace).Get(ctx, dsl.name, metav1.GetOptions{}); lastError != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Timed out trying to get daemonset %s in namespace %s: %v\", dsl.name, dsl.namespace, lastError)\n\t}\n\treturn ds, nil\n}", "func (o SetOptions) New(elements ...interface{}) (set Set) {\n\tif o.Unsafe {\n\t\tnewSet := o.newThreadUnsafeSet()\n\t\tset = &newSet\n\t} else {\n\t\tnewSet := o.newThreadSafeSet()\n\t\tset = &newSet\n\t}\n\tset.Add(elements...)\n\treturn\n}", "func GetDaemonSetInitContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.DaemonSet).Spec.Template.Spec.InitContainers\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}", "func createCustomisedStatefulSets(client clientset.Interface, namespace string,\n\tisParallelPodMgmtPolicy bool, replicas int32, nodeAffinityToSet bool,\n\tallowedTopologies []v1.TopologySelectorLabelRequirement, allowedTopologyLen int,\n\tpodAntiAffinityToSet bool, modifyStsSpec bool, stsName string,\n\taccessMode v1.PersistentVolumeAccessMode, sc *storagev1.StorageClass) *appsv1.StatefulSet {\n\tframework.Logf(\"Preparing StatefulSet Spec\")\n\tstatefulset := GetStatefulSetFromManifest(namespace)\n\n\tif accessMode == \"\" {\n\t\t// If accessMode is not specified, set the default accessMode.\n\t\taccessMode = v1.ReadWriteOnce\n\t}\n\n\tif modifyStsSpec {\n\t\tstatefulset.Spec.VolumeClaimTemplates[len(statefulset.Spec.VolumeClaimTemplates)-1].\n\t\t\tAnnotations[\"volume.beta.kubernetes.io/storage-class\"] = sc.Name\n\t\tstatefulset.Spec.VolumeClaimTemplates[len(statefulset.Spec.VolumeClaimTemplates)-1].Spec.AccessModes[0] =\n\t\t\taccessMode\n\t\tstatefulset.Name = stsName\n\t\tstatefulset.Spec.Template.Labels[\"app\"] = statefulset.Name\n\t\tstatefulset.Spec.Selector.MatchLabels[\"app\"] = statefulset.Name\n\t}\n\tif nodeAffinityToSet {\n\t\tnodeSelectorTerms := getNodeSelectorTerms(allowedTopologies)\n\t\tstatefulset.Spec.Template.Spec.Affinity = new(v1.Affinity)\n\t\tstatefulset.Spec.Template.Spec.Affinity.NodeAffinity = new(v1.NodeAffinity)\n\t\tstatefulset.Spec.Template.Spec.Affinity.NodeAffinity.\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution = new(v1.NodeSelector)\n\t\tstatefulset.Spec.Template.Spec.Affinity.NodeAffinity.\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms = nodeSelectorTerms\n\t}\n\tif podAntiAffinityToSet {\n\t\tstatefulset.Spec.Template.Spec.Affinity = &v1.Affinity{\n\t\t\tPodAntiAffinity: &v1.PodAntiAffinity{\n\t\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{\n\t\t\t\t\t{\n\t\t\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\t\t\t\"key\": \"app\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTopologyKey: \"topology.kubernetes.io/zone\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t}\n\tif isParallelPodMgmtPolicy {\n\t\tstatefulset.Spec.PodManagementPolicy = appsv1.ParallelPodManagement\n\t}\n\tstatefulset.Spec.Replicas = &replicas\n\n\tframework.Logf(\"Creating statefulset\")\n\tCreateStatefulSet(namespace, statefulset, client)\n\n\tframework.Logf(\"Wait for StatefulSet pods to be in up and running state\")\n\tfss.WaitForStatusReadyReplicas(client, statefulset, replicas)\n\tgomega.Expect(fss.CheckMount(client, statefulset, mountPath)).NotTo(gomega.HaveOccurred())\n\tssPodsBeforeScaleDown := fss.GetPodList(client, statefulset)\n\tgomega.Expect(ssPodsBeforeScaleDown.Items).NotTo(gomega.BeEmpty(),\n\t\tfmt.Sprintf(\"Unable to get list of Pods from the Statefulset: %v\", statefulset.Name))\n\tgomega.Expect(len(ssPodsBeforeScaleDown.Items) == int(replicas)).To(gomega.BeTrue(),\n\t\t\"Number of Pods in the statefulset should match with number of replicas\")\n\n\treturn statefulset\n}", "func NewMockDaemonSetFinalizer(ctrl *gomock.Controller) *MockDaemonSetFinalizer {\n\tmock := &MockDaemonSetFinalizer{ctrl: ctrl}\n\tmock.recorder = &MockDaemonSetFinalizerMockRecorder{mock}\n\treturn mock\n}", "func (c *ClientSetClient) GetDaemonSet(namespace, name string) (*appsv1.DaemonSet, error) {\n\tctx := context.TODO()\n\treturn c.clientset.AppsV1().DaemonSets(namespace).Get(ctx, name, metav1.GetOptions{})\n}", "func desiredNodeResolverDaemonSet(dns *operatorv1.DNS, clusterIP, clusterDomain, openshiftCLIImage string) (bool, *appsv1.DaemonSet, error) {\n\thostPathFile := corev1.HostPathFile\n\t// TODO: Consider setting maxSurge to a positive value.\n\tmaxSurge := intstr.FromInt(0)\n\tmaxUnavailable := intstr.FromString(\"33%\")\n\tenvs := []corev1.EnvVar{{\n\t\tName: \"SERVICES\",\n\t\tValue: services,\n\t}}\n\tif len(clusterIP) > 0 {\n\t\tenvs = append(envs, corev1.EnvVar{\n\t\t\tName: \"NAMESERVER\",\n\t\t\tValue: clusterIP,\n\t\t})\n\t}\n\tif len(clusterDomain) > 0 {\n\t\tenvs = append(envs, corev1.EnvVar{\n\t\t\tName: \"CLUSTER_DOMAIN\",\n\t\t\tValue: clusterDomain,\n\t\t})\n\t}\n\ttrueVal := true\n\tname := NodeResolverDaemonSetName()\n\tdaemonset := appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name.Name,\n\t\t\tNamespace: name.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\tdnsOwnerRef(dns),\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: NodeResolverDaemonSetPodSelector(),\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tworkloadPartitioningManagement: `{\"effect\": \"PreferredDuringScheduling\"}`,\n\t\t\t\t\t},\n\t\t\t\t\tLabels: NodeResolverDaemonSetPodSelector().MatchLabels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tCommand: []string{\n\t\t\t\t\t\t\t\"/bin/bash\", \"-c\",\n\t\t\t\t\t\t\tnodeResolverScript,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tEnv: envs,\n\t\t\t\t\t\tImage: openshiftCLIImage,\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\tName: \"dns-node-resolver\",\n\t\t\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\t\t\tRequests: corev1.ResourceList{\n\t\t\t\t\t\t\t\tcorev1.ResourceCPU: resource.MustParse(\"5m\"),\n\t\t\t\t\t\t\t\tcorev1.ResourceMemory: resource.MustParse(\"21Mi\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\tPrivileged: &trueVal,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,\n\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{{\n\t\t\t\t\t\t\tName: \"hosts-file\",\n\t\t\t\t\t\t\tMountPath: \"/etc/hosts\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t\t// The node-resolver pods need to run on\n\t\t\t\t\t// every node in the cluster. On nodes\n\t\t\t\t\t// that have Smart NICs, each pod that\n\t\t\t\t\t// uses the container network consumes\n\t\t\t\t\t// an SR-IOV device. Using the host\n\t\t\t\t\t// network eliminates the need for this\n\t\t\t\t\t// scarce resource.\n\t\t\t\t\tHostNetwork: true,\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"kubernetes.io/os\": \"linux\",\n\t\t\t\t\t},\n\t\t\t\t\tPriorityClassName: \"system-node-critical\",\n\t\t\t\t\tServiceAccountName: \"node-resolver\",\n\t\t\t\t\tTolerations: []corev1.Toleration{{\n\t\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t\t}},\n\t\t\t\t\tVolumes: []corev1.Volume{{\n\t\t\t\t\t\tName: \"hosts-file\",\n\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\tPath: \"/etc/hosts\",\n\t\t\t\t\t\t\t\tType: &hostPathFile,\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\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDaemonSetStrategyType,\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxSurge: &maxSurge,\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn true, &daemonset, nil\n}", "func FlagSetCreateGauge() *flag.FlagSet {\n\tfs := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\n\tdur, _ := time.ParseDuration(\"24h\")\n\tfs.Duration(FlagDuration, dur, \"The duration token to be locked, default 1d(24h). Other examples are 7d(168h), 14d(336h). Maximum unit is hour.\")\n\tfs.String(FlagStartTime, \"\", \"Timestamp to begin distribution\")\n\tfs.Uint64(FlagEpochs, 0, \"Total epochs to distribute tokens\")\n\tfs.Bool(FlagPerpetual, false, \"Perpetual distribution\")\n\treturn fs\n}", "func NewSet(host *Host, name string) (*Set, error) {\n\ts := &Set{host, pq.QuoteIdentifier(name)} // name is the name of the table\n\t// list is the name of the column\n\tif _, err := s.host.db.Exec(fmt.Sprintf(\"CREATE TABLE IF NOT EXISTS %s (%s %s)\", s.table, setCol, defaultStringType)); err != nil {\n\t\tif !strings.HasSuffix(err.Error(), \"already exists\") {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif Verbose {\n\t\tlog.Println(\"Created table \" + s.table + \" in database \" + host.dbname)\n\t}\n\treturn s, nil\n}", "func (o *ExpirationOptions) Run(cmd *cobra.Command) error {\n\tvar err error\n\tclientConfig, err = o.configFlags.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcoreclient, err := coreV1Client.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif o.checkKubelet {\n\t\tdaemonSet := &appv1.DaemonSet{\n\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tSpec: appv1.DaemonSetSpec{\n\t\t\t\tUpdateStrategy: appv1.DaemonSetUpdateStrategy{\n\t\t\t\t\tType: appv1.RollingUpdateDaemonSetStrategyType,\n\t\t\t\t\tRollingUpdate: &appv1.RollingUpdateDaemonSet{\n\t\t\t\t\t\tMaxUnavailable: &max,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSelector: &meta_v1.LabelSelector{\n\t\t\t\t\tMatchLabels: matchLabel,\n\t\t\t\t},\n\t\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\t\t\tLabels: matchLabel,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t\tHostPID: true,\n\t\t\t\t\t\tHostNetwork: true,\n\t\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\t\tName: name,\n\t\t\t\t\t\t\tImage: imageName,\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullAlways,\n\t\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: etcKubernetesName,\n\t\t\t\t\t\t\t\t\tMountPath: etcKubernetesPath,\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\tName: varLibKubeletName,\n\t\t\t\t\t\t\t\t\tMountPath: varLibKubeletPath,\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\tName: hostnameName,\n\t\t\t\t\t\t\t\t\tMountPath: hostnamePath,\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\tName: tmpProcName,\n\t\t\t\t\t\t\t\t\tMountPath: tmpProcPath,\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\tRestartPolicy: corev1.RestartPolicyAlways,\n\t\t\t\t\t\tTolerations: []corev1.Toleration{{\n\t\t\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t\t\t}},\n\t\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: etcKubernetesName,\n\t\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tType: &hostPathType,\n\t\t\t\t\t\t\t\t\t\tPath: etcKubernetesPath,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\tName: varLibKubeletName,\n\t\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tType: &hostPathType,\n\t\t\t\t\t\t\t\t\t\tPath: varLibKubeletPath,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\tName: hostnameName,\n\t\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tType: &hostPathFileType,\n\t\t\t\t\t\t\t\t\t\tPath: hostnamePath,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\tName: tmpProcName,\n\t\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\t\tType: &hostPathType,\n\t\t\t\t\t\t\t\t\t\tPath: realProcPath,\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\n\t\tappClient, err := appsV1Client.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = appClient.DaemonSets(defaultNamespace).Create(daemonSet)\n\n\t\tdefer appClient.DaemonSets(defaultNamespace).Delete(name, nil)\n\t}\n\n\tapiServerPods, err := getPods(\n\t\tcoreclient, kubesystemNamespace, \"component=kube-apiserver,tier=control-plane\")\n\tif err != nil {\n\t\tfmt.Println(\"Apiserver is not exists. Skip.\")\n\t}\n\n\tcontrollerManagerPods, err := getPods(\n\t\tcoreclient, kubesystemNamespace, \"component=kube-controller-manager,tier=control-plane\")\n\tif err != nil {\n\t\tfmt.Println(\"ControllerManager is not exists. Skip.\")\n\t}\n\n\tschedulerManagerPods, err := getPods(\n\t\tcoreclient, kubesystemNamespace, \"component=kube-scheduler,tier=control-plane\")\n\tif err != nil {\n\t\tfmt.Println(\"Scheduler is not exists. Skip.\")\n\t}\n\n\tdsPodCount := 0\n\tif o.checkKubelet {\n\t\tappClient, err := appsV1Client.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdsClient := appClient.DaemonSets(defaultNamespace)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Exist already\")\n\t\t} else {\n\t\t\tfor {\n\t\t\t\ttime.Sleep(time.Second / 2)\n\n\t\t\t\tds, err := dsClient.Get(name, meta_v1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif ds.Status.DesiredNumberScheduled > 0 {\n\t\t\t\t\tdsPodCount = int(ds.Status.DesiredNumberScheduled)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbar := pb.New(len(apiServerPods.Items) + len(controllerManagerPods.Items) + len(schedulerManagerPods.Items) + dsPodCount)\n\tbar.SetWidth(80)\n\tbar.SetMaxWidth(80)\n\tbar.Start()\n\n\tvar wg sync.WaitGroup\n\tvar mutex = &sync.Mutex{}\n\n\tchannel := make(chan interface{})\n\n\tserverCertifications := make([]serverCertification, 0)\n\tfor _, apiServerPod := range apiServerPods.Items {\n\t\twg.Add(1)\n\t\tgo func(p corev1.Pod) {\n\t\t\tdefer wg.Done()\n\t\t\tfor _, c := range p.Spec.Containers[0].Command {\n\t\t\t\t// only for options\n\t\t\t\tif strings.HasPrefix(c, \"--\") {\n\t\t\t\t\ts := strings.Split(c[2:], \"=\")\n\t\t\t\t\tif s[0] == kubeletCAFlag && s[1] != \"\" {\n\t\t\t\t\t\tmutex.Lock()\n\t\t\t\t\t\tcheckKubeletWithCA = true\n\t\t\t\t\t\tmutex.Unlock()\n\t\t\t\t\t}\n\t\t\t\t\tfor _, co := range certOptions {\n\t\t\t\t\t\tif co == s[0] {\n\t\t\t\t\t\t\tcert, err := ExecPod(coreclient, kubesystemNamespace, &p, []string{\"cat\", s[1]})\n\t\t\t\t\t\t\terrorStr := \"\"\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\terrorStr = err.Error()\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdate, days, err := GetDateAndDaysFromCert(cert)\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\terrorStr = err.Error()\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\t\t\t\tType: \"apiserver\",\n\t\t\t\t\t\t\t\t\t\t\tNode: p.Spec.NodeName,\n\t\t\t\t\t\t\t\t\t\t\tName: s[0],\n\t\t\t\t\t\t\t\t\t\t\tPath: s[1],\n\t\t\t\t\t\t\t\t\t\t\tDays: days,\n\t\t\t\t\t\t\t\t\t\t\tDue: date,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\tWarning: \"\",\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\tif errorStr != \"\" {\n\t\t\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\t\t\tType: \"apiserver\",\n\t\t\t\t\t\t\t\t\t\tNode: p.Spec.NodeName,\n\t\t\t\t\t\t\t\t\t\tName: s[0],\n\t\t\t\t\t\t\t\t\t\tPath: s[1],\n\t\t\t\t\t\t\t\t\t\tDays: 0,\n\t\t\t\t\t\t\t\t\t\tDue: time.Time{},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tWarning: err.Error(),\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\tmutex.Lock()\n\t\t\tbar.Increment()\n\t\t\tmutex.Unlock()\n\t\t}(apiServerPod)\n\t}\n\n\tfor _, controllerManagerPod := range controllerManagerPods.Items {\n\t\twg.Add(1)\n\t\tgo func(p corev1.Pod) {\n\t\t\tdefer wg.Done()\n\t\t\tfor _, c := range p.Spec.Containers[0].Command {\n\t\t\t\t// only for options\n\t\t\t\tif strings.HasPrefix(c, \"--\") {\n\t\t\t\t\ts := strings.Split(c[2:], \"=\")\n\t\t\t\t\tif s[0] == kubeConfigFlag {\n\t\t\t\t\t\terrorResult := func(node string, errstr string) {\n\t\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\t\tType: \"controller-manager\",\n\t\t\t\t\t\t\t\t\tNode: node,\n\t\t\t\t\t\t\t\t\tName: \"client-cert\",\n\t\t\t\t\t\t\t\t\tPath: \"-\",\n\t\t\t\t\t\t\t\t\tDays: 0,\n\t\t\t\t\t\t\t\t\tDue: time.Time{},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tWarning: errstr,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tkubeconfig, err := ExecPod(coreclient, kubesystemNamespace, &p, []string{\"cat\", s[1]})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcfg, err := clientcmd.NewClientConfigFromBytes([]byte(kubeconfig))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\trawConfig, err := cfg.RawConfig()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar cert string\n\t\t\t\t\t\tvar path string\n\t\t\t\t\t\tcurrentContext := rawConfig.CurrentContext\n\t\t\t\t\t\tuser := rawConfig.Contexts[currentContext].AuthInfo\n\t\t\t\t\t\tu := rawConfig.AuthInfos[user]\n\n\t\t\t\t\t\tif string(u.ClientCertificateData) != \"\" {\n\t\t\t\t\t\t\tcert = string(u.ClientCertificateData)\n\t\t\t\t\t\t\tpath = s[1]\n\t\t\t\t\t\t} else if string(u.ClientCertificate) != \"\" {\n\t\t\t\t\t\t\tcert, err = ExecPod(coreclient, kubesystemNamespace, &p, []string{\"cat\", string(u.ClientCertificate)})\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpath = string(u.ClientCertificate)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdate, days, err := GetDateAndDaysFromCert(cert)\n\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\tType: \"controller-manager\",\n\t\t\t\t\t\t\t\tNode: p.Spec.NodeName,\n\t\t\t\t\t\t\t\tName: \"client-cert\",\n\t\t\t\t\t\t\t\tPath: path,\n\t\t\t\t\t\t\t\tDays: days,\n\t\t\t\t\t\t\t\tDue: date,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tWarning: \"\",\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmutex.Lock()\n\t\t\tbar.Increment()\n\t\t\tmutex.Unlock()\n\t\t}(controllerManagerPod)\n\t}\n\n\tfor _, schedulerManagerPod := range schedulerManagerPods.Items {\n\t\twg.Add(1)\n\t\tgo func(p corev1.Pod) {\n\t\t\tdefer wg.Done()\n\t\t\tfor _, c := range p.Spec.Containers[0].Command {\n\t\t\t\t// only for options\n\t\t\t\tif strings.HasPrefix(c, \"--\") {\n\t\t\t\t\ts := strings.Split(c[2:], \"=\")\n\t\t\t\t\tif s[0] == kubeConfigFlag {\n\t\t\t\t\t\terrorResult := func(node string, errstr string) {\n\t\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\t\tType: \"scheduler\",\n\t\t\t\t\t\t\t\t\tNode: node,\n\t\t\t\t\t\t\t\t\tName: \"client-cert\",\n\t\t\t\t\t\t\t\t\tPath: \"-\",\n\t\t\t\t\t\t\t\t\tDays: 0,\n\t\t\t\t\t\t\t\t\tDue: time.Time{},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tWarning: errstr,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tkubeconfig, err := ExecPod(coreclient, kubesystemNamespace, &p, []string{\"cat\", s[1]})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcfg, err := clientcmd.NewClientConfigFromBytes([]byte(kubeconfig))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\trawConfig, err := cfg.RawConfig()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar cert string\n\t\t\t\t\t\tvar path string\n\t\t\t\t\t\tcurrentContext := rawConfig.CurrentContext\n\t\t\t\t\t\tuser := rawConfig.Contexts[currentContext].AuthInfo\n\t\t\t\t\t\tu := rawConfig.AuthInfos[user]\n\n\t\t\t\t\t\tif string(u.ClientCertificateData) != \"\" {\n\t\t\t\t\t\t\tcert = string(u.ClientCertificateData)\n\t\t\t\t\t\t\tpath = s[1]\n\t\t\t\t\t\t} else if string(u.ClientCertificate) != \"\" {\n\t\t\t\t\t\t\tcert, err = ExecPod(coreclient, kubesystemNamespace, &p, []string{\"cat\", string(u.ClientCertificate)})\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpath = string(u.ClientCertificate)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\terrorResult(p.Spec.NodeName, err.Error())\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdate, days, err := GetDateAndDaysFromCert(cert)\n\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\t\tType: \"scheduler\",\n\t\t\t\t\t\t\t\tNode: p.Spec.NodeName,\n\t\t\t\t\t\t\t\tName: \"client-cert\",\n\t\t\t\t\t\t\t\tPath: path,\n\t\t\t\t\t\t\t\tDays: days,\n\t\t\t\t\t\t\t\tDue: date,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tWarning: \"\",\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmutex.Lock()\n\t\t\tbar.Increment()\n\t\t\tmutex.Unlock()\n\t\t}(schedulerManagerPod)\n\t}\n\n\tif o.checkKubelet {\n\t\tappClient, err := appsV1Client.NewForConfig(clientConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdsClient := appClient.DaemonSets(defaultNamespace)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Exist already\")\n\t\t} else {\n\t\t\tfor {\n\t\t\t\ttime.Sleep(time.Second / 2)\n\n\t\t\t\tds, err := dsClient.Get(name, meta_v1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif ds.Status.NumberAvailable == ds.Status.DesiredNumberScheduled && ds.Status.DesiredNumberScheduled > 0 {\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tkrawlerPods, err := getPods(\n\t\t\tcoreclient, defaultNamespace, fmt.Sprintf(\"app=%s\", name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, p := range krawlerPods.Items {\n\t\t\twg.Add(1)\n\t\t\tgo func(p corev1.Pod) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tfor i := 1; i <= 10; i++ {\n\t\t\t\t\tif p.Status.Phase != corev1.PodRunning {\n\t\t\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// p.Spec.NodeName\n\t\t\t\tvar command string\n\t\t\t\tfor i := 1; i <= 5; i++ {\n\t\t\t\t\tcommand, err = ExecPod(\n\t\t\t\t\t\tcoreclient,\n\t\t\t\t\t\tdefaultNamespace,\n\t\t\t\t\t\t&p,\n\t\t\t\t\t\t[]string{\"krawler\"},\n\t\t\t\t\t)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(time.Second / 2)\n\t\t\t\t}\n\n\t\t\t\tif value, ok := isJSON(command); ok {\n\t\t\t\t\tfor _, v := range value.Entries {\n\t\t\t\t\t\twarn := \"\"\n\t\t\t\t\t\tif v.Name == \"server-cert\" && checkKubeletWithCA == false {\n\t\t\t\t\t\t\twarn = \"Can be ignored this.\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\t\tEntry: v,\n\t\t\t\t\t\t\tWarning: warn,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tchannel <- serverCertification{\n\t\t\t\t\t\tEntry: Entry{\n\t\t\t\t\t\t\tType: \"kubelet\",\n\t\t\t\t\t\t\tNode: p.Spec.NodeName,\n\t\t\t\t\t\t\tName: \"Error\",\n\t\t\t\t\t\t\tPath: \"\",\n\t\t\t\t\t\t\tDays: 0,\n\t\t\t\t\t\t\tDue: time.Now(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tWarning: command,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmutex.Lock()\n\t\t\t\tbar.Increment()\n\t\t\t\tmutex.Unlock()\n\n\t\t\t}(p)\n\t\t}\n\t}\n\n\tgo func() {\n\t\tdefer close(channel)\n\t\twg.Wait()\n\t}()\n\n\tfor result := range channel {\n\t\tswitch v := result.(type) {\n\t\tcase serverCertification:\n\t\t\tserverCertifications = append(serverCertifications, v)\n\t\tdefault:\n\t\t\terr := fmt.Errorf(\"Unknown type %T, %+v\", result, result)\n\t\t\tlog.Error(err)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tbar.Finish()\n\tsort.Slice(serverCertifications, func(i, j int) bool {\n\t\tif serverCertifications[i].Entry.Type == \"scheduler\" && serverCertifications[j].Entry.Type == \"kubelet\" {\n\t\t\treturn true\n\t\t}\n\t\tif serverCertifications[i].Entry.Type == \"kubelet\" && serverCertifications[j].Entry.Type == \"scheduler\" {\n\t\t\treturn false\n\t\t}\n\t\tif serverCertifications[i].Entry.Type < serverCertifications[j].Entry.Type {\n\t\t\treturn true\n\t\t}\n\t\tif serverCertifications[i].Entry.Type > serverCertifications[j].Entry.Type {\n\t\t\treturn false\n\t\t}\n\t\tif serverCertifications[i].Entry.Node < serverCertifications[j].Entry.Node {\n\t\t\treturn true\n\t\t}\n\t\tif serverCertifications[i].Entry.Node > serverCertifications[j].Entry.Node {\n\t\t\treturn false\n\t\t}\n\t\treturn serverCertifications[i].Entry.Name < serverCertifications[j].Entry.Name\n\t})\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"Type\", \"Node\", \"Name\", \"Days\", \"Due\", \"Path\", \"Warning\"})\n\n\tfor _, v := range serverCertifications {\n\t\tm := []string{v.Entry.Type, v.Entry.Node, v.Entry.Name, cast.ToString(v.Entry.Days), v.Entry.Due.String(), v.Entry.Path, v.Warning}\n\t\ttable.Append(m)\n\t}\n\ttable.Render() // Send output\n\n\treturn nil\n}" ]
[ "0.7669294", "0.762894", "0.7592906", "0.7259346", "0.7071012", "0.69273037", "0.6480448", "0.63575506", "0.6051238", "0.5929099", "0.58672136", "0.58594066", "0.5799075", "0.5754101", "0.57187104", "0.57024187", "0.568598", "0.55680805", "0.5534512", "0.5533611", "0.55053973", "0.54354066", "0.54055494", "0.5384389", "0.53450376", "0.53016466", "0.52621853", "0.5237245", "0.52244943", "0.5221506", "0.51909286", "0.5184047", "0.51639456", "0.5159985", "0.5086832", "0.5080906", "0.50431794", "0.5030216", "0.5029553", "0.50145435", "0.5010719", "0.5003854", "0.49922538", "0.49487025", "0.49247256", "0.49137905", "0.49110925", "0.49077624", "0.48772717", "0.4876143", "0.487473", "0.48744276", "0.48715878", "0.4866025", "0.48578924", "0.48556304", "0.4848104", "0.4845857", "0.48411357", "0.4835676", "0.48343685", "0.4831005", "0.48281044", "0.47986832", "0.47868127", "0.47790202", "0.47740102", "0.4772389", "0.47691897", "0.4755657", "0.4745434", "0.47294265", "0.47209036", "0.47036994", "0.46709636", "0.46689543", "0.4656626", "0.46480885", "0.46256018", "0.46218973", "0.4619349", "0.46138996", "0.45923018", "0.45894796", "0.4584831", "0.45804262", "0.45789608", "0.4570347", "0.45649722", "0.45581225", "0.45552635", "0.45336625", "0.45295724", "0.45288903", "0.4527536", "0.45051503", "0.45039755", "0.45020452", "0.45012408", "0.45001313" ]
0.7056907
5
DeleteDaemonset deletes a daemonset from this cluster.
func (c *Cluster) DeleteDaemonset(ctx context.Context, ds *appsv1.DaemonSet) error { return c.client.AppsV1().DaemonSets(ds.GetNamespace()).Delete(ctx, ds.GetName(), v1.DeleteOptions{}) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteDaemonSet(client kubernetes.Interface, namespace string, daemonsetName string) error {\n\tlogrus.Infof(\"Deleting DaemonSet %s\", daemonsetName)\n\tdaemonsetError := client.ExtensionsV1beta1().DaemonSets(namespace).Delete(daemonsetName, &metav1.DeleteOptions{})\n\ttime.Sleep(10 * time.Second)\n\treturn daemonsetError\n}", "func DeleteDaemonSet(daemonSetName, namespace string) error {\n\tconst (\n\t\tTimeout = 5 * time.Minute\n\t)\n\n\tlogrus.Infof(\"Deleting daemonset %s\", daemonSetName)\n\tdeletePolicy := metav1.DeletePropagationForeground\n\n\tif err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Delete(context.TODO(), daemonSetName, metav1.DeleteOptions{\n\t\tPropagationPolicy: &deletePolicy,\n\t}); err != nil {\n\t\tlogrus.Infof(\"The daemonset (%s) deletion is unsuccessful due to %+v\", daemonSetName, err.Error())\n\t}\n\n\tfor start := time.Now(); time.Since(start) < Timeout; {\n\n\t\tpods, err := daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pods, err: %s\", err)\n\t\t}\n\n\t\tif len(pods.Items) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tlogrus.Infof(\"Successfully cleaned up daemonset %s\", daemonSetName)\n\treturn nil\n}", "func (c *ClientSetClient) DeleteDaemonSet(daemonset *appsv1.DaemonSet) error {\n\tctx := context.TODO()\n\treturn c.clientset.AppsV1().DaemonSets(daemonset.Namespace).Delete(ctx, daemonset.Name, metav1.DeleteOptions{})\n}", "func (k *k8sService) deleteDaemonSet(name string) error {\n\terr := k.client.ExtensionsV1beta1().DaemonSets(defaultNS).Delete(name, nil)\n\tif err == nil {\n\t\tlog.Infof(\"Deleted DaemonSet %v\", name)\n\t} else if errors.IsNotFound(err) {\n\t\tlog.Infof(\"DaemonSet %v not found\", name)\n\t\terr = nil\n\t} else {\n\t\tlog.Errorf(\"Failed to delete DaemonSet %v with error: %v\", name, err)\n\t}\n\treturn err\n}", "func (c *Client) DeleteDaemonSet(daemonset appsv1.DaemonSet) error {\n\tif err := c.clientset.AppsV1().DaemonSets(daemonset.Namespace).Delete(daemonset.Name, &metav1.DeleteOptions{}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to delete DaemonSet\")\n\t}\n\n\treturn nil\n}", "func (s *K8sSvc) DeleteReplicaSet(ctx context.Context, service string) error {\n\treturn s.cliset.AppsV1beta2().ReplicaSets(s.namespace).Delete(service, &metav1.DeleteOptions{})\n}", "func DeleteStatefulSet(k8sClient kubernetes.Interface, namespace string,\n\tsvc *appsv1.StatefulSet) error {\n\treturn k8sClient.AppsV1().\n\t\tStatefulSets(namespace).\n\t\tDelete(svc.Name, nil)\n}", "func (c *FakeExtendedDaemonSetReplicaSets) Delete(name string, options *v1.DeleteOptions) error {\n\t_, err := c.Fake.\n\t\tInvokes(testing.NewDeleteAction(extendeddaemonsetreplicasetsResource, c.ns, name), &v1alpha1.ExtendedDaemonSetReplicaSet{})\n\n\treturn err\n}", "func DeleteIPSet(setName string) {\n\tRemoveAllEntriesFromIPSet(setName)\n\tDecNumIPSets()\n}", "func ValidateDaemonSet(ds *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMeta(&ds.ObjectMeta, true, ValidateDaemonSetName, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDaemonSetSpec(&ds.Spec, nil, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}", "func (c *Client) DeleteDeploySet(deploySetId string) error {\n\treturn DeleteDeploySet(c, deploySetId)\n}", "func (c *Client) DaemonSetsCleaner(namespace string, dryRun bool, directories []string) error {\n\tvar left []string\n\n\tclusterDaemonsets, err := c.ListDaemonSets(namespace)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tfor _, value := range clusterDaemonsets.Items {\n\t\tleft = append(left, value.Name)\n\t}\n\n\tobjectsToDelete := Except(left, \"DaemonSet\", directories)\n\n\tfor _, item := range objectsToDelete {\n\t\tfor _, daemonset := range clusterDaemonsets.Items {\n\t\t\tif item == daemonset.Name {\n\t\t\t\tif dryRun {\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t\tcolor.Yellow(\" Deleting DaemonSet %s [dry-run]\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t} else {\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tcolor.Red(\" Deleting DaemonSet %s\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tif err := c.DeleteDaemonSet(daemonset); err != nil {\n\t\t\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func DeleteStatefulSet(client kubernetes.Interface, namespace string, statefulsetName string) error {\n\tlogrus.Infof(\"Deleting StatefulSet %s\", statefulsetName)\n\tstatefulsetError := client.AppsV1beta1().StatefulSets(namespace).Delete(statefulsetName, &metav1.DeleteOptions{})\n\ttime.Sleep(10 * time.Second)\n\treturn statefulsetError\n}", "func (r *reconciler) deleteNodeResolverDaemonSet(daemonset *appsv1.DaemonSet) error {\n\tif err := r.client.Delete(context.TODO(), daemonset); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"failed to delete node resolver daemonset %s/%s: %v\", daemonset.Namespace, daemonset.Name, err)\n\t}\n\tlogrus.Infof(\"deleted node resolver daemonset: %s/%s\", daemonset.Namespace, daemonset.Name)\n\treturn nil\n}", "func (operator *AccessOperator) DeleteConfigSet(cxt context.Context, option *DeleteConfigSetOption) error {\n\t//query business and app first\n\tbusiness, err := operator.GetBusiness(cxt, operator.Business)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif business == nil {\n\t\tlogger.V(3).Infof(\"DeleteConfigSet: found no relative Business %s\", operator.Business)\n\t\treturn fmt.Errorf(\"No relative Business %s\", operator.Business)\n\t}\n\n\t//todo(DeveloperJim): confirm delete operation\n\trequest := &accessserver.DeleteConfigSetReq{\n\t\tSeq: pkgcommon.Sequence(),\n\t\tBid: business.Bid,\n\t\tCfgsetid: option.CfgSetID,\n\t\tOperator: option.Operator,\n\t}\n\tgrpcOptions := []grpc.CallOption{\n\t\tgrpc.WaitForReady(true),\n\t}\n\tresponse, err := operator.Client.DeleteConfigSet(cxt, request, grpcOptions...)\n\tif err != nil {\n\t\tlogger.V(3).Infof(\"DeleteConfigSet %s failed, %s\", option.CfgSetID, err.Error())\n\t\treturn err\n\t}\n\tif response.ErrCode != common.ErrCode_E_OK {\n\t\tlogger.V(3).Infof(\"DeleteConfigSet %s successfully, but response Err, %s\", option.CfgSetID, response.ErrMsg)\n\t\treturn fmt.Errorf(\"%s\", response.ErrMsg)\n\t}\n\treturn nil\n}", "func (s *Set) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !s._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif s._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM sets WHERE id = $1`\n\n\t// run query\n\tXOLog(sqlstr, s.ID)\n\t_, err = db.Exec(sqlstr, s.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\ts._deleted = true\n\n\treturn nil\n}", "func (c *FakeExportedServiceSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\t_, err := c.Fake.\n\t\tInvokes(testing.NewDeleteAction(exportedservicesetsResource, c.ns, name), &federationv1.ExportedServiceSet{})\n\n\treturn err\n}", "func (c *Client) DeleteReusableDelegationSet(ctx context.Context, params *DeleteReusableDelegationSetInput, optFns ...func(*Options)) (*DeleteReusableDelegationSetOutput, error) {\n\tif params == nil {\n\t\tparams = &DeleteReusableDelegationSetInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"DeleteReusableDelegationSet\", params, optFns, addOperationDeleteReusableDelegationSetMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*DeleteReusableDelegationSetOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (client DnsClient) DeleteRRSet(ctx context.Context, request DeleteRRSetRequest) (response DeleteRRSetResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteRRSet, 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 = DeleteRRSetResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteRRSetResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteRRSetResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteRRSetResponse\")\n\t}\n\treturn\n}", "func (c *FakeExtendedDaemonSetReplicaSets) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {\n\taction := testing.NewDeleteCollectionAction(extendeddaemonsetreplicasetsResource, c.ns, listOptions)\n\n\t_, err := c.Fake.Invokes(action, &v1alpha1.ExtendedDaemonSetReplicaSetList{})\n\treturn err\n}", "func (r ReplicaSet) Delete() error {\n\treturn r.Client.Delete(r.ReplicaSet.Name, nil)\n}", "func (client DnsClient) deleteRRSet(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/zones/{zoneNameOrId}/records/{domain}/{rtype}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteRRSetResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (c *ClientSetClient) PatchDaemonSet(namespace, name, jsonPatch string) (*appsv1.DaemonSet, error) {\n\tctx := context.TODO()\n\treturn c.clientset.AppsV1().DaemonSets(namespace).Patch(ctx, name, types.StrategicMergePatchType, []byte(jsonPatch), metav1.PatchOptions{})\n}", "func (c client) DeleteStatefulSet(objectKey k8sClient.ObjectKey) error {\n\tsts := appsv1.StatefulSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: objectKey.Name,\n\t\t\tNamespace: objectKey.Namespace,\n\t\t},\n\t}\n\treturn c.Delete(context.TODO(), &sts)\n}", "func CreateOrUpdateDaemonSet(client clientset.Interface, ds *extensions.DaemonSet) error {\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Create(ds); err != nil {\n if !apierrors.IsAlreadyExists(err) {\n return fmt.Errorf(\"unable to create daemonset: %v\", err)\n }\n\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Update(ds); err != nil {\n return fmt.Errorf(\"unable to update daemonset: %v\", err)\n }\n }\n return nil\n}", "func (s *Set) Del(value string) error {\n\tif !s.host.rawUTF8 {\n\t\tEncode(&value)\n\t}\n\t// Remove a value from the table\n\t_, err := s.host.db.Exec(fmt.Sprintf(\"DELETE FROM %s WHERE %s = '%s'\", s.table, setCol, value))\n\treturn err\n}", "func CreateDaemonSet(client *rancher.Client, clusterName, daemonSetName, namespace string, template corev1.PodTemplateSpec) (*appv1.DaemonSet, error) {\n\tdynamicClient, err := client.GetDownStreamClusterClient(clusterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabels := map[string]string{}\n\tlabels[\"workload.user.cattle.io/workloadselector\"] = fmt.Sprintf(\"apps.daemonset-%v-%v\", namespace, daemonSetName)\n\n\ttemplate.ObjectMeta = metav1.ObjectMeta{\n\t\tLabels: labels,\n\t}\n\ttemplate.Spec.RestartPolicy = corev1.RestartPolicyAlways\n\tdaemonSet := &appv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: daemonSetName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: template,\n\t\t},\n\t}\n\n\tdaemonSetResource := dynamicClient.Resource(DaemonSetGroupVersionResource).Namespace(namespace)\n\n\tunstructuredResp, err := daemonSetResource.Create(context.TODO(), unstructured.MustToUnstructured(daemonSet), metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewDaemonSet := &appv1.DaemonSet{}\n\terr = scheme.Scheme.Convert(unstructuredResp, newDaemonSet, unstructuredResp.GroupVersionKind())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn daemonSet, nil\n}", "func (iMgr *IPSetManager) DeleteIPSet(name string, deleteOption util.DeleteOption) {\n\tiMgr.Lock()\n\tdefer iMgr.Unlock()\n\tset, exists := iMgr.setMap[name]\n\tif !exists {\n\t\treturn\n\t}\n\tiMgr.modifyCacheForCacheDeletion(set, deleteOption)\n}", "func ReconcileDaemonSet(c client.Client, hdfs hdfsv1.HDFS, expected v1.DaemonSet) (v1.DaemonSet, error) {\n\n\t//create kind instance\n\tvar reconciled v1.DaemonSet\n\terr := ReconcileResource(Params{\n\t\tClient: c,\n\t\tOwner: &hdfs,\n\t\tExpected: &expected,\n\t\tReconciled: &reconciled,\n\t})\n\n\treturn reconciled, err\n}", "func GetDaemonSet(namespace string, daemonsetName string) *v1beta1.DaemonSet {\n\treturn &v1beta1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: daemonsetName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\tconstants.ConfigmapUpdateOnChangeAnnotation: daemonsetName,\n\t\t\t\tconstants.SecretUpdateOnChangeAnnotation: daemonsetName},\n\t\t},\n\t\tSpec: v1beta1.DaemonSetSpec{\n\t\t\tUpdateStrategy: v1beta1.DaemonSetUpdateStrategy{\n\t\t\t\tType: v1beta1.RollingUpdateDaemonSetStrategyType,\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\"secondLabel\": \"temp\"},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tImage: \"tutum/hello-world\",\n\t\t\t\t\t\t\tName: daemonsetName,\n\t\t\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"BUCKET_NAME\",\n\t\t\t\t\t\t\t\t\tValue: \"test\",\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 (c *FakeClusterImageSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\t_, err := c.Fake.\n\t\tInvokes(testing.NewRootDeleteActionWithOptions(clusterimagesetsResource, name, opts), &hivev1.ClusterImageSet{})\n\treturn err\n}", "func CalicoDaemonSet(repo string) string {\n\treturn calicoCommon(repo, \"node\")\n\n}", "func (c *component) daemonset() *appsv1.DaemonSet {\n\tmaxUnavailable := intstr.FromInt(1)\n\n\tannots := map[string]string{}\n\n\tif c.config.envoyConfigMap != nil {\n\t\tannots[EnvoyConfigMapName] = rmeta.AnnotationHash(c.config.envoyConfigMap)\n\t}\n\n\tif c.config.ModSecurityConfigMap != nil {\n\t\tannots[ModSecurityRulesetHashAnnotation] = rmeta.AnnotationHash(c.config.ModSecurityConfigMap.Data)\n\t}\n\n\tpodTemplate := corev1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tAnnotations: annots,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tHostIPC: true,\n\t\t\tHostNetwork: true,\n\t\t\tServiceAccountName: APLName,\n\t\t\tDNSPolicy: corev1.DNSClusterFirstWithHostNet,\n\t\t\t// Absence of l7 daemonset pod on a node will break the annotated services connectivity, so we tolerate all.\n\t\t\tTolerations: rmeta.TolerateAll,\n\t\t\tImagePullSecrets: secret.GetReferenceList(c.config.PullSecrets),\n\t\t\tContainers: c.containers(),\n\t\t\tVolumes: c.volumes(),\n\t\t},\n\t}\n\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"DaemonSet\", APIVersion: \"apps/v1\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ApplicationLayerDaemonsetName,\n\t\t\tNamespace: common.CalicoNamespace,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: podTemplate,\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (r ExistingReplicaSet) Delete() error {\n\treturn r.Client.Delete(r.Name, nil)\n}", "func UpdateDaemonSet(client *kubernetes.Clientset, namespace string, resource interface{}) error {\n\tdaemonSet := resource.(appsv1.DaemonSet)\n\t_, err := client.AppsV1().DaemonSets(namespace).Update(context.TODO(), &daemonSet, metav1.UpdateOptions{})\n\treturn err\n}", "func (c *Cluster) CreateDaemonset(ctx context.Context, ds *appsv1.DaemonSet) (*appsv1.DaemonSet, error) {\n\tif ds.GetObjectMeta().GetNamespace() == \"\" {\n\t\tds.SetNamespace(NamespaceDefault)\n\t}\n\treturn c.client.AppsV1().DaemonSets(ds.GetNamespace()).Create(ctx, ds, v1.CreateOptions{})\n}", "func (c *quarksStatefulSets) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"quarksstatefulsets\").\n\t\tName(name).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func (c *FakeExportedServiceSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\taction := testing.NewDeleteCollectionAction(exportedservicesetsResource, c.ns, listOpts)\n\n\t_, err := c.Fake.Invokes(action, &federationv1.ExportedServiceSetList{})\n\treturn err\n}", "func createDaemonSet(client k8sclient.Interface, module *protos.Module) error {\n\tdsConfig := createDaemonSetObject(module)\n\td, err := client.ExtensionsV1beta1().DaemonSets(defaultNS).Create(dsConfig)\n\tif err == nil {\n\t\tlog.Infof(\"Created DaemonSet %+v\", d)\n\t} else if errors.IsAlreadyExists(err) {\n\t\tlog.Infof(\"DaemonSet %+v already exists\", dsConfig)\n\t} else {\n\t\tlog.Errorf(\"Failed to create DaemonSet %+v with error: %v\", dsConfig, err)\n\t}\n\n\treturn err\n}", "func (apiHandler *ApiHandler) handleDeleteReplicaSet(\n\trequest *restful.Request, response *restful.Response) {\n\n\tnamespace := request.PathParameter(\"namespace\")\n\treplicaSet := request.PathParameter(\"replicaSet\")\n\n\tif err := DeleteReplicaSetWithPods(apiHandler.client, namespace, replicaSet); err != nil {\n\t\thandleInternalError(response, err)\n\t\treturn\n\t}\n\n\tresponse.WriteHeader(http.StatusOK)\n}", "func ValidateDaemonSetUpdate(ds, oldDS *apps.DaemonSet, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := apivalidation.ValidateObjectMetaUpdate(&ds.ObjectMeta, &oldDS.ObjectMeta, field.NewPath(\"metadata\"))\n\tallErrs = append(allErrs, ValidateDaemonSetSpecUpdate(&ds.Spec, &oldDS.Spec, field.NewPath(\"spec\"))...)\n\tallErrs = append(allErrs, ValidateDaemonSetSpec(&ds.Spec, &oldDS.Spec, field.NewPath(\"spec\"), opts)...)\n\treturn allErrs\n}", "func (in *BcsDaemonset) DeepCopy() *BcsDaemonset {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsDaemonset)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func TestDeleteSet(t *testing.T) {\n\ttests.ResetLog()\n\tdefer tests.DisplayLog()\n\n\tqsName := prefix + \"_basic\"\n\tqsBadName := prefix + \"_basic_advice\"\n\n\tconst fixture = \"basic.json\"\n\tset1, err := qfix.Get(fixture)\n\tif err != nil {\n\t\tt.Fatalf(\"\\t%s\\tShould load query record from file : %v\", tests.Failed, err)\n\t}\n\tt.Logf(\"\\t%s\\tShould load query record from file.\", tests.Success)\n\n\tdb, err := db.NewMGO(tests.Context, tests.TestSession)\n\tif err != nil {\n\t\tt.Fatalf(\"\\t%s\\tShould be able to get a Mongo session : %v\", tests.Failed, err)\n\t}\n\tdefer db.CloseMGO(tests.Context)\n\n\tdefer func() {\n\t\tif err := qfix.Remove(db, prefix); err != nil {\n\t\t\tt.Fatalf(\"\\t%s\\tShould be able to remove the query set : %v\", tests.Failed, err)\n\t\t}\n\t\tt.Logf(\"\\t%s\\tShould be able to remove the query set.\", tests.Success)\n\t}()\n\n\tt.Log(\"Given the need to delete a query set in the database.\")\n\t{\n\t\tt.Log(\"\\tWhen using fixture\", fixture)\n\t\t{\n\t\t\tif err := query.Upsert(tests.Context, db, set1); err != nil {\n\t\t\t\tt.Fatalf(\"\\t%s\\tShould be able to create a query set : %s\", tests.Failed, err)\n\t\t\t}\n\t\t\tt.Logf(\"\\t%s\\tShould be able to create a query set.\", tests.Success)\n\n\t\t\tif err := query.Delete(tests.Context, db, qsName); err != nil {\n\t\t\t\tt.Fatalf(\"\\t%s\\tShould be able to delete a query set using its name[%s]: %s\", tests.Failed, qsName, err)\n\t\t\t}\n\t\t\tt.Logf(\"\\t%s\\tShould be able to delete a query set using its name[%s]:\", tests.Success, qsName)\n\n\t\t\tif err := query.Delete(tests.Context, db, qsBadName); err == nil {\n\t\t\t\tt.Fatalf(\"\\t%s\\tShould not be able to delete a query set using wrong name name[%s]\", tests.Failed, qsBadName)\n\t\t\t}\n\t\t\tt.Logf(\"\\t%s\\tShould not be able to delete a query set using wrong name name[%s]\", tests.Success, qsBadName)\n\n\t\t\tif _, err := query.GetByName(tests.Context, db, qsName); err == nil {\n\t\t\t\tt.Fatalf(\"\\t%s\\tShould be able to validate query set with Name[%s] does not exists: %s\", tests.Failed, qsName, errors.New(\"Record Exists\"))\n\t\t\t}\n\t\t\tt.Logf(\"\\t%s\\tShould be able to validate query set with Name[%s] does not exists:\", tests.Success, qsName)\n\t\t}\n\t}\n}", "func (c *ClientSetClient) GetDaemonSet(namespace, name string) (*appsv1.DaemonSet, error) {\n\tctx := context.TODO()\n\treturn c.clientset.AppsV1().DaemonSets(namespace).Get(ctx, name, metav1.GetOptions{})\n}", "func MockDaemonSet() appsv1.DaemonSet {\n\tp := MockPod()\n\treturn appsv1.DaemonSet{\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n}", "func (in *DaemonsetRef) DeepCopy() *DaemonsetRef {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DaemonsetRef)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (r *ReconcileStatefulSetCleanup) deleteVolumeManagementStatefulSet(ctx context.Context, extendedstatefulset *essv1a1.ExtendedStatefulSet) error {\n\n\tstatefulSets, err := listStatefulSetsFromInformer(ctx, r.client, extendedstatefulset)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor index := range statefulSets {\n\t\tif isVolumeManagementStatefulSet(statefulSets[index].Name) {\n\t\t\tok, err := r.isVolumeManagementStatefulSetInitialized(ctx, &statefulSets[index])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\tctxlog.Info(ctx, \"Deleting volumeManagement statefulSet \", statefulSets[index].Name, \" owned by ExtendedStatefulSet \", extendedstatefulset.Name, \" in namespace \", extendedstatefulset.Namespace, \".\")\n\t\t\t\terr = r.client.Delete(ctx, &statefulSets[index], client.PropagationPolicy(metav1.DeletePropagationBackground))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o *MultiAddressesSet) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no MultiAddressesSet provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), multiAddressesSetPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"multi_addresses_sets\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from multi_addresses_sets\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for multi_addresses_sets\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func DaemonSetName(name string) string {\n\treturn DNSLengthName(DaemonSetPrefix, \"%s-%s\", DaemonSetPrefix, name)\n}", "func (c *FakeDaskClusters) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\taction := testing.NewDeleteCollectionAction(daskclustersResource, c.ns, listOpts)\n\n\t_, err := c.Fake.Invokes(action, &kubernetesdaskorgv1.DaskClusterList{})\n\treturn err\n}", "func (b *Bot) DeleteChatStickerSet(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"deleteChatStickerSet\", request); err == nil {\n\t\tv := axon.V{Value: response}\n\t\tresult, err = v.AsBool()\n\t}\n\treturn\n}", "func (b *Bot) DeleteChatStickerSet(chatID int) (ok bool, err error) {\n\tparams := map[string]interface{}{\n\t\t\"chat_id\": chatID,\n\t}\n\tresult, err := b.call(\"deleteChatStickerSet\", params)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn result.(bool), nil\n}", "func ExampleAvailabilitySetsClient_Delete_availabilitySetDeleteMaximumSetGen() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armcompute.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\t_, err = clientFactory.NewAvailabilitySetsClient().Delete(ctx, \"rgcompute\", \"aaaaaaaaaaaaaaaaaaaa\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n}", "func ExampleAvailabilitySetsClient_Delete_availabilitySetDeleteMinimumSetGen() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armcompute.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\t_, err = clientFactory.NewAvailabilitySetsClient().Delete(ctx, \"rgcompute\", \"aaaaaaaaaaa\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n}", "func CreateDaemonSet(daemonSetName, namespace, containerName, imageWithVersion string, timeout time.Duration) (*v1core.PodList, error) {\n\n\trebootDaemonSet := createDaemonSetsTemplate(daemonSetName, namespace, containerName, imageWithVersion)\n\n\tif doesDaemonSetExist(daemonSetName, namespace) {\n\t\terr := DeleteDaemonSet(daemonSetName, namespace)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to delete %s daemonset because: %s\", daemonSetName, err)\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Creating daemonset %s\", daemonSetName)\n\t_, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Create(context.TODO(), rebootDaemonSet, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = WaitDaemonsetReady(namespace, daemonSetName, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Deamonset is ready\")\n\n\tvar ptpPods *v1core.PodList\n\tptpPods, err = daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\tif err != nil {\n\t\treturn ptpPods, err\n\t}\n\tlogrus.Infof(\"Successfully created daemonset %s\", daemonSetName)\n\treturn ptpPods, nil\n}", "func SetDaemonsetOwnerRef(pod *v1.Pod) {\n\tpod.ObjectMeta.OwnerReferences = GetDaemonSetOwnerRefList()\n}", "func (c *quarksStatefulSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\tvar timeout time.Duration\n\tif listOpts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second\n\t}\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"quarksstatefulsets\").\n\t\tVersionedParams(&listOpts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tBody(&opts).\n\t\tDo(ctx).\n\t\tError()\n}", "func (az *AzureClient) DeleteVirtualMachineScaleSet(ctx context.Context, resourceGroup, vmssName string) error {\n\tfuture, err := az.virtualMachineScaleSetsClient.Delete(ctx, resourceGroup, vmssName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = future.WaitForCompletionRef(ctx, az.virtualMachineScaleSetsClient.Client); err != nil {\n\t\treturn err\n\t}\n\t_, err = future.Result(az.virtualMachineScaleSetsClient)\n\treturn err\n}", "func (ss *StrategySet) Delete(ctx context.Context, header http.Header, req *pbcs.DeleteStrategySetReq) (\n\t*pbcs.DeleteStrategySetResp, error) {\n\n\tresp := ss.client.Delete().\n\t\tWithContext(ctx).\n\t\tSubResourcef(\"/config/delete/strategy_set/strategy_set/strategy_set_id/%d/app_id/%d/biz_id/%d\",\n\t\t\treq.Id, req.AppId, req.BizId).\n\t\tWithHeaders(header).\n\t\tBody(req).\n\t\tDo()\n\n\tif resp.Err != nil {\n\t\treturn nil, resp.Err\n\t}\n\n\tpbResp := &struct {\n\t\tData *pbcs.DeleteStrategySetResp `json:\"data\"`\n\t\tError *rest.ErrorPayload `json:\"error\"`\n\t}{}\n\tif err := resp.Into(pbResp); err != nil {\n\t\treturn nil, err\n\t}\n\tif !reflect.ValueOf(pbResp.Error).IsNil() {\n\t\treturn nil, pbResp.Error\n\t}\n\n\treturn pbResp.Data, nil\n}", "func (client FeatureStateClient) DeleteStateset(ctx context.Context, statesetID string) (result autorest.Response, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/FeatureStateClient.DeleteStateset\")\n defer func() {\n sc := -1\n if result.Response != nil {\n sc = result.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.DeleteStatesetPreparer(ctx, statesetID)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"DeleteStateset\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.DeleteStatesetSender(req)\n if err != nil {\n result.Response = resp\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"DeleteStateset\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.DeleteStatesetResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.FeatureStateClient\", \"DeleteStateset\", resp, \"Failure responding to request\")\n return\n }\n\n return\n}", "func (c *Client) DeleteCluster(projectID string, seed string, clusterID string) error {\n\treq, err := c.newRequest(\"DELETE\", projectPath+\"/\"+projectID+datacenterSubPath+\"/\"+seed+clustersSubPath+\"/\"+clusterID, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := c.do(req, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// StatusCodes 401 and 403 mean empty response and should be treated as such\n\tif resp.StatusCode == 401 || resp.StatusCode == 403 {\n\t\treturn nil\n\t}\n\n\tif resp.StatusCode >= 299 {\n\t\treturn errors.New(\"Got non-2xx return code: \" + strconv.Itoa(resp.StatusCode))\n\t}\n\n\treturn nil\n}", "func (s *Set) CleanUp() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor h := range s.hosts {\n\t\tif err := s.del(h); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(s.hosts, h)\n\t}\n\treturn nil\n}", "func (r *DaemonReconciler) cleanupOldDaemonsets(ctx context.Context, namespace string) error {\n\tif r.deletedStaticProvisioner {\n\t\treturn nil\n\t}\n\n\t// search for old localvolume daemons\n\tdsList := &appsv1.DaemonSetList{}\n\terr := r.Client.List(ctx, dsList, client.InNamespace(namespace))\n\tif err != nil {\n\t\tklog.ErrorS(err, \"could not list daemonsets\")\n\t\treturn err\n\t}\n\tappNameList := make([]string, 0)\n\tfor _, ds := range dsList.Items {\n\t\tappLabel, found := ds.ObjectMeta.Labels[appLabelKey]\n\t\tif !found {\n\t\t\tcontinue\n\t\t} else if strings.HasPrefix(appLabel, oldLVDiskMakerPrefix) || strings.HasPrefix(appLabel, oldLVProvisionerPrefix) {\n\t\t\t// remember name to watch for pods to delete\n\t\t\tappNameList = append(appNameList, appLabel)\n\t\t\t// delete daemonset\n\t\t\terr = r.Client.Delete(ctx, &ds)\n\t\t\tif err != nil && !(errors.IsNotFound(err) || errors.IsGone(err)) {\n\t\t\t\tklog.ErrorS(err, \"could not delete daemonset\", \"dsName\", ds.Name)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// search for old localvolumeset daemons\n\tprovisioner := &appsv1.DaemonSet{}\n\terr = r.Client.Get(ctx, types.NamespacedName{Name: oldProvisionerName, Namespace: namespace}, provisioner)\n\tif err == nil { // provisioner daemonset found\n\t\tklog.InfoS(\"old daemonset found, cleaning up\", \"oldProvisionerName\", oldProvisionerName)\n\t\terr = r.Client.Delete(ctx, provisioner)\n\t\tif err != nil && !(errors.IsNotFound(err) || errors.IsGone(err)) {\n\t\t\tklog.ErrorS(err, \"could not delete daemonset\", \"oldProvisionerName\", oldProvisionerName)\n\t\t\treturn err\n\t\t}\n\t} else if !(errors.IsNotFound(err) || errors.IsGone(err)) { // unknown error\n\t\tklog.ErrorS(err, \"could not fetch daemonset to clean it up\", \"oldProvisionerName\", oldProvisionerName)\n\t\treturn err\n\t}\n\n\t// wait for pods to die\n\terr = wait.ExponentialBackoff(wait.Backoff{\n\t\tCap: time.Minute * 2,\n\t\tDuration: time.Second,\n\t\tFactor: 1.7,\n\t\tJitter: 1,\n\t\tSteps: 20,\n\t}, func() (done bool, err error) {\n\t\tpodList := &corev1.PodList{}\n\t\tallGone := false\n\t\t// search for any pods with label 'app' in appNameList\n\t\tappNameList = append(appNameList, oldProvisionerName)\n\t\trequirement, err := labels.NewRequirement(appLabelKey, selection.In, appNameList)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"failed to compose labelselector requirement\",\n\t\t\t\t\"appLabelKey\", appLabelKey, \"appNameList\", appNameList)\n\t\t\treturn false, err\n\t\t}\n\t\tselector := labels.NewSelector().Add(*requirement)\n\t\terr = r.Client.List(context.TODO(), podList, client.MatchingLabelsSelector{Selector: selector})\n\t\tif err != nil && !errors.IsNotFound(err) {\n\t\t\treturn false, err\n\t\t} else if len(podList.Items) == 0 {\n\t\t\tallGone = true\n\t\t}\n\t\tklog.Infof(\"waiting for 0 pods with app label %q, found = %v\",\n\t\t\toldProvisionerName, len(podList.Items))\n\t\treturn allGone, nil\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"could not determine that old provisioner pods were deleted\")\n\t\treturn err\n\t}\n\tr.deletedStaticProvisioner = true\n\treturn nil\n}", "func (s StringSet) Del(x string) { delete(s, x) }", "func ExampleRDS_DeleteDBCluster_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DeleteDBClusterInput{\n\t\tDBClusterIdentifier: aws.String(\"mycluster\"),\n\t\tFinalDBSnapshotIdentifier: aws.String(\"mycluster-final-snapshot\"),\n\t\tSkipFinalSnapshot: aws.Bool(false),\n\t}\n\n\tresult, err := svc.DeleteDBCluster(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase rds.ErrCodeDBClusterNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBClusterStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBClusterStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBClusterSnapshotAlreadyExistsFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterSnapshotAlreadyExistsFault, aerr.Error())\n\t\t\tcase rds.ErrCodeSnapshotQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeSnapshotQuotaExceededFault, aerr.Error())\n\t\t\tcase rds.ErrCodeInvalidDBClusterSnapshotStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBClusterSnapshotStateFault, aerr.Error())\n\t\t\tcase rds.ErrCodeDBClusterAutomatedBackupQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterAutomatedBackupQuotaExceededFault, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (r *DatasetsService) Undelete(datasetId string, undeletedatasetrequest *UndeleteDatasetRequest) *DatasetsUndeleteCall {\n\tc := &DatasetsUndeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.datasetId = datasetId\n\tc.undeletedatasetrequest = undeletedatasetrequest\n\treturn c\n}", "func GetDaemonSetContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.DaemonSet).Spec.Template.Spec.Containers\n}", "func (client *Client) DeleteStickerFromSet(sticker string) *VoidResponse {\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointDeleteStickerFromSet, client.accessToken)\n\trequest := gorequest.New().Get(endpoint).Set(UserAgentHeader, UserAgent+\"/\"+Version).Type(gorequest.TypeJSON).\n\t\tQuery(fmt.Sprintf(\"sticker=%v\", sticker))\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}", "func NewMockDaemonSetFinalizer(ctrl *gomock.Controller) *MockDaemonSetFinalizer {\n\tmock := &MockDaemonSetFinalizer{ctrl: ctrl}\n\tmock.recorder = &MockDaemonSetFinalizerMockRecorder{mock}\n\treturn mock\n}", "func (u *Msg) RRsetDelete(rr []RR) {\n\tu.Ns = make([]RR, len(rr))\n\tfor i, r := range rr {\n\t\tu.Ns[i] = r\n\t\tu.Ns[i].Header().Class = ClassANY\n\t\tu.Ns[i].Header().Rdlength = 0\n\t\tu.Ns[i].Header().Ttl = 0\n\t}\n}", "func (f *TestFramework) DestroyMachineSet() error {\n\tlog.Print(\"Destroying MachineSets\")\n\tif f.machineSet == nil {\n\t\tlog.Print(\"unable to find MachineSet to be deleted, was skip VM setup option selected ?\")\n\t\tlog.Print(\"MachineSets/Machines needs to be deleted manually \\nNot deleting MachineSets...\")\n\t\treturn nil\n\t}\n\terr := f.machineClient.MachineSets(\"openshift-machine-api\").Delete(context.TODO(), f.machineSet.Name, metav1.DeleteOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete MachineSet %v\", err)\n\t}\n\tlog.Print(\"MachineSets Destroyed\")\n\treturn nil\n}", "func (r *ReconcileHostPathProvisioner) reconcileDaemonSet(reqLogger logr.Logger, instance *hostpathprovisionerv1alpha1.HostPathProvisioner, namespace string) (reconcile.Result, error) {\n\t// Define a new DaemonSet object\n\tprovisionerImage := os.Getenv(provisionerImageEnvVarName)\n\tif provisionerImage == \"\" {\n\t\treqLogger.Info(\"PROVISIONER_IMAGE not set, defaulting to hostpath-provisioner\")\n\t\tprovisionerImage = ProvisionerImageDefault\n\t}\n\n\tdesired := createDaemonSetObject(instance, provisionerImage, namespace)\n\tdesiredMetaObj := &desired.ObjectMeta\n\tsetLastAppliedConfiguration(desiredMetaObj)\n\n\t// Set HostPathProvisioner instance as the owner and controller\n\tif err := controllerutil.SetControllerReference(instance, desired, r.scheme); err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Check if this DaemonSet already exists\n\tfound := &appsv1.DaemonSet{}\n\terr := r.client.Get(context.TODO(), types.NamespacedName{Name: desired.Name, Namespace: desired.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\treqLogger.Info(\"Creating a new DaemonSet\", \"DaemonSet.Namespace\", desired.Namespace, \"Daemonset.Name\", desired.Name)\n\t\terr = r.client.Create(context.TODO(), desired)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\n\t\t// DaemonSet created successfully - don't requeue\n\t\treturn reconcile.Result{}, nil\n\t} else if err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Keep a copy of the original for comparison later.\n\tcurrentRuntimeObjCopy := found.DeepCopyObject()\n\t// Copy found status fields, so the compare won't fail on desired/scheduled/ready pods being different. Updating will ignore them anyway.\n\tdesired = copyStatusFields(desired, found)\n\n\t// allow users to add new annotations (but not change ours)\n\tmergeLabelsAndAnnotations(desiredMetaObj, &found.ObjectMeta)\n\n\t// create merged DaemonSet from found and desired.\n\tmerged, err := mergeObject(desired, found)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tif !reflect.DeepEqual(currentRuntimeObjCopy, merged) {\n\t\tlogJSONDiff(reqLogger, currentRuntimeObjCopy, merged)\n\t\t// Current is different from desired, update.\n\t\treqLogger.Info(\"Updating DaemonSet\", \"DaemonSet.Name\", desired.Name)\n\t\terr = r.client.Update(context.TODO(), merged)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\t// DaemonSet already exists and matches the desired state - don't requeue\n\treqLogger.Info(\"Skip reconcile: DaemonSet already exists\", \"DaemonSet.Namespace\", found.Namespace, \"Daemonset.Name\", found.Name)\n\treturn reconcile.Result{}, nil\n}", "func NewMockDaemonSetDeletionReconciler(ctrl *gomock.Controller) *MockDaemonSetDeletionReconciler {\n\tmock := &MockDaemonSetDeletionReconciler{ctrl: ctrl}\n\tmock.recorder = &MockDaemonSetDeletionReconcilerMockRecorder{mock}\n\treturn mock\n}", "func (m *Machine) DeleteExtendedStatefulSet(namespace string, name string) error {\n\tclient := m.VersionedClientset.ExtendedstatefulsetV1alpha1().ExtendedStatefulSets(namespace)\n\treturn client.Delete(name, &metav1.DeleteOptions{})\n}", "func (w *worker) deleteHost(host *chop.ChiHost) error {\n\tw.a.V(2).M(host).S().Info(host.Address.HostName)\n\tdefer w.a.V(2).M(host).E().Info(host.Address.HostName)\n\n\tw.a.V(1).\n\t\tWithEvent(host.CHI, eventActionDelete, eventReasonDeleteStarted).\n\t\tWithStatusAction(host.CHI).\n\t\tM(host).F().\n\t\tInfo(\"Delete host %s/%s - started\", host.Address.ClusterName, host.Name)\n\n\tif _, err := w.c.getStatefulSet(host); err != nil {\n\t\tw.a.WithEvent(host.CHI, eventActionDelete, eventReasonDeleteCompleted).\n\t\t\tWithStatusAction(host.CHI).\n\t\t\tM(host).F().\n\t\t\tInfo(\"Delete host %s/%s - completed StatefulSet not found - already deleted? err: %v\",\n\t\t\t\thost.Address.ClusterName, host.Name, err)\n\t\treturn nil\n\t}\n\n\t// Each host consists of\n\t// 1. User-level objects - tables on the host\n\t// We need to delete tables on the host in order to clean Zookeeper data.\n\t// If just delete tables, Zookeeper will still keep track of non-existent tables\n\t// 2. Kubernetes-level objects - such as StatefulSet, PVC(s), ConfigMap(s), Service(s)\n\t// Need to delete all these items\n\n\tvar err error\n\terr = w.deleteTables(host)\n\terr = w.c.deleteHost(host)\n\n\t// When deleting the whole CHI (not particular host), CHI may already be unavailable, so update CHI tolerantly\n\thost.CHI.Status.DeletedHostsCount++\n\t_ = w.c.updateCHIObjectStatus(host.CHI, true)\n\n\tif err == nil {\n\t\tw.a.V(1).\n\t\t\tWithEvent(host.CHI, eventActionDelete, eventReasonDeleteCompleted).\n\t\t\tWithStatusAction(host.CHI).\n\t\t\tM(host).F().\n\t\t\tInfo(\"Delete host %s/%s - completed\", host.Address.ClusterName, host.Name)\n\t} else {\n\t\tw.a.WithEvent(host.CHI, eventActionDelete, eventReasonDeleteFailed).\n\t\t\tWithStatusError(host.CHI).\n\t\t\tM(host).F().\n\t\t\tError(\"FAILED Delete host %s/%s - completed\", host.Address.ClusterName, host.Name)\n\t}\n\n\treturn err\n}", "func DeleteRuleset(rulesetMap map[string]string) (err error) {\n uuid := rulesetMap[\"uuid\"]\n name := rulesetMap[\"name\"]\n rulesetFolderName := strings.Replace(name, \" \", \"_\", -1)\n\n localRulesetFiles, err := utils.GetKeyValueString(\"ruleset\", \"localRulesets\")\n if err != nil {\n logs.Error(\"DeleteRuleset Error getting data from main.conf for load data: \" + err.Error())\n return err\n }\n\n //delete LOG for scheduler\n err = ndb.DeleteSchedulerLog(uuid)\n if err != nil {\n logs.Error(\"Error deleting LOG DeleteSchedulerLog: \" + err.Error())\n return err\n }\n\n //delete scheduler\n schedulerUUID, err := ndb.GetSchedulerByValue(uuid)\n if err != nil {\n logs.Error(\"Error getting scheduler uuid GetSchedulerByValue: \" + err.Error())\n return err\n }\n\n err = ndb.DeleteScheduler(schedulerUUID)\n if err != nil {\n logs.Error(\"Error deleting scheduler uuid DeleteSchedulerLog: \" + err.Error())\n return err\n }\n\n //delete ruleset\n err = ndb.DeleteRulesetByUniqueid(uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetByUniqueid -> ERROR deleting ruleset: \" + err.Error())\n return err\n }\n\n //delete a node ruleset\n err = ndb.DeleteRulesetNodeByUniqueid(uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting ruleset: \" + err.Error())\n return err\n }\n\n //select all groups\n groups, err := ndb.GetAllGroups()\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR getting all groups: \" + err.Error())\n return err\n }\n groupsRulesets, err := ndb.GetAllGroupRulesets()\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR getting all grouprulesets: \" + err.Error())\n return err\n }\n for id := range groups {\n for grid := range groupsRulesets {\n if groupsRulesets[grid][\"groupid\"] == id && groupsRulesets[grid][\"rulesetid\"] == uuid {\n //delete a node ruleset\n err = ndb.DeleteGroupRulesetByValue(\"groupid\", id)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting grouprulesets: \" + err.Error())\n return err\n }\n err = ndb.DeleteGroupRulesetByValue(\"rulesetid\", uuid)\n if err != nil {\n logs.Error(\"DeleteRulesetNodeByUniqueid -> ERROR deleting grouprulesets: \" + err.Error())\n return err\n }\n }\n }\n\n }\n\n //delete ruleset from path\n err = os.RemoveAll(localRulesetFiles + rulesetFolderName)\n if err != nil {\n logs.Error(\"DB DeleteRuleset/rm -> ERROR deleting ruleset from their path...\")\n return errors.New(\"DB DeleteRuleset/rm -> ERROR deleting ruleset from their path...\")\n }\n\n //delete all ruleset source rules for specific uuid\n rules, err := ndb.GetRulesFromRuleset(uuid)\n if err != nil {\n logs.Error(\"GetRulesFromRuleset -> ERROR getting all rule_files for delete local ruleset: \" + err.Error())\n return err\n }\n for sourceUUID := range rules {\n err = ndb.DeleteRuleFilesByUuid(sourceUUID)\n if err != nil {\n logs.Error(\"DeleteRuleFilesByUuid -> ERROR deleting all local ruleset rule files associated: \" + err.Error())\n return err\n }\n }\n\n //update to nil group ruleset\n rulesetsForGroups, err := ndb.GetAllGroupsBValue(uuid)\n if err != nil {\n logs.Error(\"GetAllGroupsBValue -> ERROR getting all groups by ruleset uuid: \" + err.Error())\n return err\n }\n for y := range rulesetsForGroups {\n err = ndb.UpdateGroupValue(y, \"ruleset\", \"\")\n if err != nil {\n logs.Error(\"Error updating to null rulesets into group table: \" + err.Error())\n return err\n }\n err = ndb.UpdateGroupValue(y, \"rulesetID\", \"\")\n if err != nil {\n logs.Error(\"Error updating to null rulesetsID into group table: \" + err.Error())\n return err\n }\n }\n\n return nil\n}", "func (c *FakeDaemonstools) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\taction := testing.NewDeleteCollectionAction(daemonstoolsResource, c.ns, listOpts)\n\n\t_, err := c.Fake.Invokes(action, &v1beta1.DaemonstoolList{})\n\treturn err\n}", "func (dc Datacenter) Delete(client MetalCloudClient) error {\n\treturn nil\n}", "func DeleteCluster(t *testing.T, f *framework.Framework, ctx *framework.TestCtx, z *api.ZookeeperCluster) error {\n\tt.Logf(\"deleting zookeeper cluster: %s\", z.Name)\n\terr := f.Client.Delete(goctx.TODO(), z)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete CR: %v\", err)\n\t}\n\n\tt.Logf(\"deleted zookeeper cluster: %s\", z.Name)\n\treturn nil\n}", "func (client *Client) DeleteChatStickerSet(chatId interface{}) *VoidResponse {\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointDeleteChatStickerSet, client.accessToken)\n\trequest := gorequest.New().Type(gorequest.TypeJSON).Get(endpoint).Set(UserAgentHeader, UserAgent+\"/\"+Version).\n\t\tQuery(fmt.Sprintf(\"chat_id=%v\", chatId))\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}", "func (set StringSet) Del(str string) {\n\tdelete(set, str)\n}", "func DeleteZSetValue(serverName string, dbNum uint8, key, value string) error {\n\tconn, err := connector.GetByName(serverName, dbNum)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = conn.Do(\"ZREM\", key, value)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Set) Delete(val int) {\n\tdelete(s.set, val)\n}", "func isDaemonSetMarkedForTermination(ds *appsv1.DaemonSet) bool {\n\treturn ds.DeletionTimestamp != nil\n}", "func (c *FakeDaemonstools) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {\n\t_, err := c.Fake.\n\t\tInvokes(testing.NewDeleteAction(daemonstoolsResource, c.ns, name), &v1beta1.Daemonstool{})\n\n\treturn err\n}", "func DeleteCluster(c *cli.Context) error {\n\n\tclusters, err := getClusters(c.Bool(\"all\"), c.String(\"name\"))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(clusters) == 0 {\n\t\tif !c.IsSet(\"all\") && !c.IsSet(\"name\") {\n\t\t\treturn fmt.Errorf(\"No cluster with name '%s' found (You can add `--all` and `--name <CLUSTER-NAME>` to delete other clusters)\", c.String(\"name\"))\n\t\t}\n\t\treturn fmt.Errorf(\"No cluster(s) found\")\n\t}\n\n\t// remove clusters one by one instead of appending all names to the docker command\n\t// this allows for more granular error handling and logging\n\tfor _, cluster := range clusters {\n\t\tlog.Printf(\"Removing cluster [%s]\", cluster.name)\n\t\tif len(cluster.workers) > 0 {\n\t\t\t// TODO: this could be done in goroutines\n\t\t\tlog.Printf(\"...Removing %d workers\\n\", len(cluster.workers))\n\t\t\tfor _, worker := range cluster.workers {\n\t\t\t\tif err := removeContainer(worker.ID); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdeleteClusterDir(cluster.name)\n\t\tlog.Println(\"...Removing server\")\n\t\tif err := removeContainer(cluster.server.ID); err != nil {\n\t\t\treturn fmt.Errorf(\" Couldn't remove server for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tif err := disconnectRegistryFromNetwork(cluster.name, c.IsSet(\"keep-registry-volume\")); err != nil {\n\t\t\tlog.Warningf(\"Couldn't disconnect Registry from network %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tif c.IsSet(\"prune\") {\n\t\t\t// disconnect any other container that is connected to the k3d network\n\t\t\tnid, err := getClusterNetwork(cluster.name)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"Couldn't get the network for cluster %q\\n%+v\", cluster.name, err)\n\t\t\t}\n\t\t\tcids, err := getContainersInNetwork(nid)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"Couldn't get the list of containers connected to network %q\\n%+v\", nid, err)\n\t\t\t}\n\t\t\tfor _, cid := range cids {\n\t\t\t\terr := disconnectContainerFromNetwork(cid, nid)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"Couldn't disconnect container %q from network %q\", cid, nid)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"...%q has been forced to disconnect from %q's network\", cid, cluster.name)\n\t\t\t}\n\t\t}\n\n\t\tif err := deleteClusterNetwork(cluster.name); err != nil {\n\t\t\tlog.Warningf(\"Couldn't delete cluster network for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tlog.Println(\"...Removing docker image volume\")\n\t\tif err := deleteImageVolume(cluster.name); err != nil {\n\t\t\tlog.Warningf(\"Couldn't delete image docker volume for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tlog.Infof(\"Removed cluster [%s]\", cluster.name)\n\t}\n\n\treturn nil\n}", "func NewDaemonSetControl(config DSConfig) (*DSControl, error) {\n\terr := config.checkAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &DSControl{\n\t\tDSConfig: config,\n\t\tFieldLogger: log.WithFields(log.Fields{\n\t\t\t\"daemonset\": formatMeta(config.ObjectMeta),\n\t\t}),\n\t}, nil\n}", "func (s Set) Delete(st string) {\n\tif _, ok := s[st]; ok {\n\t\tdelete(s, st)\n\t}\n}", "func (client ReferenceDataSetsClient) Delete(ctx context.Context, resourceGroupName string, environmentName string, referenceDataSetName string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ReferenceDataSetsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DeletePreparer(ctx, resourceGroupName, environmentName, referenceDataSetName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"timeseriesinsights.ReferenceDataSetsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"timeseriesinsights.ReferenceDataSetsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"timeseriesinsights.ReferenceDataSetsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *Vrouter) PrepareDaemonSet(ds *appsv1.DaemonSet,\n\tcommonConfiguration *PodConfiguration,\n\trequest reconcile.Request,\n\tscheme *runtime.Scheme,\n\tclient client.Client) error {\n\tinstanceType := \"vrouter\"\n\tSetDSCommonConfiguration(ds, commonConfiguration)\n\tds.SetName(request.Name + \"-\" + instanceType + \"-daemonset\")\n\tds.SetNamespace(request.Namespace)\n\tds.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Selector.MatchLabels = map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name}\n\tds.Spec.Template.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Template.Spec.Affinity = &corev1.Affinity{\n\t\tPodAntiAffinity: &corev1.PodAntiAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{{\n\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchExpressions: []metav1.LabelSelectorRequirement{{\n\t\t\t\t\t\tKey: instanceType,\n\t\t\t\t\t\tOperator: \"Exists\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tTopologyKey: \"kubernetes.io/hostname\",\n\t\t\t}},\n\t\t},\n\t}\n\terr := controllerutil.SetControllerReference(c, ds, scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *FakeClusterImageSets) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {\n\taction := testing.NewRootDeleteCollectionAction(clusterimagesetsResource, listOpts)\n\n\t_, err := c.Fake.Invokes(action, &hivev1.ClusterImageSetList{})\n\treturn err\n}", "func (client *LANHostConfigManagement1) DeleteDNSServer(NewDNSServers string) (err error) {\n\treturn client.DeleteDNSServerCtx(context.Background(),\n\t\tNewDNSServers,\n\t)\n}", "func (c *client) DeleteCluster() error {\n\t_, err := c.runCmd(\"cluster\", \"delete\", c.clusterName)\n\treturn err\n}", "func getDSClient() v1.DaemonSetInterface {\n\tlog.Debug(\"Creating Daemonset client.\")\n\treturn client.AppsV1().DaemonSets(checkNamespace)\n}", "func (c *awsSesReceiptRuleSets) Delete(name string, options *meta_v1.DeleteOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"awssesreceiptrulesets\").\n\t\tName(name).\n\t\tBody(options).\n\t\tDo().\n\t\tError()\n}", "func (s *K8sSvc) DeleteService(ctx context.Context, cluster string, service string) error {\n\trequuid := utils.GetReqIDFromContext(ctx)\n\n\tdelOpt := &metav1.DeleteOptions{}\n\n\t// delete statefulset\n\terr := s.cliset.AppsV1beta2().StatefulSets(s.namespace).Delete(service, delOpt)\n\tif err != nil {\n\t\tif !k8errors.IsNotFound(err) {\n\t\t\tglog.Errorln(\"delete statefulset error\", err, \"service\", service, \"requuid\", requuid)\n\t\t\treturn err\n\t\t}\n\t\tglog.Infoln(\"statefulset not found, service\", service, \"requuid\", requuid)\n\t} else {\n\t\tglog.Infoln(\"deleted statefulset, service\", service, \"requuid\", requuid)\n\t}\n\n\t// delete the headless service\n\terr = s.cliset.CoreV1().Services(s.namespace).Delete(service, delOpt)\n\tif err != nil {\n\t\tif !k8errors.IsNotFound(err) {\n\t\t\tglog.Errorln(\"delete headless service error\", err, \"service\", service, \"requuid\", requuid)\n\t\t\treturn err\n\t\t}\n\t\tglog.Infoln(\"headless service not found, service\", service, \"requuid\", requuid)\n\t} else {\n\t\tglog.Infoln(\"deleted headless service, service\", service, \"requuid\", requuid)\n\t}\n\n\t// delete the storage class\n\terr = s.deleteStorageClass(ctx, service, requuid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.Infoln(\"deleted service\", service, \"requuid\", requuid)\n\treturn nil\n}", "func (s *Server) DeleteCluster(id uint64) {\n\ts.doDeleteCluster(id)\n}", "func (dm *DMap) deleteOnCluster(hkey uint64, key string, f *fragment) error {\n\towners := dm.s.primary.PartitionOwnersByHKey(hkey)\n\tif len(owners) == 0 {\n\t\tpanic(\"partition owners list cannot be empty\")\n\t}\n\n\terr := dm.deleteFromPreviousOwners(key, owners)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dm.s.config.ReplicaCount != 0 {\n\t\terr := dm.deleteBackupOnCluster(hkey, key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = f.storage.Delete(hkey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// DeleteHits is the number of deletion reqs resulting in an item being removed.\n\tDeleteHits.Increase(1)\n\n\treturn nil\n}", "func RemoveDaemonSetEventClient(contextName string, namespace string, client chan DaemonSetEvent) {\n\n\t// Get the context receiver\n\tctxReceiver, ok := contextReceivers[contextName]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the namespace receiver\n\tnsReceiver, ok := ctxReceiver.namespaceReceivers[namespace]\n\tif !ok {\n\t\treturn\n\t}\n\n\t// Get the receiver\n\treceiver := nsReceiver.daemonSetEventReceiver\n\tif receiver == nil {\n\t\treturn\n\t}\n\n\t// Remove the client\n\treceiver.removeClient(client)\n\n\t// If no more client, stop receiving event\n\tif len(receiver.clients) == 0 {\n\t\treceiver.stop()\n\t\tnsReceiver.daemonSetEventReceiver = nil\n\t}\n}", "func (c *awsServiceDiscoveryServices) DeleteCollection(options *meta_v1.DeleteOptions, listOptions meta_v1.ListOptions) error {\n\treturn c.client.Delete().\n\t\tNamespace(c.ns).\n\t\tResource(\"awsservicediscoveryservices\").\n\t\tVersionedParams(&listOptions, scheme.ParameterCodec).\n\t\tBody(options).\n\t\tDo().\n\t\tError()\n}" ]
[ "0.7853541", "0.7769826", "0.7575461", "0.7491888", "0.73989016", "0.61222357", "0.6069213", "0.6067609", "0.597061", "0.5968354", "0.5897512", "0.58283925", "0.58184576", "0.58067673", "0.5780559", "0.5724794", "0.5696786", "0.564604", "0.5611049", "0.54969746", "0.5492194", "0.54517674", "0.54415333", "0.5379202", "0.5374732", "0.5374251", "0.53386474", "0.53356946", "0.5262013", "0.5185041", "0.5175122", "0.51588017", "0.51376176", "0.5124247", "0.5104988", "0.50860643", "0.5075153", "0.50462687", "0.5002382", "0.4999206", "0.4976331", "0.49672472", "0.49440494", "0.49367756", "0.49214545", "0.49179643", "0.48961744", "0.48957056", "0.48649517", "0.48542866", "0.48133713", "0.48068872", "0.48052067", "0.47941846", "0.47888204", "0.4784663", "0.47662622", "0.47528937", "0.47406676", "0.47142893", "0.47117534", "0.4707802", "0.4707585", "0.47032094", "0.46954829", "0.46908388", "0.46866846", "0.46738905", "0.4662515", "0.4661618", "0.46580914", "0.46542352", "0.46529403", "0.4644828", "0.46209174", "0.46195984", "0.46183884", "0.4616934", "0.46084", "0.46056333", "0.46047187", "0.45934296", "0.45931026", "0.45914513", "0.45847735", "0.4577955", "0.4573303", "0.45656633", "0.45633718", "0.4554073", "0.45514184", "0.45512927", "0.45506588", "0.45442706", "0.45420444", "0.45404902", "0.4539729", "0.4538187", "0.45381188", "0.45253706" ]
0.7587309
2
WaitForDaemonset waits until a daemonset has propagated containers across the affected nodes.
func (c *Cluster) WaitForDaemonset(ctx context.Context, ds *appsv1.DaemonSet) error { w, err := c.client.AppsV1().DaemonSets(ds.GetNamespace()).Watch(ctx, v1.ListOptions{ FieldSelector: fields.SelectorFromSet(fields.Set{v1.ObjectNameField: ds.ObjectMeta.Name}).String(), }) if err != nil { return fmt.Errorf("failed to watch DaemonSet: %w", err) } defer w.Stop() for { select { case <-ctx.Done(): return fmt.Errorf("context canceled before DaemonSet was healthy") case e, ok := <-w.ResultChan(): d, ok := e.Object.(*appsv1.DaemonSet) if !ok { return fmt.Errorf("invalid object type: %T", d) } if d.Status.NumberReady == d.Status.DesiredNumberScheduled && d.Status.NumberUnavailable == 0 { return nil } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WaitForDaemonSet(t *testing.T, kubeclient kubernetes.Interface, namespace, name string, retryInterval, timeout time.Duration) error {\n\tstart := time.Now()\n\terr := wait.Poll(retryInterval, timeout, func() (done bool, err error) {\n\t\tctxWithTimeout, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\n\t\tdaemonset, err := kubeclient.AppsV1().DaemonSets(namespace).Get(ctxWithTimeout, name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tt.Logf(\"Waiting for availability of %s daemonset\\n\", name)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tif daemonset.Status.NumberReady > 0 && daemonset.Status.NumberReady == daemonset.Status.DesiredNumberScheduled {\n\t\t\treturn true, nil\n\t\t}\n\t\tt.Logf(\"Waiting for full availability of %s daemonsets (%d/%d)\\n\", name, daemonset.Status.NumberReady, daemonset.Status.DesiredNumberScheduled)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Logf(\"Failed waiting for daemonset %s after %s\\n\", name, time.Since(start))\n\t\treturn err\n\t}\n\tt.Logf(\"DaemonSet %s available after %s\\n\", name, time.Since(start))\n\treturn nil\n}", "func (c *Client) WaitForDaemonSet(ns, name string, timeout time.Duration) error {\n\tif c.ApplyDryRun {\n\t\treturn nil\n\t}\n\tclient, err := c.GetClientset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdaemonsets := client.AppsV1().DaemonSets(ns)\n\tid := Name{Kind: \"Daemonset\", Name: name, Namespace: ns}\n\tstart := time.Now()\n\tmsg := false\n\tfor {\n\t\tdaemonset, err := daemonsets.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif start.Add(timeout).Before(time.Now()) {\n\t\t\treturn fmt.Errorf(\"%s timeout waiting for daemonset to become ready\", id)\n\t\t}\n\n\t\tif daemonset != nil && daemonset.Status.NumberReady >= 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !msg {\n\t\t\tc.Infof(\"%s ⏳ waiting for at least 1 pod\", id)\n\t\t\tmsg = true\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}", "func waitForDaemonSets(c kubernetes.Interface, ns string, allowedNotReadyNodes int32, timeout time.Duration) error {\n\tif allowedNotReadyNodes == -1 {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\tframework.Logf(\"Waiting up to %v for all daemonsets in namespace '%s' to start\",\n\t\ttimeout, ns)\n\n\treturn wait.PollImmediate(framework.Poll, timeout, func() (bool, error) {\n\t\tdsList, err := c.AppsV1().DaemonSets(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\tframework.Logf(\"Error getting daemonsets in namespace: '%s': %v\", ns, err)\n\t\t\treturn false, err\n\t\t}\n\t\tvar notReadyDaemonSets []string\n\t\tfor _, ds := range dsList.Items {\n\t\t\tframework.Logf(\"%d / %d pods ready in namespace '%s' in daemonset '%s' (%d seconds elapsed)\", ds.Status.NumberReady, ds.Status.DesiredNumberScheduled, ns, ds.ObjectMeta.Name, int(time.Since(start).Seconds()))\n\t\t\tif ds.Status.DesiredNumberScheduled-ds.Status.NumberReady > allowedNotReadyNodes {\n\t\t\t\tnotReadyDaemonSets = append(notReadyDaemonSets, ds.ObjectMeta.Name)\n\t\t\t}\n\t\t}\n\n\t\tif len(notReadyDaemonSets) > 0 {\n\t\t\tframework.Logf(\"there are not ready daemonsets: %v\", notReadyDaemonSets)\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t})\n}", "func WaitDaemonsetReady(namespace, name string, timeout time.Duration) error {\n\n\tnodes, err := daemonsetClient.K8sClient.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get node list, err:%s\", err)\n\t}\n\n\tnodesCount := int32(len(nodes.Items))\n\tisReady := false\n\tfor start := time.Now(); !isReady && time.Since(start) < timeout; {\n\t\tdaemonSet, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Get(context.Background(), name, metav1.GetOptions{})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get daemonset, err: %s\", err)\n\t\t}\n\n\t\tif daemonSet.Status.DesiredNumberScheduled != nodesCount {\n\t\t\treturn fmt.Errorf(\"daemonset DesiredNumberScheduled not equal to number of nodes:%d, please instantiate debug pods on all nodes\", nodesCount)\n\t\t}\n\n\t\tlogrus.Infof(\"Waiting for (%d) debug pods to be ready: %+v\", nodesCount, daemonSet.Status)\n\t\tif isDaemonSetReady(&daemonSet.Status) {\n\t\t\tisReady = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tif !isReady {\n\t\treturn errors.New(\"daemonset debug pods not ready\")\n\t}\n\n\tlogrus.Infof(\"All the debug pods are ready.\")\n\treturn nil\n}", "func ForDaemonSetReady(clName string, c kubernetes.Interface, namespace, daemonSetName string) error {\n\tctx := context.Background()\n\tlog.Debugf(\"Waiting up to %v for %s daemon set roll out %s ...\", defaults.WaitDurationResources, daemonSetName, clName)\n\tdeploymentContext, cancel := context.WithTimeout(ctx, defaults.WaitDurationResources)\n\twait.Until(func() {\n\t\tdaemonSet, err := c.AppsV1().DaemonSets(namespace).Get(daemonSetName, metav1.GetOptions{})\n\t\tif err == nil && daemonSet.Status.CurrentNumberScheduled > 0 {\n\t\t\tif daemonSet.Status.NumberReady == daemonSet.Status.DesiredNumberScheduled {\n\t\t\t\tlog.Infof(\"✔ %s successfully rolled out to %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t\tcancel()\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"Still waiting for %s daemon set roll out for %s, ready replicas: %v\", daemonSetName, clName, daemonSet.Status.NumberReady)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debugf(\"Still waiting for %s daemon set roll out %s ...\", daemonSetName, clName)\n\t\t}\n\t}, 5*time.Second, deploymentContext.Done())\n\terr := deploymentContext.Err()\n\tif err != nil && err != context.Canceled {\n\t\treturn errors.Wrapf(err, \"Error waiting for %s daemon set roll out.\", daemonSetName)\n\t}\n\treturn nil\n}", "func makeDaemonsets(dsc *Checker, orphan bool) error {\n\n\tif orphan {\n\t\tdsc.hostname = \"ORPHANED-TEST\"\n\t}\n\n\tcheckRunTime := strconv.Itoa(int(CheckRunTime))\n\thostname := getHostname()\n\n\tterminationGracePeriod := int64(1)\n\ttestDS := Checker{\n\t\tNamespace: Namespace,\n\t\tDaemonSetName: daemonSetBaseName + \"-\" + hostname + \"-\" + checkRunTime,\n\t\thostname: hostname,\n\t}\n\n\ttestDS.DaemonSet = &appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: testDS.DaemonSetName,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": testDS.DaemonSetName,\n\t\t\t\t\t\t\"source\": \"kuberhealthy\",\n\t\t\t\t\t\t\"creatingInstance\": dsc.hostname,\n\t\t\t\t\t\t\"checkRunTime\": checkRunTime,\n\t\t\t\t\t},\n\t\t\t\t\tName: testDS.DaemonSetName,\n\t\t\t\t},\n\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\tTerminationGracePeriodSeconds: &terminationGracePeriod,\n\t\t\t\t\tTolerations: []apiv1.Toleration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: \"node-role.kubernetes.io/master\",\n\t\t\t\t\t\t\tEffect: \"NoSchedule\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tContainers: []apiv1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"sleep\",\n\t\t\t\t\t\t\tImage: \"gcr.io/google_containers/pause:0.8.0\",\n\t\t\t\t\t\t\tResources: apiv1.ResourceRequirements{\n\t\t\t\t\t\t\t\tRequests: apiv1.ResourceList{\n\t\t\t\t\t\t\t\t\tapiv1.ResourceCPU: resource.MustParse(\"0\"),\n\t\t\t\t\t\t\t\t\tapiv1.ResourceMemory: resource.MustParse(\"0\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tdaemonSetClient := dsc.getDaemonSetClient()\n\t_, err := daemonSetClient.Create(testDS.DaemonSet)\n\treturn err\n}", "func CreateDaemonSet(daemonSetName, namespace, containerName, imageWithVersion string, timeout time.Duration) (*v1core.PodList, error) {\n\n\trebootDaemonSet := createDaemonSetsTemplate(daemonSetName, namespace, containerName, imageWithVersion)\n\n\tif doesDaemonSetExist(daemonSetName, namespace) {\n\t\terr := DeleteDaemonSet(daemonSetName, namespace)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to delete %s daemonset because: %s\", daemonSetName, err)\n\t\t}\n\t}\n\n\tlogrus.Infof(\"Creating daemonset %s\", daemonSetName)\n\t_, err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Create(context.TODO(), rebootDaemonSet, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = WaitDaemonsetReady(namespace, daemonSetName, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Deamonset is ready\")\n\n\tvar ptpPods *v1core.PodList\n\tptpPods, err = daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\tif err != nil {\n\t\treturn ptpPods, err\n\t}\n\tlogrus.Infof(\"Successfully created daemonset %s\", daemonSetName)\n\treturn ptpPods, nil\n}", "func DaemonSetIsReady(resource common.ComponentResource) (bool, error) {\n\tvar daemonSet appsv1.DaemonSet\n\tif err := getObject(resource, &daemonSet, true); err != nil {\n\t\treturn false, err\n\t}\n\n\t// if we have a name that is empty, we know we did not find the object\n\tif daemonSet.Name == \"\" {\n\t\treturn false, nil\n\t}\n\n\t// ensure the desired number is scheduled and ready\n\tif daemonSet.Status.DesiredNumberScheduled == daemonSet.Status.NumberReady {\n\t\tif daemonSet.Status.NumberReady > 0 && daemonSet.Status.NumberUnavailable < 1 {\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (c *Client) WaitForStatefulSet(ns, name string, timeout time.Duration) error {\n\tif c.ApplyDryRun {\n\t\treturn nil\n\t}\n\tclient, err := c.GetClientset()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatefulsets := client.AppsV1().StatefulSets(ns)\n\tid := Name{Kind: \"Statefulset\", Namespace: ns, Name: name}\n\tstart := time.Now()\n\tmsg := false\n\tfor {\n\t\tstatefulset, _ := statefulsets.Get(context.TODO(), name, metav1.GetOptions{})\n\t\tif start.Add(timeout).Before(time.Now()) {\n\t\t\treturn fmt.Errorf(\"timeout exceeded waiting for statefulset to become ready %s\", name)\n\t\t}\n\t\tif statefulset != nil && statefulset.Status.ReadyReplicas >= 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !msg {\n\t\t\tc.Infof(\"%s ⏳ waiting for at least 1 pod\", id)\n\t\t\tmsg = true\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}", "func WaitForStatefulSetToBeReady(t *testing.T, mdb *mdbv1.MongoDBCommunity, retryInterval, timeout time.Duration) error {\n\treturn waitForStatefulSetCondition(t, mdb, retryInterval, timeout, func(sts appsv1.StatefulSet) bool {\n\t\treturn statefulset.IsReady(sts, mdb.Spec.Members)\n\t})\n}", "func ReconcileDaemonSet(c client.Client, hdfs hdfsv1.HDFS, expected v1.DaemonSet) (v1.DaemonSet, error) {\n\n\t//create kind instance\n\tvar reconciled v1.DaemonSet\n\terr := ReconcileResource(Params{\n\t\tClient: c,\n\t\tOwner: &hdfs,\n\t\tExpected: &expected,\n\t\tReconciled: &reconciled,\n\t})\n\n\treturn reconciled, err\n}", "func daemonSetIsReady(ds *appsv1.DaemonSet) bool {\n\treturn ds.Status.DesiredNumberScheduled == ds.Status.NumberAvailable\n}", "func WaitForStatefulset(t *testing.T, kubeclient kubernetes.Interface, namespace, name string, retryInterval, timeout time.Duration) error {\n\tstart := time.Now()\n\terr := wait.Poll(retryInterval, timeout, func() (done bool, err error) {\n\t\tctxWithTimeout, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\n\t\tstatefulset, err := kubeclient.AppsV1().StatefulSets(namespace).Get(ctxWithTimeout, name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\tt.Logf(\"Waiting for availability of %s statefulset\\n\", name)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\n\t\tif statefulset.Status.ReadyReplicas == statefulset.Status.CurrentReplicas {\n\t\t\treturn true, nil\n\t\t}\n\t\tt.Logf(\"Waiting for full availability of %s statefulsets (%d/%d)\\n\", name, statefulset.Status.ReadyReplicas, statefulset.Status.CurrentReplicas)\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Logf(\"Failed waiting for statefulset %s after %s\\n\", name, time.Since(start))\n\t\treturn err\n\t}\n\tt.Logf(\"Statefulset %s available after %s\\n\", name, time.Since(start))\n\treturn nil\n}", "func desiredNodeResolverDaemonSet(dns *operatorv1.DNS, clusterIP, clusterDomain, openshiftCLIImage string) (bool, *appsv1.DaemonSet, error) {\n\thostPathFile := corev1.HostPathFile\n\t// TODO: Consider setting maxSurge to a positive value.\n\tmaxSurge := intstr.FromInt(0)\n\tmaxUnavailable := intstr.FromString(\"33%\")\n\tenvs := []corev1.EnvVar{{\n\t\tName: \"SERVICES\",\n\t\tValue: services,\n\t}}\n\tif len(clusterIP) > 0 {\n\t\tenvs = append(envs, corev1.EnvVar{\n\t\t\tName: \"NAMESERVER\",\n\t\t\tValue: clusterIP,\n\t\t})\n\t}\n\tif len(clusterDomain) > 0 {\n\t\tenvs = append(envs, corev1.EnvVar{\n\t\t\tName: \"CLUSTER_DOMAIN\",\n\t\t\tValue: clusterDomain,\n\t\t})\n\t}\n\ttrueVal := true\n\tname := NodeResolverDaemonSetName()\n\tdaemonset := appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name.Name,\n\t\t\tNamespace: name.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\tdnsOwnerRef(dns),\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: NodeResolverDaemonSetPodSelector(),\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tworkloadPartitioningManagement: `{\"effect\": \"PreferredDuringScheduling\"}`,\n\t\t\t\t\t},\n\t\t\t\t\tLabels: NodeResolverDaemonSetPodSelector().MatchLabels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tCommand: []string{\n\t\t\t\t\t\t\t\"/bin/bash\", \"-c\",\n\t\t\t\t\t\t\tnodeResolverScript,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tEnv: envs,\n\t\t\t\t\t\tImage: openshiftCLIImage,\n\t\t\t\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\t\t\t\tName: \"dns-node-resolver\",\n\t\t\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\t\t\tRequests: corev1.ResourceList{\n\t\t\t\t\t\t\t\tcorev1.ResourceCPU: resource.MustParse(\"5m\"),\n\t\t\t\t\t\t\t\tcorev1.ResourceMemory: resource.MustParse(\"21Mi\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\tPrivileged: &trueVal,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,\n\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{{\n\t\t\t\t\t\t\tName: \"hosts-file\",\n\t\t\t\t\t\t\tMountPath: \"/etc/hosts\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t\t// The node-resolver pods need to run on\n\t\t\t\t\t// every node in the cluster. On nodes\n\t\t\t\t\t// that have Smart NICs, each pod that\n\t\t\t\t\t// uses the container network consumes\n\t\t\t\t\t// an SR-IOV device. Using the host\n\t\t\t\t\t// network eliminates the need for this\n\t\t\t\t\t// scarce resource.\n\t\t\t\t\tHostNetwork: true,\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"kubernetes.io/os\": \"linux\",\n\t\t\t\t\t},\n\t\t\t\t\tPriorityClassName: \"system-node-critical\",\n\t\t\t\t\tServiceAccountName: \"node-resolver\",\n\t\t\t\t\tTolerations: []corev1.Toleration{{\n\t\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t\t}},\n\t\t\t\t\tVolumes: []corev1.Volume{{\n\t\t\t\t\t\tName: \"hosts-file\",\n\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\tPath: \"/etc/hosts\",\n\t\t\t\t\t\t\t\tType: &hostPathFile,\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\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tType: appsv1.RollingUpdateDaemonSetStrategyType,\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxSurge: &maxSurge,\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn true, &daemonset, nil\n}", "func DeleteDaemonSet(daemonSetName, namespace string) error {\n\tconst (\n\t\tTimeout = 5 * time.Minute\n\t)\n\n\tlogrus.Infof(\"Deleting daemonset %s\", daemonSetName)\n\tdeletePolicy := metav1.DeletePropagationForeground\n\n\tif err := daemonsetClient.K8sClient.AppsV1().DaemonSets(namespace).Delete(context.TODO(), daemonSetName, metav1.DeleteOptions{\n\t\tPropagationPolicy: &deletePolicy,\n\t}); err != nil {\n\t\tlogrus.Infof(\"The daemonset (%s) deletion is unsuccessful due to %+v\", daemonSetName, err.Error())\n\t}\n\n\tfor start := time.Now(); time.Since(start) < Timeout; {\n\n\t\tpods, err := daemonsetClient.K8sClient.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: \"name=\" + daemonSetName})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pods, err: %s\", err)\n\t\t}\n\n\t\tif len(pods.Items) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(waitingTime)\n\t}\n\n\tlogrus.Infof(\"Successfully cleaned up daemonset %s\", daemonSetName)\n\treturn nil\n}", "func (c *Vrouter) PrepareDaemonSet(ds *appsv1.DaemonSet,\n\tcommonConfiguration *PodConfiguration,\n\trequest reconcile.Request,\n\tscheme *runtime.Scheme,\n\tclient client.Client) error {\n\tinstanceType := \"vrouter\"\n\tSetDSCommonConfiguration(ds, commonConfiguration)\n\tds.SetName(request.Name + \"-\" + instanceType + \"-daemonset\")\n\tds.SetNamespace(request.Namespace)\n\tds.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Selector.MatchLabels = map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name}\n\tds.Spec.Template.SetLabels(map[string]string{\"contrail_manager\": instanceType,\n\t\tinstanceType: request.Name})\n\tds.Spec.Template.Spec.Affinity = &corev1.Affinity{\n\t\tPodAntiAffinity: &corev1.PodAntiAffinity{\n\t\t\tRequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{{\n\t\t\t\tLabelSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchExpressions: []metav1.LabelSelectorRequirement{{\n\t\t\t\t\t\tKey: instanceType,\n\t\t\t\t\t\tOperator: \"Exists\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t\tTopologyKey: \"kubernetes.io/hostname\",\n\t\t\t}},\n\t\t},\n\t}\n\terr := controllerutil.SetControllerReference(c, ds, scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CalicoDaemonSet(repo string) string {\n\treturn calicoCommon(repo, \"node\")\n\n}", "func ReconcileDaemonSets(ctx context.Context, namedGetters []NamedDaemonSetCreatorGetter, namespace string, client ctrlruntimeclient.Client, objectModifiers ...ObjectModifier) error {\n\tfor _, get := range namedGetters {\n\t\tname, create := get()\n\t\tcreate = DefaultDaemonSet(create)\n\t\tcreateObject := DaemonSetObjectWrapper(create)\n\t\tcreateObject = createWithNamespace(createObject, namespace)\n\t\tcreateObject = createWithName(createObject, name)\n\n\t\tfor _, objectModifier := range objectModifiers {\n\t\t\tcreateObject = objectModifier(createObject)\n\t\t}\n\n\t\tif err := EnsureNamedObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, createObject, client, &appsv1.DaemonSet{}, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to ensure DaemonSet %s/%s: %v\", namespace, name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func WaitForInfraServices(ctx context.Context, kc *kubernetes.Clientset) error {\n\tfor _, app := range daemonsetWhitelist {\n\t\tlog.Infof(\"checking daemonset %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\tds, err := kc.AppsV1().DaemonSets(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\treturn ds.Status.DesiredNumberScheduled == ds.Status.CurrentNumberScheduled &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.NumberReady &&\n\t\t\t\t\tds.Status.DesiredNumberScheduled == ds.Status.UpdatedNumberScheduled &&\n\t\t\t\t\tds.Generation == ds.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, app := range deploymentWhitelist {\n\t\tlog.Infof(\"checking deployment %s/%s\", app.Namespace, app.Name)\n\n\t\terr := wait.PollImmediateUntil(time.Second, func() (bool, error) {\n\t\t\td, err := kc.AppsV1().Deployments(app.Namespace).Get(app.Name, metav1.GetOptions{})\n\t\t\tswitch {\n\t\t\tcase kerrors.IsNotFound(err):\n\t\t\t\treturn false, nil\n\t\t\tcase err == nil:\n\t\t\t\tspecReplicas := int32(1)\n\t\t\t\tif d.Spec.Replicas != nil {\n\t\t\t\t\tspecReplicas = *d.Spec.Replicas\n\t\t\t\t}\n\n\t\t\t\treturn specReplicas == d.Status.Replicas &&\n\t\t\t\t\tspecReplicas == d.Status.ReadyReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.AvailableReplicas &&\n\t\t\t\t\tspecReplicas == d.Status.UpdatedReplicas &&\n\t\t\t\t\td.Generation == d.Status.ObservedGeneration, nil\n\t\t\tdefault:\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}, ctx.Done())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func expectedDaemonSet(instance *sfv1alpha1.SplunkForwarder) *appsv1.DaemonSet {\n\tvar expectedRunAsUID int64 = 0\n\tvar expectedIsPrivContainer bool = true\n\tvar expectedTerminationGracePeriodSeconds int64 = 10\n\n\tuseVolumeSecret := !instance.Spec.UseHeavyForwarder\n\tvar sfImage string\n\tif instance.Spec.ImageDigest == \"\" {\n\t\tsfImage = image + \":\" + imageTag\n\t} else {\n\t\tsfImage = image + \"@\" + imageDigest\n\t}\n\n\treturn &appsv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName + \"-ds\",\n\t\t\tNamespace: instanceNamespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": instanceName,\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"genVersion\": \"10\",\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"name\": \"splunk-forwarder\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: \"splunk-forwarder\",\n\t\t\t\t\tNamespace: instanceNamespace,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": \"splunk-forwarder\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\t\"beta.kubernetes.io/os\": \"linux\",\n\t\t\t\t\t},\n\n\t\t\t\t\tServiceAccountName: \"default\",\n\t\t\t\t\tTolerations: []corev1.Toleration{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tOperator: corev1.TolerationOpExists,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tTerminationGracePeriodSeconds: &expectedTerminationGracePeriodSeconds,\n\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"splunk-uf\",\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullAlways,\n\t\t\t\t\t\t\tImage: sfImage,\n\t\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tContainerPort: 8089,\n\t\t\t\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResources: corev1.ResourceRequirements{},\n\t\t\t\t\t\t\tTerminationMessagePath: \"/dev/termination-log\",\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"SPLUNK_ACCEPT_LICENSE\",\n\t\t\t\t\t\t\t\t\tValue: \"yes\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t {\n\t\t\t\t\t\t Name: \"HOSTNAME\",\n\t\t\t\t\t\t ValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\t\t FieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\t\t FieldPath: \"spec.nodeName\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t },\n\n\t\t\t\t\t\t\tVolumeMounts: GetVolumeMounts(instance),\n\n\t\t\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\t\t\tPrivileged: &expectedIsPrivContainer,\n\t\t\t\t\t\t\t\tRunAsUser: &expectedRunAsUID,\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\tVolumes: GetVolumes(true, useVolumeSecret, instanceName),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func CreateDaemonSet(client *rancher.Client, clusterName, daemonSetName, namespace string, template corev1.PodTemplateSpec) (*appv1.DaemonSet, error) {\n\tdynamicClient, err := client.GetDownStreamClusterClient(clusterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabels := map[string]string{}\n\tlabels[\"workload.user.cattle.io/workloadselector\"] = fmt.Sprintf(\"apps.daemonset-%v-%v\", namespace, daemonSetName)\n\n\ttemplate.ObjectMeta = metav1.ObjectMeta{\n\t\tLabels: labels,\n\t}\n\ttemplate.Spec.RestartPolicy = corev1.RestartPolicyAlways\n\tdaemonSet := &appv1.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: daemonSetName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: template,\n\t\t},\n\t}\n\n\tdaemonSetResource := dynamicClient.Resource(DaemonSetGroupVersionResource).Namespace(namespace)\n\n\tunstructuredResp, err := daemonSetResource.Create(context.TODO(), unstructured.MustToUnstructured(daemonSet), metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewDaemonSet := &appv1.DaemonSet{}\n\terr = scheme.Scheme.Convert(unstructuredResp, newDaemonSet, unstructuredResp.GroupVersionKind())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn daemonSet, nil\n}", "func EnsureDaemonSetNode(g osgraph.MutableUniqueGraph, ds *kappsv1.DaemonSet) *DaemonSetNode {\n\tdsName := DaemonSetNodeName(ds)\n\tdsNode := osgraph.EnsureUnique(\n\t\tg,\n\t\tdsName,\n\t\tfunc(node osgraph.Node) graph.Node {\n\t\t\treturn &DaemonSetNode{Node: node, DaemonSet: ds, IsFound: true}\n\t\t},\n\t).(*DaemonSetNode)\n\n\tpodTemplateSpecNode := EnsurePodTemplateSpecNode(g, &ds.Spec.Template, ds.Namespace, dsName)\n\tg.AddEdge(dsNode, podTemplateSpecNode, osgraph.ContainsEdgeKind)\n\n\treturn dsNode\n}", "func GetDaemonSetContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.DaemonSet).Spec.Template.Spec.Containers\n}", "func (m *Machine) WaitForStatefulSet(namespace string, labels string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.StatefulSetRunning(namespace, labels)\n\t})\n}", "func (r *ReconcileHostPathProvisioner) reconcileDaemonSet(reqLogger logr.Logger, instance *hostpathprovisionerv1alpha1.HostPathProvisioner, namespace string) (reconcile.Result, error) {\n\t// Define a new DaemonSet object\n\tprovisionerImage := os.Getenv(provisionerImageEnvVarName)\n\tif provisionerImage == \"\" {\n\t\treqLogger.Info(\"PROVISIONER_IMAGE not set, defaulting to hostpath-provisioner\")\n\t\tprovisionerImage = ProvisionerImageDefault\n\t}\n\n\tdesired := createDaemonSetObject(instance, provisionerImage, namespace)\n\tdesiredMetaObj := &desired.ObjectMeta\n\tsetLastAppliedConfiguration(desiredMetaObj)\n\n\t// Set HostPathProvisioner instance as the owner and controller\n\tif err := controllerutil.SetControllerReference(instance, desired, r.scheme); err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Check if this DaemonSet already exists\n\tfound := &appsv1.DaemonSet{}\n\terr := r.client.Get(context.TODO(), types.NamespacedName{Name: desired.Name, Namespace: desired.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\treqLogger.Info(\"Creating a new DaemonSet\", \"DaemonSet.Namespace\", desired.Namespace, \"Daemonset.Name\", desired.Name)\n\t\terr = r.client.Create(context.TODO(), desired)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\n\t\t// DaemonSet created successfully - don't requeue\n\t\treturn reconcile.Result{}, nil\n\t} else if err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Keep a copy of the original for comparison later.\n\tcurrentRuntimeObjCopy := found.DeepCopyObject()\n\t// Copy found status fields, so the compare won't fail on desired/scheduled/ready pods being different. Updating will ignore them anyway.\n\tdesired = copyStatusFields(desired, found)\n\n\t// allow users to add new annotations (but not change ours)\n\tmergeLabelsAndAnnotations(desiredMetaObj, &found.ObjectMeta)\n\n\t// create merged DaemonSet from found and desired.\n\tmerged, err := mergeObject(desired, found)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\tif !reflect.DeepEqual(currentRuntimeObjCopy, merged) {\n\t\tlogJSONDiff(reqLogger, currentRuntimeObjCopy, merged)\n\t\t// Current is different from desired, update.\n\t\treqLogger.Info(\"Updating DaemonSet\", \"DaemonSet.Name\", desired.Name)\n\t\terr = r.client.Update(context.TODO(), merged)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t\treturn reconcile.Result{}, nil\n\t}\n\n\t// DaemonSet already exists and matches the desired state - don't requeue\n\treqLogger.Info(\"Skip reconcile: DaemonSet already exists\", \"DaemonSet.Namespace\", found.Namespace, \"Daemonset.Name\", found.Name)\n\treturn reconcile.Result{}, nil\n}", "func (r *reconciler) ensureNodeResolverDaemonSet(dns *operatorv1.DNS, clusterIP, clusterDomain string) (bool, *appsv1.DaemonSet, error) {\n\thaveDS, current, err := r.currentNodeResolverDaemonSet()\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\twantDS, desired, err := desiredNodeResolverDaemonSet(dns, clusterIP, clusterDomain, r.OpenshiftCLIImage)\n\tif err != nil {\n\t\treturn haveDS, current, fmt.Errorf(\"failed to build node resolver daemonset: %v\", err)\n\t}\n\tswitch {\n\tcase !wantDS && !haveDS:\n\t\treturn false, nil, nil\n\tcase !wantDS && haveDS:\n\t\tif err := r.deleteNodeResolverDaemonSet(current); err != nil {\n\t\t\treturn true, current, err\n\t\t}\n\t\treturn false, nil, nil\n\tcase wantDS && !haveDS:\n\t\tif err := r.createNodeResolverDaemonSet(desired); err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\treturn r.currentNodeResolverDaemonSet()\n\tcase wantDS && haveDS:\n\t\tif updated, err := r.updateNodeResolverDaemonSet(current, desired); err != nil {\n\t\t\treturn true, current, err\n\t\t} else if updated {\n\t\t\treturn r.currentNodeResolverDaemonSet()\n\t\t}\n\t}\n\treturn true, current, nil\n}", "func (sia *statefulsetInitAwaiter) await(\n\tstatefulsetEvents, podEvents <-chan watch.Event,\n\ttimeout, aggregateErrorTicker <-chan time.Time,\n) error {\n\tfor {\n\t\tif sia.checkAndLogStatus() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Else, wait for updates.\n\t\tselect {\n\t\tcase <-sia.config.ctx.Done():\n\t\t\treturn &cancellationError{\n\t\t\t\tobject: sia.statefulset,\n\t\t\t\tsubErrors: sia.errorMessages(),\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\treturn &timeoutError{\n\t\t\t\tobject: sia.statefulset,\n\t\t\t\tsubErrors: sia.errorMessages(),\n\t\t\t}\n\t\tcase <-aggregateErrorTicker:\n\t\t\tmessages := sia.aggregatePodErrors()\n\t\t\tfor _, message := range messages {\n\t\t\t\tsia.config.logMessage(message)\n\t\t\t}\n\t\tcase event := <-statefulsetEvents:\n\t\t\tsia.processStatefulSetEvent(event)\n\t\tcase event := <-podEvents:\n\t\t\tsia.processPodEvent(event)\n\t\t}\n\t}\n}", "func (h *H) WaitTimeoutForDaemonSetInNamespace(ctx context.Context, daemonSetName string, namespace string, timeout time.Duration, poll time.Duration) error {\n\treturn (wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tif _, err := h.Kube().AppsV1().DaemonSets(namespace).Get(ctx, daemonSetName, metav1.GetOptions{}); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}))\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Machine) WaitForStatefulSetDelete(namespace string, name string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\tfound, err := m.StatefulSetExist(namespace, name)\n\t\treturn !found, err\n\t})\n}", "func (sia *statefulsetInitAwaiter) Await() error {\n\tstopper := make(chan struct{})\n\tdefer close(stopper)\n\n\tinformerFactory := informers.NewInformerFactory(sia.config.clientSet,\n\t\tinformers.WithNamespaceOrDefault(sia.config.currentInputs.GetNamespace()))\n\tinformerFactory.Start(stopper)\n\n\tstatefulSetEvents := make(chan watch.Event)\n\tstatefulSetInformer, err := informers.New(informerFactory, informers.ForGVR(schema.GroupVersionResource{\n\t\tGroup: \"apps\",\n\t\tVersion: \"v1\",\n\t\tResource: \"statefulsets\",\n\t}), informers.WithEventChannel(statefulSetEvents))\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo statefulSetInformer.Informer().Run(stopper)\n\n\tpodEvents := make(chan watch.Event)\n\tpodInformer, err := informers.New(informerFactory, informers.ForPods(), informers.WithEventChannel(podEvents))\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo podInformer.Informer().Run(stopper)\n\n\taggregateErrorTicker := time.NewTicker(10 * time.Second)\n\tdefer aggregateErrorTicker.Stop()\n\n\ttimeout := metadata.TimeoutDuration(sia.config.timeout, sia.config.currentInputs, DefaultStatefulSetTimeoutMins*60)\n\treturn sia.await(statefulSetEvents, podEvents, time.After(timeout), aggregateErrorTicker.C)\n}", "func GetDaemonSetInitContainers(item interface{}) []corev1.Container {\n\treturn item.(appsv1.DaemonSet).Spec.Template.Spec.InitContainers\n}", "func (a *MemberAwaitility) WaitUntilNSTemplateSetDeleted(name string) error {\n\treturn wait.Poll(a.RetryInterval, a.Timeout, func() (done bool, err error) {\n\t\tnsTmplSet := &toolchainv1alpha1.NSTemplateSet{}\n\t\tif err := a.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: a.Namespace}, nsTmplSet); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\ta.T.Logf(\"deleted NSTemplateSet '%s'\", name)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\ta.T.Logf(\"waiting for deletion of NSTemplateSet '%s'\", name)\n\t\treturn false, nil\n\t})\n}", "func (c *component) daemonset() *appsv1.DaemonSet {\n\tmaxUnavailable := intstr.FromInt(1)\n\n\tannots := map[string]string{}\n\n\tif c.config.envoyConfigMap != nil {\n\t\tannots[EnvoyConfigMapName] = rmeta.AnnotationHash(c.config.envoyConfigMap)\n\t}\n\n\tif c.config.ModSecurityConfigMap != nil {\n\t\tannots[ModSecurityRulesetHashAnnotation] = rmeta.AnnotationHash(c.config.ModSecurityConfigMap.Data)\n\t}\n\n\tpodTemplate := corev1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tAnnotations: annots,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tHostIPC: true,\n\t\t\tHostNetwork: true,\n\t\t\tServiceAccountName: APLName,\n\t\t\tDNSPolicy: corev1.DNSClusterFirstWithHostNet,\n\t\t\t// Absence of l7 daemonset pod on a node will break the annotated services connectivity, so we tolerate all.\n\t\t\tTolerations: rmeta.TolerateAll,\n\t\t\tImagePullSecrets: secret.GetReferenceList(c.config.PullSecrets),\n\t\t\tContainers: c.containers(),\n\t\t\tVolumes: c.volumes(),\n\t\t},\n\t}\n\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"DaemonSet\", APIVersion: \"apps/v1\"},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ApplicationLayerDaemonsetName,\n\t\t\tNamespace: common.CalicoNamespace,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: podTemplate,\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func WaitForStatefulSetToBeReadyAfterScaleDown(t *testing.T, mdb *mdbv1.MongoDBCommunity, retryInterval, timeout time.Duration) error {\n\treturn waitForStatefulSetCondition(t, mdb, retryInterval, timeout, func(sts appsv1.StatefulSet) bool {\n\t\treturn int32(mdb.Spec.Members) == sts.Status.ReadyReplicas\n\t})\n}", "func waitForGlusterContainer() error {\n\n\t//Check if docker gluster container is up and running\n\tfor {\n\t\tglusterServerContainerVal, err := helpers.GetSystemDockerNode(\"gluster-server\")\n\t\tif err != nil {\n\t\t\trwolog.Error(\"Error in checking docker gluster container for status \", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tif len(glusterServerContainerVal) > 0 {\n\t\t\tbreak\n\t\t} else {\n\t\t\trwolog.Debug(\"Sleeping for 10 seconds to get gluster docker container up\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func WaitForPodsReady(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) error {\n\treturn wait.PollImmediate(1*time.Second, time.Minute*5, func() (bool, error) {\n\t\tpl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tr := 0\n\t\tfor i := range pl.Items {\n\t\t\tif isRunning, _ := podRunningReady(&pl.Items[i]); isRunning {\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\n\t\tif r == expectedReplicas {\n\t\t\treturn true, nil\n\t\t}\n\n\t\treturn false, nil\n\t})\n}", "func GetExpectedDaemonSet(t *testing.T, fileName string) *appsv1.DaemonSet {\n\tobj := getKubernetesObject(t, fileName)\n\tdaemonSet, ok := obj.(*appsv1.DaemonSet)\n\tassert.True(t, ok, \"Expected DaemonSet object\")\n\treturn daemonSet\n}", "func buildPrePullDaemonSet(component, image string) *apps.DaemonSet {\n\tvar gracePeriodSecs int64\n\treturn &apps.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: addPrepullPrefix(component),\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tSpec: apps.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: component,\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tCommand: []string{\"/bin/sleep\", \"3600\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\tconstants.LabelNodeRoleMaster: \"\",\n\t\t\t\t\t},\n\t\t\t\t\tTolerations: []v1.Toleration{constants.MasterToleration},\n\t\t\t\t\tTerminationGracePeriodSeconds: &gracePeriodSecs,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func waitManagerDeploymentsReady(ctx context.Context, opts InstallOptions, installQueue []repository.Components, proxy Proxy) error {\n\tfor _, components := range installQueue {\n\t\tfor _, obj := range components.Objs() {\n\t\t\tif util.IsDeploymentWithManager(obj) {\n\t\t\t\tif err := waitDeploymentReady(ctx, obj, opts.WaitProviderTimeout, proxy); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"deployment %q is not ready after %s\", obj.GetName(), opts.WaitProviderTimeout)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func nodeResolverDaemonSetConfigChanged(current, expected *appsv1.DaemonSet) (bool, *appsv1.DaemonSet) {\n\tchanged := false\n\tupdated := current.DeepCopy()\n\n\tif !cmp.Equal(current.Spec.UpdateStrategy, expected.Spec.UpdateStrategy, cmpopts.EquateEmpty()) {\n\t\tupdated.Spec.UpdateStrategy = expected.Spec.UpdateStrategy\n\t\tchanged = true\n\t}\n\n\tif len(current.Spec.Template.Spec.Containers) != len(expected.Spec.Template.Spec.Containers) {\n\t\tupdated.Spec.Template.Spec.Containers = expected.Spec.Template.Spec.Containers\n\t\tchanged = true\n\t} else if len(expected.Spec.Template.Spec.Containers) > 0 {\n\t\tcurCommand := current.Spec.Template.Spec.Containers[0].Command\n\t\texpCommand := expected.Spec.Template.Spec.Containers[0].Command\n\t\tif !cmp.Equal(curCommand, expCommand, cmpopts.EquateEmpty()) {\n\t\t\tupdated.Spec.Template.Spec.Containers[0].Command = expCommand\n\t\t\tchanged = true\n\t\t}\n\n\t\tcurImage := current.Spec.Template.Spec.Containers[0].Image\n\t\texpImage := expected.Spec.Template.Spec.Containers[0].Image\n\t\tif curImage != expImage {\n\t\t\tupdated.Spec.Template.Spec.Containers[0].Image = expImage\n\t\t\tchanged = true\n\t\t}\n\n\t\tcurEnv := current.Spec.Template.Spec.Containers[0].Env\n\t\texpEnv := expected.Spec.Template.Spec.Containers[0].Env\n\t\tif !cmp.Equal(curEnv, expEnv, cmpopts.EquateEmpty()) {\n\t\t\tupdated.Spec.Template.Spec.Containers[0].Env = expEnv\n\t\t\tchanged = true\n\t\t}\n\t}\n\tif !cmp.Equal(current.Spec.Template.Spec.NodeSelector, expected.Spec.Template.Spec.NodeSelector, cmpopts.EquateEmpty()) {\n\t\tupdated.Spec.Template.Spec.NodeSelector = expected.Spec.Template.Spec.NodeSelector\n\t\tchanged = true\n\t}\n\tif !cmp.Equal(current.Spec.Template.Spec.Tolerations, expected.Spec.Template.Spec.Tolerations, cmpopts.EquateEmpty(), cmpopts.SortSlices(cmpTolerations)) {\n\t\tupdated.Spec.Template.Spec.Tolerations = expected.Spec.Template.Spec.Tolerations\n\t\tchanged = true\n\t}\n\tif !cmp.Equal(current.Spec.Template.Spec.Volumes, expected.Spec.Template.Spec.Volumes, cmpopts.EquateEmpty(), cmp.Comparer(cmpConfigMapVolumeSource), cmp.Comparer(cmpSecretVolumeSource)) {\n\t\tupdated.Spec.Template.Spec.Volumes = expected.Spec.Template.Spec.Volumes\n\t\tchanged = true\n\t}\n\n\tif !changed {\n\t\treturn false, nil\n\t}\n\treturn true, updated\n}", "func waitForMachineSetToExist(capiClient capiclientset.Interface, namespace, name string) error {\n\treturn waitForMachineSetStatus(\n\t\tcapiClient,\n\t\tnamespace, name,\n\t\tfunc(machineSet *capiv1alpha1.MachineSet) bool { return machineSet != nil },\n\t)\n}", "func createDaemonSet(client k8sclient.Interface, module *protos.Module) error {\n\tdsConfig := createDaemonSetObject(module)\n\td, err := client.ExtensionsV1beta1().DaemonSets(defaultNS).Create(dsConfig)\n\tif err == nil {\n\t\tlog.Infof(\"Created DaemonSet %+v\", d)\n\t} else if errors.IsAlreadyExists(err) {\n\t\tlog.Infof(\"DaemonSet %+v already exists\", dsConfig)\n\t} else {\n\t\tlog.Errorf(\"Failed to create DaemonSet %+v with error: %v\", dsConfig, err)\n\t}\n\n\treturn err\n}", "func WaitForCleanup() error {\n\tctx := context.Background()\n\tcli, err := client.NewEnvClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar (\n\t\tinterval = time.NewTicker(1 * time.Second)\n\t\ttimeout = time.NewTimer(1 * time.Minute)\n\t)\n\n\tfor range interval.C {\n\t\tselect {\n\t\tcase <-timeout.C:\n\t\t\treturn errors.New(\"timed out waiting for all easycontainers containers to get removed\")\n\t\tdefault:\n\t\t\t// only grab the containers created by easycontainers\n\t\t\targs := filters.NewArgs()\n\t\t\targs.Add(\"name\", \"/\"+prefix)\n\n\t\t\tcontainers, err := cli.ContainerList(ctx, types.ContainerListOptions{\n\t\t\t\tFilters: args,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(containers) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Controller) waitStatefulSetGeneration(namespace, name string, targetGeneration int64) error {\n\t// Wait for some limited time for StatefulSet to reach target generation\n\t// Wait timeout is specified in c.chopConfig.StatefulSetUpdateTimeout in seconds\n\tstart := time.Now()\n\tfor {\n\t\tif statefulSet, err := c.statefulSetLister.StatefulSets(namespace).Get(name); err != nil {\n\t\t\t// Unable to get StatefulSet\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\t// Object with such name not found - may be is still being created - wait for it\n\t\t\t\tglog.V(1).Infof(\"waitStatefulSetGeneration() - object not yet created, wait for it\\n\")\n\t\t\t\ttime.Sleep(time.Duration(c.chopConfig.StatefulSetUpdatePollPeriod) * time.Second)\n\t\t\t} else {\n\t\t\t\t// Some kind of total error\n\t\t\t\tglog.V(1).Infof(\"ERROR waitStatefulSetGeneration(%s/%s) Get() FAILED\\n\", namespace, name)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if hasStatefulSetReachedGeneration(statefulSet, targetGeneration) {\n\t\t\t// StatefulSet is available and generation reached\n\t\t\t// All is good, job done, exit\n\t\t\tglog.V(1).Infof(\"waitStatefulSetGeneration(OK):%s\\n\", strStatefulSetStatus(&statefulSet.Status))\n\t\t\treturn nil\n\t\t} else if time.Since(start) < (time.Duration(c.chopConfig.StatefulSetUpdateTimeout) * time.Second) {\n\t\t\t// StatefulSet is available but generation is not yet reached\n\t\t\t// Wait some more time\n\t\t\tglog.V(1).Infof(\"waitStatefulSetGeneration():%s\\n\", strStatefulSetStatus(&statefulSet.Status))\n\t\t\ttime.Sleep(time.Duration(c.chopConfig.StatefulSetUpdatePollPeriod) * time.Second)\n\t\t} else {\n\t\t\t// StatefulSet is available but generation is not yet reached\n\t\t\t// Timeout reached\n\t\t\t// Failed, time to quit\n\t\t\tglog.V(1).Infof(\"ERROR waitStatefulSetGeneration(%s/%s) - TIMEOUT reached\\n\", namespace, name)\n\t\t\treturn errors.New(fmt.Sprintf(\"waitStatefulSetGeneration(%s/%s) - wait timeout\", namespace, name))\n\t\t}\n\t}\n\n\treturn errors.New(fmt.Sprintf(\"waitStatefulSetGeneration(%s/%s) - unknown position\", namespace, name))\n}", "func CreateDaemonSet(client kubernetes.Interface, daemonsetName string, namespace string) (*v1beta1.DaemonSet, error) {\n\tlogrus.Infof(\"Creating DaemonSet\")\n\tdaemonsetClient := client.ExtensionsV1beta1().DaemonSets(namespace)\n\tdaemonset, err := daemonsetClient.Create(GetDaemonSet(namespace, daemonsetName))\n\ttime.Sleep(10 * time.Second)\n\treturn daemonset, err\n}", "func inheritDaemonsetLabels(service *apistructs.Service, daemonset *appsv1.DaemonSet) error {\n\tif daemonset == nil {\n\t\treturn nil\n\t}\n\n\tif daemonset.Labels == nil {\n\t\tdaemonset.Labels = make(map[string]string)\n\t}\n\n\tif daemonset.Spec.Template.Labels == nil {\n\t\tdaemonset.Spec.Template.Labels = make(map[string]string)\n\t}\n\n\thasHostPath := serviceHasHostpath(service)\n\n\terr := setPodLabelsFromService(hasHostPath, service.Labels, daemonset.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\tfor lk, lv := range daemonset.Labels {\n\t\tif lk == apistructs.AlibabaECILabel && lv == \"true\" {\n\t\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: ECI not support daemonset, do not set lables %s='true' for daemonset\", daemonset.Name, daemonset.Namespace, lk)\n\t\t}\n\t}\n\n\terr = setPodLabelsFromService(hasHostPath, service.Labels, daemonset.Spec.Template.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.Labels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\terr = setPodLabelsFromService(hasHostPath, service.DeploymentLabels, daemonset.Spec.Template.Labels)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error in service.DeploymentLabels: for daemonset %v in namesapce %v with error: %v\\n\", daemonset.Name, daemonset.Namespace, err)\n\t}\n\n\tfor lk, lv := range daemonset.Spec.Template.Labels {\n\t\tif lk == apistructs.AlibabaECILabel && lv == \"true\" {\n\t\t\treturn errors.Errorf(\"error in service.DeploymentLabels: for daemonset %v in namesapce %v with error: ECI not support daemonset, do not set lables %s='true' for daemonset.\\n\", daemonset.Name, daemonset.Namespace, lk)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dsl *DaemonSetLock) GetDaemonSet(sleep, timeout time.Duration) (*v1.DaemonSet, error) {\n\tvar ds *v1.DaemonSet\n\tvar lastError error\n\terr := wait.PollImmediate(sleep, timeout, func() (bool, error) {\n\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\tdefer cancel()\n\t\tif ds, lastError = dsl.client.AppsV1().DaemonSets(dsl.namespace).Get(ctx, dsl.name, metav1.GetOptions{}); lastError != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Timed out trying to get daemonset %s in namespace %s: %v\", dsl.name, dsl.namespace, lastError)\n\t}\n\treturn ds, nil\n}", "func (s *Scheduler) CheckPodBelongDaemonset(taskgroupID string) bool {\n\tnamespace, name := types.GetRunAsAndAppIDbyTaskGroupID(taskgroupID)\n\tversion, err := s.store.GetVersion(namespace, name)\n\tif err != nil {\n\t\tblog.Errorf(\"Fetch taskgroup(%s) version(%s.%s) error %s\", taskgroupID, namespace, name, err.Error())\n\t\treturn false\n\t}\n\tif version == nil {\n\t\tblog.Errorf(\"Fetch taskgroup(%s) version(%s.%s) is empty\", taskgroupID, namespace, name)\n\t\treturn false\n\t}\n\n\tif version.Kind == commtype.BcsDataType_Daemonset {\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *EndToEndTest) WaitForServer() error {\n\tsuccess := false\n\ttried := 1\n\tfor ok := true; ok; ok = !success {\n\t\t_, _, err := e.Client.RepositoriesApi.ListRepositories(context.Background())\n\t\tif err == nil {\n\t\t\tsuccess = true\n\t\t} else {\n\t\t\ttried++\n\t\t\tif tried == waitRetries {\n\t\t\t\tlogs, err := exec.Command(\"docker\", \"logs\", e.GetPrimaryContainer()).CombinedOutput()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn errors.New(fmt.Sprintf(\"timeoed out waiting for server to start: %s\", logs))\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(waitTimeout) * time.Second)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *DockerRegistryServiceController) waitForDockerURLs(ready chan<- struct{}, stopCh <-chan struct{}) {\n\tdefer utilruntime.HandleCrash()\n\n\t// Wait for the stores to fill\n\tif !cache.WaitForCacheSync(stopCh, e.servicesSynced, e.secretsSynced) {\n\t\treturn\n\t}\n\n\t// after syncing, determine the current state and assume that we're up to date for it if you don't do this,\n\t// you'll get an initial storm as you mess with all the dockercfg secrets every time you startup\n\turls := e.getDockerRegistryLocations()\n\te.setRegistryURLs(urls...)\n\te.dockercfgController.SetDockerURLs(urls...)\n\tclose(e.dockerURLsInitialized)\n\tclose(ready)\n\n\treturn\n}", "func (m *Machine) WaitForExtendedStatefulSets(namespace string, labels string) error {\n\treturn wait.PollImmediate(m.PollInterval, m.PollTimeout, func() (bool, error) {\n\t\treturn m.ExtendedStatefulSetExists(namespace, labels)\n\t})\n}", "func updateDaemonSetEnvVars(ds *appsv1.DaemonSet, envs []corev1.EnvVar) {\n\tfor c, container := range ds.Spec.Template.Spec.Containers {\n\t\tlog.Debugf(\"add/replace env vars for daemonset (%s) container (%s)\", ds.Name, container.Name)\n\t\tfor _, env := range envs {\n\t\t\ti := findEnvVar(container.Env, env.Name)\n\t\t\tif i == -1 {\n\t\t\t\tlog.Debugf(\"add env var (name: '%s' value: '%s')\", env.Name, env.Value)\n\t\t\t\tds.Spec.Template.Spec.Containers[c].Env = append(ds.Spec.Template.Spec.Containers[c].Env, env)\n\t\t\t} else if container.Env[i].Value != env.Value {\n\t\t\t\tlog.Debugf(\"replace env var (name: '%s' value: '%s' -> '%s')\", env.Name, container.Env[i].Value, env.Value)\n\t\t\t\tds.Spec.Template.Spec.Containers[c].Env[i].Value = env.Value\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"no change for env var (name: '%s' value: '%s')\", env.Name, container.Env[i].Value)\n\t\t\t}\n\t\t}\n\t}\n}", "func createDaemonSetObject(cr *hostpathprovisionerv1alpha1.HostPathProvisioner, provisionerImage, namespace string) *appsv1.DaemonSet {\n\tvolumeType := corev1.HostPathDirectoryOrCreate\n\tlabels := map[string]string{\n\t\t\"k8s-app\": cr.Name,\n\t}\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"DaemonSet\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": cr.Name,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tServiceAccountName: cr.Name + \"-admin\",\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: cr.Name,\n\t\t\t\t\t\t\tImage: provisionerImage,\n\t\t\t\t\t\t\tImagePullPolicy: cr.Spec.ImagePullPolicy,\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"USE_NAMING_PREFIX\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.UseNamingPrefix,\n\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\t\tName: \"NODE_NAME\",\n\t\t\t\t\t\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\t\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\t\t\t\t\t\tFieldPath: \"spec.nodeName\",\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\t{\n\t\t\t\t\t\t\t\t\tName: \"PV_DIR\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"pv-volume\",\n\t\t\t\t\t\t\t\t\tMountPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTerminationMessagePath: \"/dev/termination-log\",\n\t\t\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"pv-volume\", // Has to match VolumeMounts in containers\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\tPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t\tType: &volumeType,\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 *Plugin) Monitor(kubeclient kubernetes.Interface, availableNodes []v1.Node, resultsCh chan<- *plugin.Result) {\n\tpodsReported := make(map[string]bool)\n\tpodsFound := make(map[string]bool, len(availableNodes))\n\tfor _, node := range availableNodes {\n\t\tpodsFound[node.Name] = false\n\t\tpodsReported[node.Name] = false\n\t}\n\n\tfor {\n\t\t// Sleep between each poll, which should give the DaemonSet\n\t\t// enough time to create pods\n\t\ttime.Sleep(10 * time.Second)\n\t\t// If we've cleaned up after ourselves, stop monitoring\n\t\tif p.cleanedUp {\n\t\t\tbreak\n\t\t}\n\n\t\t// If we don't have a daemonset created, retry next time. We\n\t\t// only send errors if we successfully see that an expected pod\n\t\t// is having issues.\n\t\tds, err := p.findDaemonSet(kubeclient)\n\t\tif err != nil {\n\t\t\terrlog.LogError(errors.Wrapf(err, \"could not find DaemonSet created by plugin %v, will retry\", p.GetName()))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find all the pods configured by this daemonset\n\t\tpods, err := kubeclient.CoreV1().Pods(p.Namespace).List(p.listOptions())\n\t\tif err != nil {\n\t\t\terrlog.LogError(errors.Wrapf(err, \"could not find pods created by plugin %v, will retry\", p.GetName()))\n\t\t\t// Likewise, if we can't query for pods, just retry next time.\n\t\t\tcontinue\n\t\t}\n\n\t\t// Cycle through each pod in this daemonset, reporting any failures.\n\t\tfor _, pod := range pods.Items {\n\t\t\tnodeName := pod.Spec.NodeName\n\t\t\t// We don't care about nodes we already saw\n\t\t\tif podsReported[nodeName] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpodsFound[nodeName] = true\n\n\t\t\t// Check if it's failing and submit the error result\n\t\t\tif isFailing, reason := utils.IsPodFailing(&pod); isFailing {\n\t\t\t\tpodsReported[nodeName] = true\n\n\t\t\t\tresultsCh <- utils.MakeErrorResult(p.GetResultType(), map[string]interface{}{\n\t\t\t\t\t\"error\": reason,\n\t\t\t\t\t\"pod\": pod,\n\t\t\t\t}, nodeName)\n\t\t\t}\n\t\t}\n\n\t\t// DaemonSets are a bit strange, if node taints are preventing\n\t\t// scheduling, pods won't even be created (unlike say Jobs,\n\t\t// which will create the pod and leave it in an unscheduled\n\t\t// state.) So take any nodes we didn't see pods on, and report\n\t\t// issues scheduling them.\n\t\tfor _, node := range availableNodes {\n\t\t\tif !podsFound[node.Name] && !podsReported[node.Name] {\n\t\t\t\tpodsReported[node.Name] = true\n\t\t\t\tresultsCh <- utils.MakeErrorResult(p.GetResultType(), map[string]interface{}{\n\t\t\t\t\t\"error\": fmt.Sprintf(\n\t\t\t\t\t\t\"No pod was scheduled on node %v within %v. Check tolerations for plugin %v\",\n\t\t\t\t\t\tnode.Name,\n\t\t\t\t\t\ttime.Now().Sub(ds.CreationTimestamp.Time),\n\t\t\t\t\t\tp.Name,\n\t\t\t\t\t),\n\t\t\t\t}, node.Name)\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *dockerWaiter) Wait(ctx context.Context, containerID string) error {\n\treturn d.retryWait(ctx, containerID, nil)\n}", "func (r *DaemonReconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) {\n\terr := r.cleanupOldObjects(ctx, request.Namespace)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tlvSets, lvs, tolerations, ownerRefs, nodeSelector, err := r.aggregateDeamonInfo(ctx, request)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tif len(lvSets.Items) < 1 && len(lvs.Items) < 1 {\n\t\treturn ctrl.Result{}, nil\n\t}\n\n\tconfigMap, opResult, err := r.reconcileProvisionerConfigMap(ctx, request, lvSets.Items, lvs.Items, ownerRefs)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t} else if opResult == controllerutil.OperationResultUpdated || opResult == controllerutil.OperationResultCreated {\n\t\tklog.InfoS(\"provisioner configmap\", \"configMap\", configMap.GetName(), \"result\", opResult)\n\t}\n\n\t// enable service and servicemonitor for diskmaker daemonset\n\tmetricsExportor := localmetrics.NewExporter(ctx, r.Client, common.DiskMakerServiceName, request.Namespace, common.DiskMakerMetricsServingCert,\n\t\townerRefs, DiskMakerName)\n\tif err := metricsExportor.EnableMetricsExporter(); err != nil {\n\t\tklog.ErrorS(err, \"failed to create service and servicemonitors for diskmaker daemonset\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tif err := localmetrics.CreateOrUpdateAlertRules(ctx, r.Client, request.Namespace, DiskMakerName, ownerRefs); err != nil {\n\t\tklog.ErrorS(err, \"failed to create alerting rules\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\tconfigMapDataHash := dataHash(configMap.Data)\n\n\tdiskMakerDSMutateFn := getDiskMakerDSMutateFn(request, tolerations, ownerRefs, nodeSelector, configMapDataHash)\n\tds, opResult, err := CreateOrUpdateDaemonset(ctx, r.Client, diskMakerDSMutateFn)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t} else if opResult == controllerutil.OperationResultUpdated || opResult == controllerutil.OperationResultCreated {\n\t\tklog.InfoS(\"daemonset changed\", \"dsName\", ds.GetName(), \"opResult\", opResult)\n\t}\n\n\treturn ctrl.Result{}, err\n}", "func createStafeulSetAndVerifyPVAndPodNodeAffinty(ctx context.Context, client clientset.Interface,\n\tnamespace string, parallelPodPolicy bool, replicas int32, nodeAffinityToSet bool,\n\tallowedTopologies []v1.TopologySelectorLabelRequirement, allowedTopologyLen int,\n\tpodAntiAffinityToSet bool, parallelStatefulSetCreation bool, modifyStsSpec bool,\n\tstsName string, accessMode v1.PersistentVolumeAccessMode,\n\tsc *storagev1.StorageClass, verifyTopologyAffinity bool) (*v1.Service, *appsv1.StatefulSet, error) {\n\n\tginkgo.By(\"Create service\")\n\tservice := CreateService(namespace, client)\n\n\tframework.Logf(\"Create StatefulSet\")\n\tstatefulset := createCustomisedStatefulSets(client, namespace, parallelPodPolicy,\n\t\treplicas, nodeAffinityToSet, allowedTopologies, allowedTopologyLen, podAntiAffinityToSet, modifyStsSpec,\n\t\t\"\", \"\", nil)\n\n\tif verifyTopologyAffinity {\n\t\tframework.Logf(\"Verify PV node affinity and that the PODS are running on appropriate node\")\n\t\terr := verifyPVnodeAffinityAndPODnodedetailsForStatefulsetsLevel5(ctx, client, statefulset,\n\t\t\tnamespace, allowedTopologies, parallelStatefulSetCreation, true)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error verifying PV node affinity and POD node details: %v\", err)\n\t\t}\n\t}\n\n\treturn service, statefulset, nil\n}", "func TestRollingUpdateDaemonSetExistingPodAdoption(t *testing.T) {\n\tserver, closeFn, dc, informers, clientset := setup(t)\n\tdefer closeFn()\n\n\ttearDownFn := setupGC(t, server)\n\tdefer tearDownFn()\n\n\tns := framework.CreateTestingNamespace(\"rolling-update-daemonset-existing-pod-adoption-test\", server, t)\n\tdefer framework.DeleteTestingNamespace(ns, server, t)\n\n\tdsClient := clientset.AppsV1().DaemonSets(ns.Name)\n\tpodClient := clientset.CoreV1().Pods(ns.Name)\n\tnodeClient := clientset.CoreV1().Nodes()\n\tpodInformer := informers.Core().V1().Pods().Informer()\n\tcontrollerRevisionClient := clientset.AppsV1().ControllerRevisions(ns.Name)\n\tstopCh := make(chan struct{})\n\tdefer close(stopCh)\n\tinformers.Start(stopCh)\n\tgo dc.Run(5, stopCh)\n\n\t// Step 1: create a RollingUpdate DaemonSet\n\tdsName := \"daemonset\"\n\tds := newDaemonSet(dsName, ns.Name)\n\tds.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds, err := dsClient.Create(ds)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName, err)\n\t}\n\n\tnodeName := \"single-node\"\n\tnode := newNode(nodeName, nil)\n\t_, err = nodeClient.Create(node)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create node %q: %v\", nodeName, err)\n\t}\n\n\t// Validate everything works correctly (include marking daemon pod as ready)\n\tvalidateDaemonSetPodsAndMarkReady(podClient, podInformer, 1, t)\n\tvalidateDaemonSetStatus(dsClient, ds.Name, ds.Namespace, 1, t)\n\n\t// Step 2: delete daemonset and orphan its pods\n\tdeleteDaemonSetAndOrphanPods(dsClient, podClient, controllerRevisionClient, podInformer, ds, t)\n\n\t// Step 3: create 2rd daemonset to adopt the pods (no restart) as long as template matches\n\tdsName2 := \"daemonset-adopt-template-matches\"\n\tds2 := newDaemonSet(dsName2, ns.Name)\n\tds2.Spec.UpdateStrategy = *newRollbackStrategy()\n\tds2, err = dsClient.Create(ds2)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create daemonset %q: %v\", dsName2, err)\n\t}\n\tif !apiequality.Semantic.DeepEqual(ds2.Spec.Template, ds.Spec.Template) {\n\t\tt.Fatalf(\".spec.template of new daemonset %q and old daemonset %q are not the same\", dsName2, dsName)\n\t}\n\n\t// Wait for pods and history to be adopted by 2nd daemonset\n\twaitDaemonSetAdoption(podClient, controllerRevisionClient, podInformer, ds2, ds.Name, t)\n\tvalidateDaemonSetStatus(dsClient, ds2.Name, ds2.Namespace, 1, t)\n}", "func WaitForWantedNodes(cfg cbgt.Cfg, wantedNodes []string,\n\tcancelCh <-chan struct{}, secs int, ignoreWaitTimeOut bool) (\n\t[]string, error) {\n\tvar nodeDefWantedUUIDs []string\n\tfor i := 0; i < secs; i++ {\n\t\tselect {\n\t\tcase <-cancelCh:\n\t\t\treturn nil, ErrCtlCanceled\n\t\tdefault:\n\t\t}\n\n\t\tnodeDefsWanted, _, err :=\n\t\t\tcbgt.CfgGetNodeDefs(cfg, cbgt.NODE_DEFS_WANTED)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnodeDefWantedUUIDs = nil\n\t\tfor _, nodeDef := range nodeDefsWanted.NodeDefs {\n\t\t\tnodeDefWantedUUIDs = append(nodeDefWantedUUIDs, nodeDef.UUID)\n\t\t}\n\t\tif len(cbgt.StringsRemoveStrings(wantedNodes, nodeDefWantedUUIDs)) <= 0 {\n\t\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\tif ignoreWaitTimeOut {\n\t\tlog.Printf(\"ctl: WaitForWantedNodes ignoreWaitTimeOut\")\n\t\treturn cbgt.StringsRemoveStrings(nodeDefWantedUUIDs, wantedNodes), nil\n\t}\n\treturn nil, fmt.Errorf(\"ctl: WaitForWantedNodes\"+\n\t\t\" could not attain wantedNodes: %#v,\"+\n\t\t\" only reached nodeDefWantedUUIDs: %#v\",\n\t\twantedNodes, nodeDefWantedUUIDs)\n}", "func DeleteDaemonSet(client kubernetes.Interface, namespace string, daemonsetName string) error {\n\tlogrus.Infof(\"Deleting DaemonSet %s\", daemonsetName)\n\tdaemonsetError := client.ExtensionsV1beta1().DaemonSets(namespace).Delete(daemonsetName, &metav1.DeleteOptions{})\n\ttime.Sleep(10 * time.Second)\n\treturn daemonsetError\n}", "func (c *client) WalkDaemonSets(f func(DaemonSet) error) error {\n\tif c.daemonSetStore == nil {\n\t\treturn nil\n\t}\n\tfor _, m := range c.daemonSetStore.List() {\n\t\tds := m.(*apiappsv1.DaemonSet)\n\t\tif err := f(NewDaemonSet(ds)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func daemonSetProgressing(ds *appsv1.DaemonSet, allowHung bool) bool {\n\tstatus := ds.Status\n\n\t// Copy-pasted from status_manager: Determine if a DaemonSet is progressing\n\tprogressing := (status.UpdatedNumberScheduled < status.DesiredNumberScheduled ||\n\t\tstatus.NumberUnavailable > 0 ||\n\t\tstatus.NumberAvailable == 0 ||\n\t\tds.Generation > status.ObservedGeneration)\n\n\ts := \"progressing\"\n\tif !progressing {\n\t\ts = \"complete\"\n\t}\n\tklog.V(2).Infof(\"daemonset %s/%s rollout %s; %d/%d scheduled; %d unavailable; %d available; generation %d -> %d\",\n\t\tds.Namespace, ds.Name, s, status.UpdatedNumberScheduled, status.DesiredNumberScheduled,\n\t\tstatus.NumberUnavailable, status.NumberAvailable, ds.Generation, status.ObservedGeneration)\n\n\tif !progressing {\n\t\tklog.V(2).Infof(\"daemonset %s/%s rollout complete\", ds.Namespace, ds.Name)\n\t\treturn false\n\t}\n\n\t// If we're hung, but max(90% of nodes, 1) have been updated, then act as if not progressing\n\tif allowHung {\n\t\t_, hung := ds.GetAnnotations()[names.RolloutHungAnnotation]\n\t\tmaxBehind := int(math.Max(1, math.Floor(float64(status.DesiredNumberScheduled)*0.1)))\n\t\tnumBehind := int(status.DesiredNumberScheduled - status.UpdatedNumberScheduled)\n\t\tif hung && numBehind <= maxBehind {\n\t\t\tklog.Warningf(\"daemonset %s/%s rollout seems to have hung with %d/%d behind, force-continuing\", ds.Namespace, ds.Name, numBehind, status.DesiredNumberScheduled)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (fmd *FakeMysqlDaemon) Wait(ctx context.Context, cnf *Mycnf) error {\n\treturn nil\n}", "func (r *reconciler) updateNodeResolverDaemonSet(current, desired *appsv1.DaemonSet) (bool, error) {\n\tchanged, updated := nodeResolverDaemonSetConfigChanged(current, desired)\n\tif !changed {\n\t\treturn false, nil\n\t}\n\n\tif err := r.client.Update(context.TODO(), updated); err != nil {\n\t\treturn false, fmt.Errorf(\"failed to update node resolver daemonset %s/%s: %v\", updated.Namespace, updated.Name, err)\n\t}\n\tlogrus.Infof(\"updated node resolver daemonset: %s/%s\", updated.Namespace, updated.Name)\n\treturn true, nil\n}", "func CreateOrUpdateDaemonSet(client clientset.Interface, ds *extensions.DaemonSet) error {\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Create(ds); err != nil {\n if !apierrors.IsAlreadyExists(err) {\n return fmt.Errorf(\"unable to create daemonset: %v\", err)\n }\n\n if _, err := client.ExtensionsV1beta1().DaemonSets(ds.ObjectMeta.Namespace).Update(ds); err != nil {\n return fmt.Errorf(\"unable to update daemonset: %v\", err)\n }\n }\n return nil\n}", "func (e *dockerExec) WaitUntil(min execState) error {\n\te.mu.Lock()\n\tfor e.State < min && e.err == nil {\n\t\te.cond.Wait()\n\t}\n\te.mu.Unlock()\n\treturn e.err\n}", "func (b *Botanist) WaitUntilContainerRuntimeResourcesReady(ctx context.Context) error {\n\tfns := []flow.TaskFn{}\n\n\tfor _, worker := range b.Shoot.Info.Spec.Provider.Workers {\n\t\tif worker.CRI != nil {\n\t\t\tfor _, containerRuntime := range worker.CRI.ContainerRuntimes {\n\t\t\t\tvar (\n\t\t\t\t\tname = getContainerRuntimeKey(containerRuntime.Type, worker.Name)\n\t\t\t\t\tnamespace = b.Shoot.SeedNamespace\n\t\t\t\t)\n\t\t\t\tfns = append(fns, func(ctx context.Context) error {\n\t\t\t\t\tif err := retry.UntilTimeout(ctx, DefaultInterval, shoot.ExtensionDefaultTimeout, func(ctx context.Context) (bool, error) {\n\t\t\t\t\t\treq := &extensionsv1alpha1.ContainerRuntime{}\n\t\t\t\t\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(namespace, name), req); err != nil {\n\t\t\t\t\t\t\treturn retry.SevereError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif err := health.CheckExtensionObject(req); err != nil {\n\t\t\t\t\t\t\tb.Logger.WithError(err).Errorf(\"Container runtime %s/%s did not get ready yet\", namespace, name)\n\t\t\t\t\t\t\treturn retry.MinorError(err)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn retry.Ok()\n\t\t\t\t\t}); err != nil {\n\t\t\t\t\t\treturn gardencorev1beta1helper.DetermineError(err, fmt.Sprintf(\"failed waiting for container runtime %s to be ready: %v\", name, err))\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn flow.ParallelExitOnError(fns...)(ctx)\n}", "func WaitForFederationApiserverReady(c *federation_clientset.Clientset) error {\n\treturn wait.PollImmediate(time.Second, 1*time.Minute, func() (bool, error) {\n\t\t_, err := c.Federation().Clusters().List(metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n}", "func MockDaemonSet() appsv1.DaemonSet {\n\tp := MockPod()\n\treturn appsv1.DaemonSet{\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n}", "func waitForConductor(ctx context.Context, client *gophercloud.ServiceClient) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[DEBUG] Waiting for conductor API to become available...\")\n\t\t\tdriverCount := 0\n\n\t\t\tdrivers.ListDrivers(client, drivers.ListDriversOpts{\n\t\t\t\tDetail: false,\n\t\t\t}).EachPage(func(page pagination.Page) (bool, error) {\n\t\t\t\tactual, err := drivers.ExtractDrivers(page)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tdriverCount += len(actual)\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\t// If we have any drivers, conductor is up.\n\t\t\tif driverCount > 0 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t}\n}", "func (c *client) WaitContainer(ctx context.Context, ctn *pipeline.Container) error {\n\tlogrus.Tracef(\"waiting for container %s\", ctn.ID)\n\n\t// create label selector for watching the pod\n\tselector := fmt.Sprintf(\"pipeline=%s\", c.pod.ObjectMeta.Name)\n\n\t// create options for watching the container\n\topts := metav1.ListOptions{\n\t\tLabelSelector: selector,\n\t\tWatch: true,\n\t}\n\n\t// send API call to capture channel for watching the container\n\t//\n\t// https://pkg.go.dev/k8s.io/client-go/kubernetes/typed/core/v1?tab=doc#PodInterface\n\t// ->\n\t// https://pkg.go.dev/k8s.io/apimachinery/pkg/watch?tab=doc#Interface\n\twatch, err := c.kubernetes.CoreV1().Pods(c.namespace).Watch(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\t// capture new result from the channel\n\t\t//\n\t\t// https://pkg.go.dev/k8s.io/apimachinery/pkg/watch?tab=doc#Interface\n\t\tresult := <-watch.ResultChan()\n\n\t\t// convert the object from the result to a pod\n\t\tpod, ok := result.Object.(*v1.Pod)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unable to watch pod %s\", c.pod.ObjectMeta.Name)\n\t\t}\n\n\t\t// check if the pod is in a pending state\n\t\t//\n\t\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#PodStatus\n\t\tif pod.Status.Phase == v1.PodPending {\n\t\t\t// skip pod if it's in a pending state\n\t\t\tcontinue\n\t\t}\n\n\t\t// iterate through each container in the pod\n\t\tfor _, cst := range pod.Status.ContainerStatuses {\n\t\t\t// check if the container has a matching ID\n\t\t\t//\n\t\t\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#ContainerStatus\n\t\t\tif !strings.EqualFold(cst.Name, ctn.ID) {\n\t\t\t\t// skip container if it's not a matching ID\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// check if the container is in a terminated state\n\t\t\t//\n\t\t\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#ContainerState\n\t\t\tif cst.State.Terminated == nil {\n\t\t\t\t// skip container if it's not in a terminated state\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// check if the container has a terminated state reason\n\t\t\t//\n\t\t\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#ContainerStateTerminated\n\t\t\tif len(cst.State.Terminated.Reason) > 0 {\n\t\t\t\t// break watching the container as it's complete\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n}", "func WaitForStatefulSetToBeUnready(t *testing.T, mdb *mdbv1.MongoDBCommunity, retryInterval, timeout time.Duration) error {\n\treturn waitForStatefulSetCondition(t, mdb, retryInterval, timeout, func(sts appsv1.StatefulSet) bool {\n\t\treturn !statefulset.IsReady(sts, mdb.Spec.Members)\n\t})\n}", "func TestWaitUntilAllNodesReady(t *testing.T) {\n\tt.Parallel()\n\n\toptions := NewKubectlOptions(\"\", \"\", \"default\")\n\n\tWaitUntilAllNodesReady(t, options, 12, 5*time.Second)\n\n\tnodes := GetNodes(t, options)\n\tnodeNames := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tnodeNames[node.Name] = true\n\t}\n\n\treadyNodes := GetReadyNodes(t, options)\n\treadyNodeNames := map[string]bool{}\n\tfor _, node := range readyNodes {\n\t\treadyNodeNames[node.Name] = true\n\t}\n\n\tassert.Equal(t, nodeNames, readyNodeNames)\n}", "func TestWaitForContainerTransitionsForTerminalTask(t *testing.T) {\n\tacsMessages := make(chan acsTransition)\n\tdockerMessages := make(chan dockerContainerChange)\n\tctx, cancel := context.WithCancel(context.TODO())\n\tdefer cancel()\n\ttask := &managedTask{\n\t\tacsMessages: acsMessages,\n\t\tdockerMessages: dockerMessages,\n\t\tTask: &apitask.Task{\n\t\t\tContainers: []*apicontainer.Container{},\n\t\t\tKnownStatusUnsafe: apitaskstatus.TaskStopped,\n\t\t},\n\t\tctx: ctx,\n\t}\n\n\ttransitionChange := make(chan struct{}, 2)\n\ttransitionChangeContainer := make(chan string, 2)\n\n\tfirstContainerName := \"container1\"\n\tsecondContainerName := \"container2\"\n\ttransitions := make(map[string]string)\n\ttransitions[firstContainerName] = apicontainerstatus.ContainerPulled.String()\n\ttransitions[secondContainerName] = apicontainerstatus.ContainerPulled.String()\n\n\t// Event though there are two keys in the transitions map, send\n\t// only one event. This tests that `waitForContainerTransition` doesn't\n\t// block to receive two events and will still progress\n\tgo func() {\n\t\ttransitionChange <- struct{}{}\n\t\ttransitionChangeContainer <- secondContainerName\n\t}()\n\ttask.waitForTransition(transitions, transitionChange, transitionChangeContainer)\n}", "func expectStatefulSetTLSConfig(t *testing.T, g *gomega.GomegaWithT, sc *solr.SolrCloud, needsPkcs12InitContainer bool) *appsv1.StatefulSet {\n\tctx := context.TODO()\n\tstateful := &appsv1.StatefulSet{}\n\tg.Eventually(func() error { return testClient.Get(ctx, expectedStatefulSetName, stateful) }, timeout).Should(gomega.Succeed())\n\tpodTemplate := &stateful.Spec.Template\n\texpectTLSConfigOnPodTemplate(t, sc.Spec.SolrTLS, podTemplate, needsPkcs12InitContainer)\n\n\t// Check HTTPS cluster prop setup container\n\tassert.NotNil(t, podTemplate.Spec.InitContainers)\n\tvar zkSetupInitContainer *corev1.Container = nil\n\tfor _, cnt := range podTemplate.Spec.InitContainers {\n\t\tif cnt.Name == \"setup-zk\" {\n\t\t\tzkSetupInitContainer = &cnt\n\t\t\tbreak\n\t\t}\n\t}\n\texpCmd := \"/opt/solr/server/scripts/cloud-scripts/zkcli.sh -zkhost ${ZK_HOST} -cmd clusterprop -name urlScheme -val https\"\n\tif sc.Spec.SolrTLS != nil {\n\t\tassert.NotNil(t, zkSetupInitContainer, \"Didn't find the zk-setup InitContainer in the sts!\")\n\t\tif zkSetupInitContainer != nil {\n\t\t\tassert.Equal(t, \"library/solr:7.7.0\", zkSetupInitContainer.Image)\n\t\t\tassert.Equal(t, 3, len(zkSetupInitContainer.Command), \"Wrong command length for zk-setup init container\")\n\t\t\tassert.Contains(t, zkSetupInitContainer.Command[2], expCmd, \"ZK Setup command does not set urlScheme\")\n\t\t\tassert.Equal(t, 3, len(zkSetupInitContainer.Env), \"Wrong number of envVars for zk-setup init container\")\n\t\t}\n\t} else {\n\t\tassert.Nil(t, zkSetupInitContainer, \"Shouldn't find the zk-setup InitContainer in the sts, when not using https!\")\n\t}\n\treturn stateful\n}", "func CreateDaemonSet(name string) *appsv1.DaemonSet {\n\tmaxUnavailable := intstr.FromInt(1)\n\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: genTypeMeta(gvk.DaemonSet),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tRevisionHistoryLimit: conversion.PtrInt32(10),\n\t\t\tUpdateStrategy: appsv1.DaemonSetUpdateStrategy{\n\t\t\t\tRollingUpdate: &appsv1.RollingUpdateDaemonSet{\n\t\t\t\t\tMaxUnavailable: &maxUnavailable,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tStatus: appsv1.DaemonSetStatus{\n\t\t\tCurrentNumberScheduled: 1,\n\t\t\tDesiredNumberScheduled: 1,\n\t\t\tNumberAvailable: 1,\n\t\t\tNumberReady: 1,\n\t\t\tUpdatedNumberScheduled: 1,\n\t\t},\n\t}\n}", "func WaitForStatefulSetToExist(stsName string, retryInterval, timeout time.Duration, namespace string) (appsv1.StatefulSet, error) {\n\tsts := appsv1.StatefulSet{}\n\treturn sts, waitForRuntimeObjectToExist(stsName, retryInterval, timeout, &sts, namespace)\n}", "func WaitForResources(objects object.K8sObjects, opts *kubectlcmd.Options) error {\n\tif opts.DryRun {\n\t\tlogAndPrint(\"Not waiting for resources ready in dry run mode.\")\n\t\treturn nil\n\t}\n\n\tcs, err := kubernetes.NewForConfig(k8sRESTConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"k8s client error: %s\", err)\n\t}\n\n\terrPoll := wait.Poll(2*time.Second, opts.WaitTimeout, func() (bool, error) {\n\t\tpods := []v1.Pod{}\n\t\tservices := []v1.Service{}\n\t\tdeployments := []deployment{}\n\t\tnamespaces := []v1.Namespace{}\n\n\t\tfor _, o := range objects {\n\t\t\tkind := o.GroupVersionKind().Kind\n\t\t\tswitch kind {\n\t\t\tcase \"Namespace\":\n\t\t\t\tnamespace, err := cs.CoreV1().Namespaces().Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnamespaces = append(namespaces, *namespace)\n\t\t\tcase \"Pod\":\n\t\t\t\tpod, err := cs.CoreV1().Pods(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, *pod)\n\t\t\tcase \"ReplicationController\":\n\t\t\t\trc, err := cs.CoreV1().ReplicationControllers(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rc.Namespace, rc.Spec.Selector)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Deployment\":\n\t\t\t\tcurrentDeployment, err := cs.AppsV1().Deployments(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\t_, _, newReplicaSet, err := kubectlutil.GetAllReplicaSets(currentDeployment, cs.AppsV1())\n\t\t\t\tif err != nil || newReplicaSet == nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tnewDeployment := deployment{\n\t\t\t\t\tnewReplicaSet,\n\t\t\t\t\tcurrentDeployment,\n\t\t\t\t}\n\t\t\t\tdeployments = append(deployments, newDeployment)\n\t\t\tcase \"DaemonSet\":\n\t\t\t\tds, err := cs.AppsV1().DaemonSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, ds.Namespace, ds.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"StatefulSet\":\n\t\t\t\tsts, err := cs.AppsV1().StatefulSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, sts.Namespace, sts.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"ReplicaSet\":\n\t\t\t\trs, err := cs.AppsV1().ReplicaSets(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tlist, err := getPods(cs, rs.Namespace, rs.Spec.Selector.MatchLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tpods = append(pods, list...)\n\t\t\tcase \"Service\":\n\t\t\t\tsvc, err := cs.CoreV1().Services(o.Namespace).Get(o.Name, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tservices = append(services, *svc)\n\t\t\t}\n\t\t}\n\t\tisReady := namespacesReady(namespaces) && podsReady(pods) && deploymentsReady(deployments) && servicesReady(services)\n\t\tif !isReady {\n\t\t\tlogAndPrint(\"Waiting for resources ready with timeout of %v\", opts.WaitTimeout)\n\t\t}\n\t\treturn isReady, nil\n\t})\n\n\tif errPoll != nil {\n\t\tlogAndPrint(\"Failed to wait for resources ready: %v\", errPoll)\n\t\treturn fmt.Errorf(\"failed to wait for resources ready: %s\", errPoll)\n\t}\n\treturn nil\n}", "func (r *DaemonSetReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\treqNamespace := req.NamespacedName.Namespace\n\tif reqNamespace != KubeNs && reqNamespace != ControllerNs {\n\t\tr.Log.WithValues(\"daemonset\", req.NamespacedName)\n\t\tdaemonsets := &appsv1.DaemonSet{}\n\t\terr := r.Get(context.TODO(), req.NamespacedName, daemonsets)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\t\tif isDaemonSetReady(daemonsets) {\n\t\t\tcontainers := daemonsets.Spec.Template.Spec.Containers\n\t\t\tfor i, c := range containers {\n\t\t\t\tif isImagePresent(c.Image) {\n\t\t\t\t\tvar msg string\n\t\t\t\t\tmsg = fmt.Sprintf(\"Retagging image %s of daemonset: %s\", c.Image, daemonsets.Name)\n\t\t\t\t\tsetupLog.Info(msg)\n\t\t\t\t\timg, err := images.Process(c.Image)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tmsg = fmt.Sprintf(\"Failed to process image: %s\", img)\n\t\t\t\t\t\tsetupLog.Error(err, msg)\n\t\t\t\t\t\treturn reconcile.Result{}, err\n\t\t\t\t\t}\n\t\t\t\t\t// update image\n\t\t\t\t\tmsg = fmt.Sprintf(\"Updating image %s of daemonset: %s\", c.Image, daemonsets.Name)\n\t\t\t\t\tsetupLog.Info(msg)\n\t\t\t\t\tdaemonsets.Spec.Template.Spec.Containers[i].Image = img\n\t\t\t\t\terr = r.Update(context.TODO(), daemonsets)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn reconcile.Result{}, err\n\t\t\t\t\t}\n\t\t\t\t\tmsg = fmt.Sprintf(\"Updated image: %s -> %s\", c.Image, img)\n\t\t\t\t\tsetupLog.Info(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn reconcile.Result{}, nil\n}", "func (a *MemberAwaitility) WaitForNSTmplSet(name string, criteria ...NSTemplateSetWaitCriterion) (*toolchainv1alpha1.NSTemplateSet, error) {\n\tvar nsTmplSet *toolchainv1alpha1.NSTemplateSet\n\terr := wait.Poll(a.RetryInterval, a.Timeout, func() (done bool, err error) {\n\t\tobj := &toolchainv1alpha1.NSTemplateSet{}\n\t\tif err := a.Client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: a.Namespace}, obj); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\ta.T.Logf(\"waiting for availability of NSTemplateSet '%s'\", name)\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, match := range criteria {\n\t\t\tif !match(a, obj) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\ta.T.Logf(\"found NSTemplateSet '%s'\", name)\n\t\tnsTmplSet = obj\n\t\treturn true, nil\n\t})\n\treturn nsTmplSet, err\n}", "func waitForCRDs(s *state.State) error {\n\tcondFn := clientutil.CRDsReadyCondition(s.Context, s.DynamicClient, CRDNames())\n\terr := wait.PollUntilContextTimeout(s.Context, 5*time.Second, 3*time.Minute, false, condFn.WithContext())\n\n\treturn fail.KubeClient(err, \"waiting for machine-controller CRDs to became ready\")\n}", "func (d *dockerWaiter) wait(ctx context.Context, containerID string, stopFn func()) error {\n\tstatusCh, errCh := d.client.ContainerWait(ctx, containerID, container.WaitConditionNotRunning)\n\n\tif stopFn != nil {\n\t\tstopFn()\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(time.Second):\n\t\t\tif stopFn != nil {\n\t\t\t\tstopFn()\n\t\t\t}\n\n\t\tcase err := <-errCh:\n\t\t\treturn err\n\n\t\tcase status := <-statusCh:\n\t\t\tif status.StatusCode != 0 {\n\t\t\t\treturn &common.BuildError{\n\t\t\t\t\tInner: fmt.Errorf(\"exit code %d\", status.StatusCode),\n\t\t\t\t\tExitCode: int(status.StatusCode),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (e *dockerExec) Wait(ctx context.Context) error {\n\treturn e.WaitUntil(execComplete)\n}", "func TestContainerStartOnDaemonRestart(t *testing.T) {\n\tskip.If(t, testEnv.IsRemoteDaemon, \"cannot start daemon on remote test run\")\n\tskip.If(t, testEnv.DaemonInfo.OSType == \"windows\")\n\tskip.If(t, testEnv.IsRootless)\n\tt.Parallel()\n\n\td := daemon.New(t)\n\td.StartWithBusybox(t, \"--iptables=false\")\n\tdefer d.Stop(t)\n\n\tc := d.NewClientT(t)\n\n\tctx := context.Background()\n\n\tcID := container.Create(ctx, t, c)\n\tdefer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})\n\n\terr := c.ContainerStart(ctx, cID, types.ContainerStartOptions{})\n\tassert.Check(t, err, \"error starting test container\")\n\n\tinspect, err := c.ContainerInspect(ctx, cID)\n\tassert.Check(t, err, \"error getting inspect data\")\n\n\tppid := getContainerdShimPid(t, inspect)\n\n\terr = d.Kill()\n\tassert.Check(t, err, \"failed to kill test daemon\")\n\n\terr = unix.Kill(inspect.State.Pid, unix.SIGKILL)\n\tassert.Check(t, err, \"failed to kill container process\")\n\n\terr = unix.Kill(ppid, unix.SIGKILL)\n\tassert.Check(t, err, \"failed to kill containerd-shim\")\n\n\td.Start(t, \"--iptables=false\")\n\n\terr = c.ContainerStart(ctx, cID, types.ContainerStartOptions{})\n\tassert.Check(t, err, \"failed to start test container\")\n}", "func (client *Client) WaitForContainerSourcesReady() error {\n\tnamespace := client.Namespace\n\tcontainerSources, err := client.Eventing.SourcesV1alpha1().ContainerSources(namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, containerSource := range containerSources.Items {\n\t\tif err := client.WaitForContainerSourceReady(containerSource.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ValidateDaemonSetSpec(spec, oldSpec *apps.DaemonSetSpec, fldPath *field.Path, opts apivalidation.PodValidationOptions) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tlabelSelectorValidationOpts := unversionedvalidation.LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: opts.AllowInvalidLabelValueInSelector}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelSelector(spec.Selector, labelSelectorValidationOpts, fldPath.Child(\"selector\"))...)\n\n\tselector, err := metav1.LabelSelectorAsSelector(spec.Selector)\n\tif err == nil && !selector.Matches(labels.Set(spec.Template.Labels)) {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"template\", \"metadata\", \"labels\"), spec.Template.Labels, \"`selector` does not match template `labels`\"))\n\t}\n\tif spec.Selector != nil && len(spec.Selector.MatchLabels)+len(spec.Selector.MatchExpressions) == 0 {\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"selector\"), spec.Selector, \"empty selector is invalid for daemonset\"))\n\t}\n\n\tallErrs = append(allErrs, apivalidation.ValidatePodTemplateSpec(&spec.Template, fldPath.Child(\"template\"), opts)...)\n\t// get rid of apivalidation.ValidateReadOnlyPersistentDisks,stop passing oldSpec to this function\n\tvar oldVols []api.Volume\n\tif oldSpec != nil {\n\t\toldVols = oldSpec.Template.Spec.Volumes // +k8s:verify-mutation:reason=clone\n\t}\n\tallErrs = append(allErrs, apivalidation.ValidateReadOnlyPersistentDisks(spec.Template.Spec.Volumes, oldVols, fldPath.Child(\"template\", \"spec\", \"volumes\"))...)\n\t// RestartPolicy has already been first-order validated as per ValidatePodTemplateSpec().\n\tif spec.Template.Spec.RestartPolicy != api.RestartPolicyAlways {\n\t\tallErrs = append(allErrs, field.NotSupported(fldPath.Child(\"template\", \"spec\", \"restartPolicy\"), spec.Template.Spec.RestartPolicy, []string{string(api.RestartPolicyAlways)}))\n\t}\n\tif spec.Template.Spec.ActiveDeadlineSeconds != nil {\n\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"template\", \"spec\", \"activeDeadlineSeconds\"), \"activeDeadlineSeconds in DaemonSet is not Supported\"))\n\t}\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.MinReadySeconds), fldPath.Child(\"minReadySeconds\"))...)\n\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(spec.TemplateGeneration), fldPath.Child(\"templateGeneration\"))...)\n\n\tallErrs = append(allErrs, ValidateDaemonSetUpdateStrategy(&spec.UpdateStrategy, fldPath.Child(\"updateStrategy\"))...)\n\tif spec.RevisionHistoryLimit != nil {\n\t\t// zero is a valid RevisionHistoryLimit\n\t\tallErrs = append(allErrs, apivalidation.ValidateNonnegativeField(int64(*spec.RevisionHistoryLimit), fldPath.Child(\"revisionHistoryLimit\"))...)\n\t}\n\treturn allErrs\n}", "func (r *marathonClient) WaitOnGroup(name string, timeout time.Duration) error {\n\terr := deadline(timeout, func(stop_channel chan bool) error {\n\t\tvar flick atomicSwitch\n\t\tgo func() {\n\t\t\t<-stop_channel\n\t\t\tclose(stop_channel)\n\t\t\tflick.SwitchOn()\n\t\t}()\n\t\tfor !flick.IsSwitched() {\n\t\t\tif group, err := r.Group(name); err != nil {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tallRunning := true\n\t\t\t\t// for each of the application, check if the tasks and running\n\t\t\t\tfor _, appID := range group.Apps {\n\t\t\t\t\t// Arrrgghhh!! .. so we can't use application instances from the Application struct like with app wait on as it\n\t\t\t\t\t// appears the instance count is not set straight away!! .. it defaults to zero and changes probably at the\n\t\t\t\t\t// dependencies gets deployed. Which is probably how it internally handles dependencies ..\n\t\t\t\t\t// step: grab the application\n\t\t\t\t\tapplication, err := r.Application(appID.ID)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tallRunning = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif application.Tasks == nil {\n\t\t\t\t\t\tallRunning = false\n\t\t\t\t\t} else if len(application.Tasks) != *appID.Instances {\n\t\t\t\t\t\tallRunning = false\n\t\t\t\t\t} else if application.TasksRunning != *appID.Instances {\n\t\t\t\t\t\tallRunning = false\n\t\t\t\t\t} else if len(application.DeploymentIDs()) > 0 {\n\t\t\t\t\t\tallRunning = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// has anyone toggle the flag?\n\t\t\t\tif allRunning {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(r.config.PollingWaitTime)\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func (b *Botanist) WaitUntilClusterAutoscalerDeleted(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, 600*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameClusterAutoscaler), &appsv1.Deployment{}); err != nil {\n\t\t\tif apierrors.IsNotFound(err) {\n\t\t\t\treturn retry.Ok()\n\t\t\t}\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\t\tb.Logger.Infof(\"Waiting until the %s has been deleted in the Seed cluster...\", v1beta1constants.DeploymentNameClusterAutoscaler)\n\t\treturn retry.MinorError(fmt.Errorf(\"deployment %q is still present\", v1beta1constants.DeploymentNameClusterAutoscaler))\n\t})\n}", "func (r *DaemonReconciler) cleanupOldDaemonsets(ctx context.Context, namespace string) error {\n\tif r.deletedStaticProvisioner {\n\t\treturn nil\n\t}\n\n\t// search for old localvolume daemons\n\tdsList := &appsv1.DaemonSetList{}\n\terr := r.Client.List(ctx, dsList, client.InNamespace(namespace))\n\tif err != nil {\n\t\tklog.ErrorS(err, \"could not list daemonsets\")\n\t\treturn err\n\t}\n\tappNameList := make([]string, 0)\n\tfor _, ds := range dsList.Items {\n\t\tappLabel, found := ds.ObjectMeta.Labels[appLabelKey]\n\t\tif !found {\n\t\t\tcontinue\n\t\t} else if strings.HasPrefix(appLabel, oldLVDiskMakerPrefix) || strings.HasPrefix(appLabel, oldLVProvisionerPrefix) {\n\t\t\t// remember name to watch for pods to delete\n\t\t\tappNameList = append(appNameList, appLabel)\n\t\t\t// delete daemonset\n\t\t\terr = r.Client.Delete(ctx, &ds)\n\t\t\tif err != nil && !(errors.IsNotFound(err) || errors.IsGone(err)) {\n\t\t\t\tklog.ErrorS(err, \"could not delete daemonset\", \"dsName\", ds.Name)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// search for old localvolumeset daemons\n\tprovisioner := &appsv1.DaemonSet{}\n\terr = r.Client.Get(ctx, types.NamespacedName{Name: oldProvisionerName, Namespace: namespace}, provisioner)\n\tif err == nil { // provisioner daemonset found\n\t\tklog.InfoS(\"old daemonset found, cleaning up\", \"oldProvisionerName\", oldProvisionerName)\n\t\terr = r.Client.Delete(ctx, provisioner)\n\t\tif err != nil && !(errors.IsNotFound(err) || errors.IsGone(err)) {\n\t\t\tklog.ErrorS(err, \"could not delete daemonset\", \"oldProvisionerName\", oldProvisionerName)\n\t\t\treturn err\n\t\t}\n\t} else if !(errors.IsNotFound(err) || errors.IsGone(err)) { // unknown error\n\t\tklog.ErrorS(err, \"could not fetch daemonset to clean it up\", \"oldProvisionerName\", oldProvisionerName)\n\t\treturn err\n\t}\n\n\t// wait for pods to die\n\terr = wait.ExponentialBackoff(wait.Backoff{\n\t\tCap: time.Minute * 2,\n\t\tDuration: time.Second,\n\t\tFactor: 1.7,\n\t\tJitter: 1,\n\t\tSteps: 20,\n\t}, func() (done bool, err error) {\n\t\tpodList := &corev1.PodList{}\n\t\tallGone := false\n\t\t// search for any pods with label 'app' in appNameList\n\t\tappNameList = append(appNameList, oldProvisionerName)\n\t\trequirement, err := labels.NewRequirement(appLabelKey, selection.In, appNameList)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"failed to compose labelselector requirement\",\n\t\t\t\t\"appLabelKey\", appLabelKey, \"appNameList\", appNameList)\n\t\t\treturn false, err\n\t\t}\n\t\tselector := labels.NewSelector().Add(*requirement)\n\t\terr = r.Client.List(context.TODO(), podList, client.MatchingLabelsSelector{Selector: selector})\n\t\tif err != nil && !errors.IsNotFound(err) {\n\t\t\treturn false, err\n\t\t} else if len(podList.Items) == 0 {\n\t\t\tallGone = true\n\t\t}\n\t\tklog.Infof(\"waiting for 0 pods with app label %q, found = %v\",\n\t\t\toldProvisionerName, len(podList.Items))\n\t\treturn allGone, nil\n\t})\n\tif err != nil {\n\t\tklog.ErrorS(err, \"could not determine that old provisioner pods were deleted\")\n\t\treturn err\n\t}\n\tr.deletedStaticProvisioner = true\n\treturn nil\n}", "func (b *Botanist) WaitUntilEtcdReady(ctx context.Context) error {\n\tvar (\n\t\tretryCountUntilSevere int\n\t\tinterval = 5 * time.Second\n\t\tsevereThreshold = 30 * time.Second\n\t\ttimeout = 5 * time.Minute\n\t)\n\n\treturn retry.UntilTimeout(ctx, interval, timeout, func(ctx context.Context) (done bool, err error) {\n\t\tretryCountUntilSevere++\n\n\t\tetcdList := &druidv1alpha1.EtcdList{}\n\t\tif err := b.K8sSeedClient.DirectClient().List(ctx, etcdList,\n\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\tclient.MatchingLabels{\"garden.sapcloud.io/role\": \"controlplane\"},\n\t\t); err != nil {\n\t\t\treturn retry.SevereError(err)\n\t\t}\n\n\t\tif n := len(etcdList.Items); n < 2 {\n\t\t\tb.Logger.Info(\"Waiting until the etcd gets created...\")\n\t\t\treturn retry.MinorError(fmt.Errorf(\"only %d/%d etcd resources found\", n, 2))\n\t\t}\n\n\t\tvar lastErrors error\n\n\t\tfor _, etcd := range etcdList.Items {\n\t\t\tswitch {\n\t\t\tcase etcd.Status.LastError != nil:\n\t\t\t\treturn retry.MinorOrSevereError(retryCountUntilSevere, int(severeThreshold.Nanoseconds()/interval.Nanoseconds()), fmt.Errorf(\"%s reconciliation errored: %s\", etcd.Name, *etcd.Status.LastError))\n\t\t\tcase etcd.DeletionTimestamp != nil:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s unexpectedly has a deletion timestamp\", etcd.Name))\n\t\t\tcase etcd.Status.ObservedGeneration == nil || etcd.Generation != *etcd.Status.ObservedGeneration:\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation pending\", etcd.Name))\n\t\t\tcase metav1.HasAnnotation(etcd.ObjectMeta, v1beta1constants.GardenerOperation):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s reconciliation in process\", etcd.Name))\n\t\t\tcase !utils.IsTrue(etcd.Status.Ready):\n\t\t\t\tlastErrors = multierror.Append(lastErrors, fmt.Errorf(\"%s is not ready yet\", etcd.Name))\n\t\t\t}\n\t\t}\n\n\t\tif lastErrors == nil {\n\t\t\treturn retry.Ok()\n\t\t}\n\n\t\tb.Logger.Info(\"Waiting until the both etcds are ready...\")\n\t\treturn retry.MinorError(lastErrors)\n\t})\n}", "func (c *Client) DaemonSetsCleaner(namespace string, dryRun bool, directories []string) error {\n\tvar left []string\n\n\tclusterDaemonsets, err := c.ListDaemonSets(namespace)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tfor _, value := range clusterDaemonsets.Items {\n\t\tleft = append(left, value.Name)\n\t}\n\n\tobjectsToDelete := Except(left, \"DaemonSet\", directories)\n\n\tfor _, item := range objectsToDelete {\n\t\tfor _, daemonset := range clusterDaemonsets.Items {\n\t\t\tif item == daemonset.Name {\n\t\t\t\tif dryRun {\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t\tcolor.Yellow(\" Deleting DaemonSet %s [dry-run]\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Yellow(\"******************************************************************************\")\n\t\t\t\t} else {\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tcolor.Red(\" Deleting DaemonSet %s\\n\", daemonset.Name)\n\t\t\t\t\tcolor.Red(\"******************************************************************************\")\n\t\t\t\t\tif err := c.DeleteDaemonSet(daemonset); err != nil {\n\t\t\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func UpdateDaemonSetEnvVars(ctx context.Context, f *framework.Framework, ns *corev1.Namespace, ds *appsv1.DaemonSet, envs []corev1.EnvVar) {\n\tvar err error\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tds, err = f.ClientSet.AppsV1().DaemonSets(ns.Name).Get(ctx, ds.Name, metav1.GetOptions{})\n\tcancel()\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\tupdateDaemonSetEnvVars(ds, envs)\n\n\t// Update daemonset\n\tresource := &resources.Resources{\n\t\tDaemonset: ds,\n\t}\n\tresource.ExpectDaemonsetUpdateSuccessful(ctx, f, ns)\n}", "func WaitFabricReady(ctx context.Context, log logging.Logger, params WaitFabricReadyParams) error {\n\tif common.InterfaceIsNil(params.StateProvider) {\n\t\treturn errors.New(\"nil NetDevStateProvider\")\n\t}\n\n\tif len(params.FabricIfaces) == 0 {\n\t\treturn errors.New(\"no fabric interfaces requested\")\n\t}\n\n\tparams.FabricIfaces = common.DedupeStringSlice(params.FabricIfaces)\n\n\tch := make(chan error)\n\tgo loopFabricReady(log, params, ch)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-ch:\n\t\treturn err\n\t}\n}", "func (r *reconciler) createLogsDaemonSet(\n\tctx context.Context,\n\tl log.Logger,\n\td config.Deployment,\n\ts assets.SecretStore,\n) error {\n\tname := fmt.Sprintf(\"%s-logs\", d.Agent.Name)\n\tds, err := generateLogsDaemonSet(r.config, name, d)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate DaemonSet: %w\", err)\n\t}\n\tkey := types.NamespacedName{Namespace: ds.Namespace, Name: ds.Name}\n\n\tif len(d.Logs) == 0 {\n\n\t\tvar ds apps_v1.DaemonSet\n\t\terr := r.Client.Get(ctx, key, &ds)\n\t\tif k8s_errors.IsNotFound(err) || !isManagedResource(&ds) {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn fmt.Errorf(\"failed to find stale DaemonSet %s: %w\", key, err)\n\t\t}\n\n\t\terr = r.Client.Delete(ctx, &ds)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete stale DaemonSet %s: %w\", key, err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlevel.Info(l).Log(\"msg\", \"reconciling logs daemonset\", \"ds\", key)\n\terr = clientutil.CreateOrUpdateDaemonSet(ctx, r.Client, ds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to reconcile statefulset governing service: %w\", err)\n\t}\n\treturn nil\n}", "func CommonDaemonSets(controllersCount int, selfHostedKubeletDisabled bool) []Workload {\n\tbase := []Workload{\n\t\t{\n\t\t\tName: \"calico-node\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"pod-checkpointer\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-proxy\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t}\n\n\tif !selfHostedKubeletDisabled {\n\t\tbase = append(base, Workload{\n\t\t\tName: \"kubelet\",\n\t\t\tNamespace: \"kube-system\",\n\t\t})\n\t}\n\n\tif controllersCount == 1 {\n\t\treturn base\n\t}\n\n\treturn append(base, []Workload{\n\t\t{\n\t\t\tName: \"kube-apiserver\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"coredns\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-controller-manager\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t{\n\t\t\tName: \"kube-scheduler\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t}...)\n}", "func (c *containerAdapter) waitClusterVolumes(ctx context.Context) error {\n\tfor _, attached := range c.container.task.Volumes {\n\t\t// for every attachment, try until we succeed or until the context\n\t\t// is canceled.\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tdefault:\n\t\t\t\t// continue through the code.\n\t\t\t}\n\t\t\tpath, err := c.dependencies.Volumes().Get(attached.ID)\n\t\t\tif err == nil && path != \"\" {\n\t\t\t\t// break out of the inner-most loop\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tswarmlog.G(ctx).Debug(\"volumes ready\")\n\treturn nil\n}", "func (c *gcsCore) WaitContainer(id string) (func() prot.NotificationType, error) {\n\tc.containerCacheMutex.Lock()\n\tentry := c.getContainer(id)\n\tif entry == nil {\n\t\tc.containerCacheMutex.Unlock()\n\t\treturn nil, gcserr.NewHresultError(gcserr.HrVmcomputeSystemNotFound)\n\t}\n\tc.containerCacheMutex.Unlock()\n\n\tf := func() prot.NotificationType {\n\t\tlogrus.Debugf(\"gcscore::WaitContainer waiting on init process waitgroup\")\n\t\tentry.initProcess.writersWg.Wait()\n\t\tlogrus.Debugf(\"gcscore::WaitContainer init process waitgroup count has dropped to zero\")\n\t\t// v1 only supported unexpected exit\n\t\treturn prot.NtUnexpectedExit\n\t}\n\n\treturn f, nil\n}", "func (s) TestDiamondDependency(t *testing.T) {\n\tch, fakeClient := setupTests()\n\tch.updateRootCluster(\"clusterA\")\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\t_, err := fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeAggregate,\n\t\tClusterName: \"clusterA\",\n\t\tPrioritizedClusterNames: []string{\"clusterB\", \"clusterC\"},\n\t}, nil)\n\t// Two watches should be started for both child clusters.\n\t_, err = fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\t_, err = fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\t// B -> D.\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeAggregate,\n\t\tClusterName: \"clusterB\",\n\t\tPrioritizedClusterNames: []string{\"clusterD\"},\n\t}, nil)\n\t_, err = fakeClient.WaitForWatchCluster(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"xdsClient.WatchCDS failed with error: %v\", err)\n\t}\n\n\t// This shouldn't cause an update to be written to the update buffer,\n\t// as cluster C has not received a cluster update yet.\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\tClusterName: \"clusterD\",\n\t}, nil)\n\n\tsCtx, cancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)\n\tdefer cancel()\n\tselect {\n\tcase <-ch.updateChannel:\n\t\tt.Fatal(\"an update should not have been written to the update buffer\")\n\tcase <-sCtx.Done():\n\t}\n\n\t// This update for C should cause an update to be written to the update\n\t// buffer. When you search this aggregated cluster graph, each node has\n\t// received an update. This update should only contain one clusterD, as\n\t// clusterC does not add a clusterD child update due to the clusterD update\n\t// already having been added as a child of clusterB.\n\tfakeClient.InvokeWatchClusterCallback(xdsresource.ClusterUpdate{\n\t\tClusterType: xdsresource.ClusterTypeAggregate,\n\t\tClusterName: \"clusterC\",\n\t\tPrioritizedClusterNames: []string{\"clusterD\"},\n\t}, nil)\n\n\tselect {\n\tcase chu := <-ch.updateChannel:\n\t\tif diff := cmp.Diff(chu.updates, []xdsresource.ClusterUpdate{{\n\t\t\tClusterType: xdsresource.ClusterTypeEDS,\n\t\t\tClusterName: \"clusterD\",\n\t\t}}); diff != \"\" {\n\t\t\tt.Fatalf(\"got unexpected cluster update, diff (-got, +want): %v\", diff)\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Fatal(\"Timed out waiting for the cluster update to be written to the update buffer.\")\n\t}\n}", "func TestRestartDaemonWithRestartingContainer(t *testing.T) {\n\tskip.If(t, testEnv.IsRemoteDaemon, \"cannot start daemon on remote test run\")\n\tskip.If(t, testEnv.DaemonInfo.OSType == \"windows\")\n\n\tt.Parallel()\n\n\td := daemon.New(t)\n\tdefer d.Cleanup(t)\n\n\td.StartWithBusybox(t, \"--iptables=false\")\n\tdefer d.Stop(t)\n\n\tctx := context.Background()\n\tclient := d.NewClientT(t)\n\n\t// Just create the container, no need to start it to be started.\n\t// We really want to make sure there is no process running when docker starts back up.\n\t// We will manipulate the on disk state later\n\tid := container.Create(ctx, t, client, container.WithRestartPolicy(\"always\"), container.WithCmd(\"/bin/sh\", \"-c\", \"exit 1\"))\n\n\td.Stop(t)\n\n\tconfigPath := filepath.Join(d.Root, \"containers\", id, \"config.v2.json\")\n\tconfigBytes, err := ioutil.ReadFile(configPath)\n\tassert.NilError(t, err)\n\n\tvar c realcontainer.Container\n\n\tassert.NilError(t, json.Unmarshal(configBytes, &c))\n\n\tc.State = realcontainer.NewState()\n\tc.SetRestarting(&realcontainer.ExitStatus{ExitCode: 1})\n\tc.HasBeenStartedBefore = true\n\n\tconfigBytes, err = json.Marshal(&c)\n\tassert.NilError(t, err)\n\tassert.NilError(t, ioutil.WriteFile(configPath, configBytes, 0600))\n\n\td.Start(t)\n\n\tctxTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\tchOk, chErr := client.ContainerWait(ctxTimeout, id, containerapi.WaitConditionNextExit)\n\tselect {\n\tcase <-chOk:\n\tcase err := <-chErr:\n\t\tassert.NilError(t, err)\n\t}\n}" ]
[ "0.7154246", "0.7076622", "0.6618112", "0.65511364", "0.6372314", "0.6067593", "0.5784652", "0.56116945", "0.5610634", "0.5572265", "0.54858935", "0.54802495", "0.54631937", "0.5448744", "0.5440538", "0.5433369", "0.5408045", "0.5392125", "0.5387219", "0.53741777", "0.53413004", "0.53372574", "0.533151", "0.5322611", "0.53045", "0.5242902", "0.51608515", "0.51486385", "0.51325166", "0.5113378", "0.51104766", "0.509778", "0.5084922", "0.5066567", "0.50628144", "0.50564975", "0.50053823", "0.49957195", "0.49949363", "0.49915135", "0.49851254", "0.49805394", "0.49443063", "0.49288052", "0.49073178", "0.49056593", "0.49028024", "0.48865363", "0.48683512", "0.4836199", "0.48289797", "0.48130187", "0.47992378", "0.47963318", "0.4782717", "0.4771451", "0.47557047", "0.47457886", "0.47212613", "0.472092", "0.47196674", "0.47148", "0.47094074", "0.47044814", "0.46975398", "0.4690618", "0.46873513", "0.46870753", "0.46726578", "0.46684492", "0.46678042", "0.46665788", "0.46644518", "0.46640414", "0.46608046", "0.46582", "0.4648179", "0.4644567", "0.46436056", "0.46360445", "0.46135807", "0.45999447", "0.45782286", "0.4574656", "0.45737755", "0.45718044", "0.45613125", "0.45608282", "0.45552635", "0.45536342", "0.45528007", "0.4541368", "0.45249817", "0.45223847", "0.45163697", "0.45120135", "0.44954953", "0.44844186", "0.44822294", "0.448007" ]
0.6967107
2
NewRemoteAccessVpnUserService creates a new VPN User Service for this specific service and environment
func NewRemoteAccessVpnUserService(apiClient api.ApiClient, serviceCode string, environmentName string) RemoteAccessVpnUserService { return &RemoteAccessVpnUserApi{ entityService: services.NewEntityService(apiClient, serviceCode, environmentName, REMOTE_ACCESS_VPN_USER_ENTITY_TYPE), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) Create(remoteAccessVpnUser RemoteAccessVpnUser) (bool, error) {\n\tsend, merr := json.Marshal(remoteAccessVpnUser)\n\tif merr != nil {\n\t\treturn false, merr\n\t}\n\t_, err := remoteAccessVpnUserApi.entityService.Create(send, map[string]string{})\n\treturn err == nil, err\n}", "func NewUserService(serverURL string) *UserSvc {\n\treturn &UserSvc{\n\t\tserverURL: serverURL,\n\t}\n}", "func(h Bundlable) CreateService(appCtx AppContext.Context) (interface{}, error) {\n\treturn &UserSvc{\n\t\tAppCtx: appCtx,\n\t}, nil\n}", "func NewUserService(token string) *UserService {\n\ts := &UserService{\n\t\ttoken: token,\n\t}\n\ts.updateLogger(monitor.F{})\n\treturn s\n}", "func NewService(repo *UserRepository) *UserService {\n\treturn &UserService{\n\t\trepository: repo,\n\t}\n}", "func New(udb model.UserDB) *Service {\n\treturn &Service{udb}\n}", "func NewUserService(connectionInfo string) (UserService, error) {\n\tug, err := newUserGorm(connectionInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thmac := hash.NewHMAC(hmacSecretKey)\n\tuv := newUserValidator(ug, hmac)\n\treturn &userService{\n\t\tUserDB: uv,\n\t\t/*\n\t\t\tuv implements all the methods in the UserDB interface, so we are able to assign it to the UserDB type\n\t\t\tin userService struct.\n\t\t*/\n\t}, nil\n\t/*\n\t\tWe are able to return a userService struct type for UserService interface type as the userService struct type\n\t\timplements all the methods in the UserService interface.\n\t*/\n}", "func newIPVSService(svc *Service) *ipvsService {\n\tipvsSvc := &ipvsService{\n\t\tAddress: svc.Address,\n\t\tProtocol: svc.Protocol,\n\t\tPort: svc.Port,\n\t\tFirewallMark: svc.FirewallMark,\n\t\tScheduler: svc.Scheduler,\n\t\tFlags: svc.Flags,\n\t\tTimeout: svc.Timeout,\n\t\tPersistenceEngine: svc.PersistenceEngine,\n\t}\n\n\tif ip4 := svc.Address.To4(); ip4 != nil {\n\t\tipvsSvc.AddrFamily = syscall.AF_INET\n\t\tipvsSvc.Netmask = 0xffffffff\n\t} else {\n\t\tipvsSvc.AddrFamily = syscall.AF_INET6\n\t\tipvsSvc.Netmask = 128\n\t}\n\n\treturn ipvsSvc\n}", "func NewUserService(\n\trepo userrepo.Repo,\n\tpwdRepo pwdRepo.Repo,\n\trds rdms.RandomString,\n\thmac hmachash.HMAC,\n\tpepper string) UserService {\n\n\treturn &userService{\n\t\tRepo: repo,\n\t\tPwdRepo: pwdRepo,\n\t\tRds: rds,\n\t\thmac: hmac,\n\t\tpepper: pepper,\n\t}\n}", "func NewUserService() pb.UserServiceServer {\n\treturn &userService{\n\t\tdao: dao.New(config.Cfg),\n\t}\n}", "func NewUserService(client *ent.Client) *UserService {\n\treturn &UserService{\n\t\tclient: client,\n\t}\n}", "func createVhostUserEndpoint(netInfo NetworkInfo, socket string) (*VhostUserEndpoint, error) {\n\n\tvhostUserEndpoint := &VhostUserEndpoint{\n\t\tSocketPath: socket,\n\t\tHardAddr: netInfo.Iface.HardwareAddr.String(),\n\t\tIfaceName: netInfo.Iface.Name,\n\t\tEndpointType: VhostUserEndpointType,\n\t}\n\treturn vhostUserEndpoint, nil\n}", "func NewUserService(connectionInfo string) (*UserService, error) {\n\tdb, err := gorm.Open(postgres.Open(connectionInfo), &gorm.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &UserService{\n\t\tdb: db,\n\t}, nil\n}", "func NewUserService(connectionInfo string) (*UserService, error) {\n\tdb, err := gorm.Open(\"postgres\", connectionInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb.LogMode(true)\n\treturn &UserService{\n\t\tdb: db,\n\t}, nil\n}", "func newVserverUserAccess(cluster *config.Cluster) (vserverUserAccess, error) {\n\tvua := make(vserverUserAccess)\n\tfor _, vs := range cluster.Vservers {\n\t\tfor _, ag := range vs.AccessGrants {\n\t\t\tif !ag.IsGroup {\n\t\t\t\tvua.grantAccess(vs.Name, ag.Grantee, ag.Key())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgroup, ok := cluster.AccessGroups[ag.Grantee]\n\t\t\tif !ok {\n\t\t\t\tlog.Warningf(\"vserver %v references non-existent access group %q, ignoring\", vs.Name, ag.Grantee)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, username := range group.Members {\n\t\t\t\tvua.grantAccess(vs.Name, username, ag.Key())\n\t\t\t}\n\t\t}\n\t}\n\treturn vua, nil\n}", "func NewService(s userStorage) *userService {\n\treturn &userService{\n\t\tstorage: s,\n\t}\n}", "func NewUserService(conf *conf.Config) (UserService, error) {\n\tdb, err := infrastructure.NewDB(&conf.PostgresConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &userService{\n\t\tUserRepo: infrastructure.NewUserRepo(db),\n\t}, nil\n}", "func NewUserService(db *sqlx.DB) *UserService {\n\treturn &UserService{DB: db}\n}", "func NewService(repo repository.Repository) *Service {\n\tuser := Model{\n\t\tID: 1,\n\t\tUsername: \"[email protected]\",\n\t}\n\tuser2 := Model{\n\t\tID: 2,\n\t\tUsername: \"[email protected]\",\n\t}\n\treturn &Service{\n\t\tusersByIDs: map[int]*Model{1: &user, 2: &user2},\n\t\tusersByUsername: map[string]*Model{\"[email protected]\": &user, \"[email protected]\": &user2},\n\t\trepo: repo,\n\t}\n}", "func New(ctx context.Context) (*Controller, error) {\n\t// create user service\n\tuserSVC, err := service.New(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating service: %v\", err)\n\t}\n\n\treturn &Controller{\n\t\tuser: userSVC,\n\t}, nil\n}", "func NewUserService(config *config.Config, repository *models.UserRepository) *UserService {\n\treturn &UserService{config: config, repository: repository}\n}", "func NewUser(logger *log.Logger) user.Service {\n\treturn &usersrvc{logger}\n}", "func NewService(userService users.Service, rbac *rbacService) Service {\n\treturn service{rbac, userService}\n}", "func NewVpnGateway(ctx *pulumi.Context,\n\tname string, args *VpnGatewayArgs, opts ...pulumi.ResourceOption) (*VpnGateway, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\taliases := pulumi.Aliases([]pulumi.Alias{\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20191201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20180401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20180401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20180601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20180601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20180701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20180701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20180801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20180801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20181001:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20181001:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20181101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20181101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20181201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20181201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20190901:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20190901:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20191101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20191101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200301:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200301:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200401:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200501:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200501:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200601:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200701:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20200801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20200801:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20201101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20201101:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:network/v20210201:VpnGateway\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:network/v20210201:VpnGateway\"),\n\t\t},\n\t})\n\topts = append(opts, aliases)\n\tvar resource VpnGateway\n\terr := ctx.RegisterResource(\"azure-native:network/v20191201:VpnGateway\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewUserServiceServer(db *sql.DB) pb.UserServiceServer {\n\treturn &userServer{db: db}\n}", "func NewUserService(db *gorm.DB) (UserService, error) {\n\tug := newUserGorm(db)\n\tuserValidator := newUserValidator(ug, hash.NewHMAC(secretkey))\n\t//userValidator implements the UserDB interface for userService\n\n\tuserService := &userService{UserDB: userValidator}\n\treturn userService, nil\n}", "func NewUserService() UserService {\n\treturn &userService{}\n}", "func newService(name, project, image string, envs map[string]string, options options) *runapi.Service {\n\tvar envVars []*runapi.EnvVar\n\tfor k, v := range envs {\n\t\tenvVars = append(envVars, &runapi.EnvVar{Name: k, Value: v})\n\t}\n\n\tsvc := &runapi.Service{\n\t\tApiVersion: \"serving.knative.dev/v1\",\n\t\tKind: \"Service\",\n\t\tMetadata: &runapi.ObjectMeta{\n\t\t\tAnnotations: make(map[string]string),\n\t\t\tName: name,\n\t\t\tNamespace: project,\n\t\t},\n\t\tSpec: &runapi.ServiceSpec{\n\t\t\tTemplate: &runapi.RevisionTemplate{\n\t\t\t\tMetadata: &runapi.ObjectMeta{\n\t\t\t\t\tName: generateRevisionName(name, 0),\n\t\t\t\t\tAnnotations: make(map[string]string),\n\t\t\t\t},\n\t\t\t\tSpec: &runapi.RevisionSpec{\n\t\t\t\t\tContainerConcurrency: int64(options.Concurrency),\n\t\t\t\t\tContainers: []*runapi.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tEnv: envVars,\n\t\t\t\t\t\t\tResources: optionsToResourceRequirements(options),\n\t\t\t\t\t\t\tPorts: []*runapi.ContainerPort{optionsToContainerSpec(options)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tForceSendFields: nil,\n\t\t\t\tNullFields: nil,\n\t\t\t},\n\t\t},\n\t}\n\n\tapplyMeta(svc.Metadata, image)\n\tapplyMeta(svc.Spec.Template.Metadata, image)\n\tapplyScaleMeta(svc.Spec.Template.Metadata, \"maxScale\", options.MaxInstances)\n\n\treturn svc\n}", "func NewUserService(provider UserProvider) UserService {\n\treturn UserService{provider}\n}", "func newUser(vres *hyuserviews.UserView) *User {\n\tres := &User{\n\t\tUserID: vres.UserID,\n\t\tUserName: vres.UserName,\n\t\tEmail: vres.Email,\n\t}\n\treturn res\n}", "func NewUserServiceServer(svc UserService, opts ...interface{}) TwirpServer {\n\tserverOpts := newServerOpts(opts)\n\n\t// Using ReadOpt allows backwards and forwads compatibility with new options in the future\n\tjsonSkipDefaults := false\n\t_ = serverOpts.ReadOpt(\"jsonSkipDefaults\", &jsonSkipDefaults)\n\tjsonCamelCase := false\n\t_ = serverOpts.ReadOpt(\"jsonCamelCase\", &jsonCamelCase)\n\tvar pathPrefix string\n\tif ok := serverOpts.ReadOpt(\"pathPrefix\", &pathPrefix); !ok {\n\t\tpathPrefix = \"/twirp\" // default prefix\n\t}\n\n\treturn &userServiceServer{\n\t\tUserService: svc,\n\t\thooks: serverOpts.Hooks,\n\t\tinterceptor: twirp.ChainInterceptors(serverOpts.Interceptors...),\n\t\tpathPrefix: pathPrefix,\n\t\tjsonSkipDefaults: jsonSkipDefaults,\n\t\tjsonCamelCase: jsonCamelCase,\n\t}\n}", "func NewUserService(userRepository UserRepository) *UserService {\n\treturn &UserService{userRepository}\n}", "func New() []di.Def {\n\t// add user services\n\tsvc := append(services, user.Services...)\n\treturn svc\n}", "func NewService(\n\tuserRepo domain.UserRepository,\n\tuserStorageCredRepo domain.UserStorageCredentialRepository,\n\tauthenticator domain.Authenticator,\n\tmailer domain.Mailer,\n\tpasswordHasher domain.Hasher,\n\tstringGenerator domain.StringGenerator,\n\tstorageProviderPool domain.StorageProviderPool,\n\thtmlTemplates *htmlTemplate.Template,\n\ttextTemplates *textTemplate.Template,\n\tconfig Config,\n) domain.UserService {\n\treturn &service{\n\t\tuserRepo: userRepo,\n\t\tuserStorageCredRepo: userStorageCredRepo,\n\t\tauthenticator: authenticator,\n\t\tmailer: mailer,\n\t\tpasswordHasher: passwordHasher,\n\t\tstringGenerator: stringGenerator,\n\n\t\tstorageProviderPool: storageProviderPool,\n\n\t\thtmlTemplates: htmlTemplates,\n\t\ttextTemplates: textTemplates,\n\n\t\tconfig: config,\n\t}\n}", "func NewService(repo svc.UserRepository) *service {\n\treturn &service{\n\t\trepo: repo,\n\t}\n}", "func NewService(repo Repository, userRestRepo UsersRepository) Service {\n\treturn &service{\n\t\trepository: repo,\n\t\tuserRestRepo: userRestRepo,\n\t}\n}", "func NewService(rep user.Repository, logger *logrus.Logger) user.Service {\n\treturn &userService {\n\t\trepository: rep,\n\t\tlogger: logger,\n\t}\n}", "func NewUserService(db *gorm.DB) *UserService {\n\treturn &UserService{db: db}\n}", "func NewUserServiceServer(svc UserService, opts ...interface{}) TwirpServer {\n\tserverOpts := twirp.ServerOptions{}\n\tfor _, opt := range opts {\n\t\tswitch o := opt.(type) {\n\t\tcase twirp.ServerOption:\n\t\t\to(&serverOpts)\n\t\tcase *twirp.ServerHooks: // backwards compatibility, allow to specify hooks as an argument\n\t\t\ttwirp.WithServerHooks(o)(&serverOpts)\n\t\tcase nil: // backwards compatibility, allow nil value for the argument\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Invalid option type %T on NewUserServiceServer\", o))\n\t\t}\n\t}\n\n\treturn &userServiceServer{\n\t\tUserService: svc,\n\t\tpathPrefix: serverOpts.PathPrefix(),\n\t\tinterceptor: twirp.ChainInterceptors(serverOpts.Interceptors...),\n\t\thooks: serverOpts.Hooks,\n\t\tjsonSkipDefaults: serverOpts.JSONSkipDefaults,\n\t}\n}", "func NewService(vendor string, product string, version string, url string) (*Service, error) {\n\ts := Service{\n\t\tvendor: vendor,\n\t\tproduct: product,\n\t\tversion: version,\n\t\turl: url,\n\t\tinterfaces: make(map[string]dispatcher),\n\t\tdescriptions: make(map[string]string),\n\t}\n\terr := s.RegisterInterface(orgvarlinkserviceNew())\n\n\treturn &s, err\n}", "func NewUserService(db *gorm.DB, pepper, hmacKey string) UserService {\r\n\tug := &userGorm{db}\r\n\thmac := hash.NewHMAC(hmacKey)\r\n\tuv := newUserValidator(ug, hmac, pepper)\r\n\treturn &userService{\r\n\t\tUserDB: uv,\r\n\t\tpepper: pepper,\r\n\t}\r\n}", "func newService(rcvr interface{}, guard Guard) *service {\n\ts := new(service)\n\ts.typ = reflect.TypeOf(rcvr)\n\ts.rcvr = reflect.ValueOf(rcvr)\n\ts.name = reflect.Indirect(s.rcvr).Type().Name()\n\ts.guard = guard\n\n\t// install the methods\n\ts.method = suitableMethods(s.typ, true)\n\n\treturn s\n}", "func (c PGClient) NewService(name string, binsIB int64, host string, port int, typeService string, runSTR string, projects []string, owner string) (err error) {\n\t_, err = c.DB.Query(\"select new_service_function($1,$2,$3,$4,$5,$6,$7,$8)\", name, binsIB, host, port, typeService, runSTR, pg.Array(projects), owner)\n\treturn err\n}", "func New(middleware []Middleware) UserService {\n\tvar svc UserService = NewBasicUserService()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func NewVpnGateway(ctx *pulumi.Context,\n\tname string, args *VpnGatewayArgs, opts ...pulumi.ResourceOption) (*VpnGateway, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Region == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Region'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"project\",\n\t\t\"region\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource VpnGateway\n\terr := ctx.RegisterResource(\"google-native:compute/alpha:VpnGateway\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func newUserService(logger logger.Service) *UserService {\n\tvar t int32 = 0\n\treturn &UserService{\n\t\tDict: make(map[int32]*User),\n\t\tatomicCounter: &t,\n\t\tlogger: logger,\n\t}\n}", "func NewUserService() *UserServiceImpl {\n\treturn &UserServiceImpl{}\n}", "func NewService(repo users.RepoUsers) RepoServiceAuth {\n\treturn &service{\n\t\trepoUser: repo,\n\t}\n}", "func NewUserService(logger logger.Service) Service {\n\treturn newUserService(logger)\n}", "func NewUserService(repo repository.UserRepository) UserService {\n\treturn UserService{\n\t\tuserRepository: repo,\n\t}\n}", "func NewUserService(userRepo repository.IUserRepository) IUserService {\n\treturn &userService{userRepo: userRepo}\n}", "func NewUserServiceServer(\n\tgc *github.Client,\n) UserServiceServer {\n\treturn &userServiceServerImpl{\n\t\tgc: gc,\n\t}\n}", "func NewServiceProxy(addrs []string, ctx *handlers.Context) *httputil.ReverseProxy {\r\n\tnextIndex := 0\r\n\tmx := sync.Mutex{}\r\n\treturn &httputil.ReverseProxy{\r\n\t\tDirector: func(r *http.Request) {\r\n\t\t\tuser := GetCurrentUser(r, ctx)\r\n\t\t\tuserJSON, err := json.Marshal(user)\r\n\t\t\tif err != nil {\r\n\t\t\t\tlog.Printf(\"error marshaling user: %v\", err)\r\n\t\t\t}\r\n\t\t\tr.Header.Set(\"X-User\", string(userJSON))\r\n\r\n\t\t\tr.Header.Set(\"Content-Type\", \"application/json\")\r\n\t\t\tmx.Lock()\r\n\t\t\tr.URL.Host = addrs[nextIndex%len(addrs)]\r\n\t\t\tnextIndex++\r\n\t\t\tmx.Unlock()\r\n\t\t\tr.URL.Scheme = \"http\"\r\n\t\t},\r\n\t}\r\n}", "func NewUserService(db *gorm.DB) *UserService {\n\tusersRepository := &Repository{db}\n\treturn &UserService{\n\t\tusersRepository,\n\t}\n}", "func NewVpnConfiguration()(*VpnConfiguration) {\n m := &VpnConfiguration{\n DeviceConfiguration: *NewDeviceConfiguration(),\n }\n odataTypeValue := \"#microsoft.graph.vpnConfiguration\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func (h *ServiceUsersHandler) Create(ctx context.Context, project, service string, req CreateServiceUserRequest) (*ServiceUser, error) {\n\tpath := buildPath(\"project\", project, \"service\", service, \"user\")\n\tbts, err := h.client.doPostRequest(ctx, path, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r ServiceUserResponse\n\terrR := checkAPIResponse(bts, &r)\n\n\treturn r.User, errR\n}", "func NewUserService(repo repository.UserRepository) UserService {\n\treturn &userService{\n\t\trepo: repo,\n\t}\n}", "func New(config Config) (*Service, error) {\n\tvar err error\n\n\tvar versionService *version.Service\n\t{\n\t\tc := version.Config{\n\t\t\tDescription: config.Description,\n\t\t\tGitCommit: config.GitCommit,\n\t\t\tName: config.Name,\n\t\t\tSource: config.Source,\n\t\t}\n\n\t\tversionService, err = version.New(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar opsgenieService *opsgenie.OpsGenie\n\t{\n\t\tc := opsgenie.Config{\n\t\t\tLogger: config.Logger,\n\t\t\tAuthToken: config.Viper.GetString(config.Flag.Service.Oncall.OpsgenieToken),\n\t\t}\n\t\topsgenieService, err = opsgenie.New(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar webhookService *webhook.Service\n\t{\n\t\tusers := make(map[string]string)\n\t\tuserList := config.Viper.GetString(config.Flag.Service.Oncall.Users)\n\t\tfor _, user := range strings.Split(userList, \",\") {\n\t\t\tkv := strings.Split(user, \":\")\n\t\t\tusers[kv[0]] = kv[1]\n\t\t}\n\n\t\twebhookConfig := webhook.Config{\n\t\t\tHttpClient: &http.Client{Timeout: time.Second * 10},\n\t\t\tLogger: config.Logger,\n\n\t\t\tGithubToken: config.Viper.GetString(config.Flag.Service.Oncall.GithubToken),\n\t\t\tOpsgenie: opsgenieService,\n\t\t\tUsers: users,\n\t\t\tWebhookSecret: config.Viper.GetString(config.Flag.Service.Oncall.WebhookSecret),\n\t\t}\n\n\t\twebhookService, err = webhook.New(webhookConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tnewService := &Service{\n\t\tVersion: versionService,\n\t\tWebhook: webhookService,\n\t}\n\n\treturn newService, nil\n}", "func NewUserServiceController(userService user.Service) mygrpc.UserServiceServer {\n\treturn &userServiceController{\n\t\tuserService: userService,\n\t}\n}", "func UserImageCreateService(userid string, label string, name string) (*domain.Image, error) {\n\timage, err := domain.UserCreateItem(userid, label, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn image, nil\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func NewUserService(repository repositories.UserRepository) UserService {\n\trepo = repository\n\treturn &service{}\n}", "func NewUserlogService(opts ...Option) (*UserlogService, error) {\n\to := &Options{}\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\n\tif o.Stream == nil || o.Store == nil {\n\t\treturn nil, fmt.Errorf(\"need non nil stream (%v) and store (%v) to work properly\", o.Stream, o.Store)\n\t}\n\n\tch, err := events.Consume(o.Stream, \"userlog\", o.RegisteredEvents...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tul := &UserlogService{\n\t\tlog: o.Logger,\n\t\tm: o.Mux,\n\t\tstore: o.Store,\n\t\tcfg: o.Config,\n\t\thistoryClient: o.HistoryClient,\n\t\tgatewaySelector: o.GatewaySelector,\n\t\tvalueClient: o.ValueClient,\n\t\tregisteredEvents: make(map[string]events.Unmarshaller),\n\t\ttp: o.TraceProvider,\n\t\ttracer: o.TraceProvider.Tracer(\"github.com/owncloud/ocis/services/userlog/pkg/service\"),\n\t\tpublisher: o.Stream,\n\t}\n\n\tfor _, e := range o.RegisteredEvents {\n\t\ttyp := reflect.TypeOf(e)\n\t\tul.registeredEvents[typ.String()] = e\n\t}\n\n\tm := roles.NewManager(\n\t\t// TODO: caching?\n\t\troles.Logger(o.Logger),\n\t\troles.RoleService(o.RoleClient),\n\t)\n\n\tul.m.Route(\"/ocs/v2.php/apps/notifications/api/v1/notifications\", func(r chi.Router) {\n\t\tr.Get(\"/\", ul.HandleGetEvents)\n\t\tr.Delete(\"/\", ul.HandleDeleteEvents)\n\t\tr.Post(\"/global\", RequireAdminOrSecret(&m, o.Config.GlobalNotificationsSecret)(ul.HandlePostGlobalEvent))\n\t\tr.Delete(\"/global\", RequireAdminOrSecret(&m, o.Config.GlobalNotificationsSecret)(ul.HandleDeleteGlobalEvent))\n\t})\n\n\tgo ul.MemorizeEvents(ch)\n\n\treturn ul, nil\n}", "func NewService(network, address string, userManager user.Manager, ts jwt.TokenService) *Server {\n\treturn &Server{\n\t\tNetwork: network,\n\t\tAddress: address,\n\t\tManager: userManager,\n\t\tToken: ts,\n\t}\n}", "func NewVcapService(binding kfv1alpha1.ServiceInstanceBinding, credentialsSecret corev1.Secret) VcapService {\n\t// See the cloud-controller-ng source for how this is supposed to be built\n\t// being that it doesn't seem to be formally fully documented anywhere:\n\t// https://github.com/cloudfoundry/cloud_controller_ng/blob/65a75e6c97f49756df96e437e253f033415b2db1/app/presenters/system_environment/service_binding_presenter.rb#L32\n\n\tvs := VcapService{\n\t\tBindingName: getBindingName(binding),\n\t\tName: binding.Status.BindingName,\n\t\tInstanceName: binding.Spec.InstanceRef.Name,\n\t\tLabel: binding.Status.ClassName,\n\t\tPlan: binding.Status.PlanName,\n\t\tTags: binding.Status.Tags,\n\t\tCredentials: make(map[string]json.RawMessage),\n\t}\n\n\tfor sn, sd := range credentialsSecret.Data {\n\t\tvs.Credentials[sn] = sd\n\t}\n\n\tif binding.Status.VolumeStatus != nil {\n\t\tvar mode string\n\t\tif binding.Status.VolumeStatus.ReadOnly {\n\t\t\tmode = \"ro\"\n\t\t} else {\n\t\t\tmode = \"rw\"\n\t\t}\n\t\tvolumeMounts := []VolumeMount{\n\t\t\t{\n\t\t\t\tContainerDir: binding.Status.VolumeStatus.Mount,\n\t\t\t\tDeviceType: \"shared\",\n\t\t\t\tMode: mode,\n\t\t\t},\n\t\t}\n\n\t\tvs.VolumeMounts = volumeMounts\n\t}\n\n\treturn vs\n}", "func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) {\n\tc, err := parseConfig(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuserManager, plug, err := getDriver(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsvc := &service{\n\t\tusermgr: userManager,\n\t\tplugin: plug,\n\t}\n\n\treturn svc, nil\n}", "func NewService(userService user.Service, adminService admin.Service, adminRepo admin.Repository, userRepo user.Repository, cfg *config.AppConfig) Service {\n\treturn &service{\n\t\tuserService,\n\t\tadminService,\n\t\tadminRepo,\n\t\tuserRepo,\n\t\t*cfg,\n\t}\n}", "func New(c *conf.Config) *VipService {\n\treturn &VipService{\n\t\tc: c,\n\t\tdao: vip.New(c),\n\t\tliveVipChangePub: databus.New(c.LiveVipChangePub),\n\t\tinfoRunCache: cache.New(1, 10240),\n\t\taddRunCache: cache.New(1, 1024),\n\t}\n}", "func NewUser(vres *hyuserviews.User) *User {\n\tvar res *User\n\tswitch vres.View {\n\tcase \"default\", \"\":\n\t\tres = newUser(vres.Projected)\n\tcase \"id\":\n\t\tres = newUserID(vres.Projected)\n\t}\n\treturn res\n}", "func NewUserService(tx *gorm.DB) *UserService {\n\treturn &UserService{\n\t\ttx: tx,\n\t\tuserRepo: repository.NewUserRepository(tx),\n\t}\n}", "func NewUserService(logger *zap.Logger) *UserService {\n\treturn &UserService{Dao: dao.NewUserDAO(logger), logger: logger}\n}", "func (in *IstioClient) CreateVirtualService(namespace string, virtualServiceToBeCreated IstioObject) (IstioObject, error) {\n\tlog.Error(namespace)\n\tresult, err := in.istioNetworkingApi.Post().Namespace(namespace).Resource(virtualServices).Body(virtualServiceToBeCreated).Do().Get()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tlog.Error(\"called namespace and no error\")\n\tvirtualService, ok := result.(*VirtualService)\n\tif !ok {\n\t\tlog.Error(\"no virtual service object returned\")\n\t\treturn nil, fmt.Errorf(\"%s doesn't return a VirtualService object\", namespace)\n\t}\n\treturn virtualService.DeepCopyIstioObject(), nil\n}", "func NewService(\n\tapp *userproductapp.App,\n) *Service {\n\treturn &Service{\n\t\tapp: app,\n\t}\n}", "func newVserverAccess() *vserverAccess {\n\treturn &vserverAccess{\n\t\taccess: make(vserverUserAccess),\n\t}\n}", "func NewUserService(list map[int]models.User, count int) models.UserStorage {\n\treturn &UserService{\n\t\tUserList: list,\n\t\tMaxUserID: count,\n\t}\n}", "func CreateCurrentUserRsvp(w http.ResponseWriter, r *http.Request) {\n\tid := r.Header.Get(\"HackIllinois-Identity\")\n\n\tif id == \"\" {\n\t\terrors.WriteError(w, r, errors.MalformedRequestError(\"Must provide id in request.\", \"Must provide id in request.\"))\n\t\treturn\n\t}\n\n\tisAccepted, isActive, err := service.IsApplicantAcceptedAndActive(id)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not determine status of applicant decision, which is needed to create an RSVP for the user.\"))\n\t\treturn\n\t}\n\n\tif !isAccepted {\n\t\terrors.WriteError(w, r, errors.AttributeMismatchError(\"Applicant not accepted.\", \"Applicant must be accepted to RSVP.\"))\n\t\treturn\n\t}\n\n\tif !isActive {\n\t\terrors.WriteError(w, r, errors.AttributeMismatchError(\"Applicant decision has expired.\", \"Applicant decision has expired.\"))\n\t\treturn\n\t}\n\n\trsvp := datastore.NewDataStore(config.RSVP_DEFINITION)\n\terr = json.NewDecoder(r.Body).Decode(&rsvp)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not decode user rsvp information. Failure in JSON validation or incorrect rsvp definition.\"))\n\t\treturn\n\t}\n\n\trsvp.Data[\"id\"] = id\n\n\tregistration_data, err := service.GetRegistrationData(id)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not retrieve registration data.\"))\n\t\treturn\n\t}\n\n\trsvp.Data[\"registrationData\"] = registration_data\n\n\terr = service.CreateUserRsvp(id, rsvp)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not create an RSVP for the user.\"))\n\t\treturn\n\t}\n\n\tisAttending, ok := rsvp.Data[\"isAttending\"].(bool)\n\n\tif !ok {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Failure in parsing user rsvp\"))\n\t\treturn\n\t}\n\n\tif isAttending {\n\t\terr = service.AddAttendeeRole(id)\n\n\t\tif err != nil {\n\t\t\terrors.WriteError(w, r, errors.AuthorizationError(err.Error(), \"Could not add Attendee role to applicant.\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tupdated_rsvp, err := service.GetUserRsvp(id)\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.DatabaseError(err.Error(), \"Could not get user's RSVP.\"))\n\t\treturn\n\t}\n\n\tif isAttending {\n\t\tmail_template := \"rsvp_confirmation\"\n\t\terr = service.SendUserMail(id, mail_template)\n\n\t\tif err != nil {\n\t\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not send user RSVP confirmation mail.\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tjson.NewEncoder(w).Encode(updated_rsvp)\n}", "func NewUserService(db *gorm.DB) UserService {\n\tug := &userGorm{db}\n\thmac := hash.NewHMAC(hmacSecretKey)\n\tuv := newUserValidator(ug, hmac)\n\treturn &userService{\n\t\tUserDB: uv,\n\t}\n}", "func NewUserService(ctx servicecontext.ServiceContext, config UserServiceConfiguration) service.UserService {\n\treturn &userServiceImpl{\n\t\tBaseService: base.NewBaseService(ctx),\n\t\tconfig: config,\n\t}\n}", "func newRemoteUserFromIdentity(identity tlsca.Identity, clusterName string) authz.RemoteUser {\n\treturn authz.RemoteUser{\n\t\tClusterName: clusterName,\n\t\tUsername: identity.Username,\n\t\tPrincipals: identity.Principals,\n\t\tKubernetesGroups: identity.KubernetesGroups,\n\t\tKubernetesUsers: identity.KubernetesUsers,\n\t\tDatabaseNames: identity.DatabaseNames,\n\t\tDatabaseUsers: identity.DatabaseUsers,\n\t\tRemoteRoles: identity.Groups,\n\t\tIdentity: identity,\n\t}\n}", "func CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"CreateNewUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Creating new user\")\n\treq := &CreateNewUserRequest{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, req)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tisValidPassphrase := passphrase.Validate(req.Passphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\tuser, err := UserRepo.CreateUserRecord(r.Context(), req.Email, req.Passphrase)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.CreateUserRecord got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := &CreateNewUserResponse{\n\t\tRecordID: user.RecID,\n\t\tEmail: user.Email,\n\t\tEnabled: user.Enabled,\n\t\tSuspended: user.Suspended,\n\t\tLastSeen: user.LastSeen,\n\t\tLastLogin: user.LastLogin,\n\t\tTotpEnabled: user.Enable2FactorAuth,\n\t}\n\tfLog.Warnf(\"Sending email\")\n\tmailer.Send(r.Context(), &mailer.Email{\n\t\tFrom: config.Get(\"mailer.from\"),\n\t\tFromName: config.Get(\"mailer.from.name\"),\n\t\tTo: []string{user.Email},\n\t\tCc: nil,\n\t\tBcc: nil,\n\t\tTemplate: \"EMAIL_VERIFY\",\n\t\tData: user,\n\t})\n\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"Success creating user\", nil, resp)\n\treturn\n}", "func NewTunnelVirtualNetwork(ctx *pulumi.Context,\n\tname string, args *TunnelVirtualNetworkArgs, opts ...pulumi.ResourceOption) (*TunnelVirtualNetwork, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.AccountId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'AccountId'\")\n\t}\n\tif args.Name == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Name'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource TunnelVirtualNetwork\n\terr := ctx.RegisterResource(\"cloudflare:index/tunnelVirtualNetwork:TunnelVirtualNetwork\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewUser(ctx *pulumi.Context,\n\tname string, args *UserArgs, opts ...pulumi.ResourceOption) (*User, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.InstanceId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceId'\")\n\t}\n\tif args.Source == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Source'\")\n\t}\n\tif args.UserName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserName'\")\n\t}\n\tif args.Password != nil {\n\t\targs.Password = pulumi.ToSecret(args.Password).(pulumi.StringPtrInput)\n\t}\n\tsecrets := pulumi.AdditionalSecretOutputs([]string{\n\t\t\"password\",\n\t})\n\topts = append(opts, secrets)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource User\n\terr := ctx.RegisterResource(\"alicloud:bastionhost/user:User\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewCreateUserContext(ctx context.Context, r *http.Request, service *goa.Service) (*CreateUserContext, error) {\n\tvar err error\n\tresp := goa.ContextResponse(ctx)\n\tresp.Service = service\n\treq := goa.ContextRequest(ctx)\n\treq.Request = r\n\trctx := CreateUserContext{Context: ctx, ResponseData: resp, RequestData: req}\n\treturn &rctx, err\n}", "func createUserV1() user {\n\tu := user{\n\t\tname: \"Bill\",\n\t\temail: \"[email protected]\",\n\t}\n\n\tprintln(\"V1\", &u)\n\n\treturn u\n}", "func (s Obj_value) NewService() (ServiceInfo, error) {\n\ts.Struct.SetUint16(4, 7)\n\tss, err := NewServiceInfo(s.Struct.Segment())\n\tif err != nil {\n\t\treturn ServiceInfo{}, err\n\t}\n\terr = s.Struct.SetPtr(0, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func createNginxService() {\n\tserviceData := &apiv1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"test-nginx\",\n\t\t},\n\t\tSpec: apiv1.ServiceSpec{\n\t\t\tType: apiv1.ServiceTypeNodePort,\n\t\t\tPorts: []apiv1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tPort: 80,\n\t\t\t\t\tNodePort: 30010,\n\t\t\t\t},\n\t\t\t},\n\t\t\tSelector: map[string]string{\n\t\t\t\t\"app\": \"test-nginx\",\n\t\t\t},\n\t\t},\n\t}\n\tcreateService(serviceData)\n}", "func newClient(ctx context.Context, cfg vcConfig) (*vsClient, error) {\n\tu := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: cfg.server,\n\t\tPath: \"sdk\",\n\t}\n\n\tu.User = url.UserPassword(cfg.user, cfg.password)\n\tinsecure := cfg.insecure\n\n\tgc, err := govmomi.NewClient(ctx, &u, insecure)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connecting to vSphere API: %w\", err)\n\t}\n\n\trc := rest.NewClient(gc.Client)\n\ttm := tags.NewManager(rc)\n\n\tvsc := vsClient{\n\t\tgovmomi: gc,\n\t\trest: rc,\n\t\ttagManager: tm,\n\t}\n\n\terr = vsc.rest.Login(ctx, u.User)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"logging into rest api: %w\", err)\n\t}\n\n\treturn &vsc, nil\n}", "func NewAccountService(userParam interface{}) (*AccountService, error) {\n\t// var user *schema.User\n\t// var ok bool\n\t// var err error\n\t//\n\t// if user, ok = userParam.(*schema.User); !ok {\n\t// \tuserid := utils.ObjectId(userParam)\n\t// \tuser, err = models.User.FindById(userid)\n\t// \tif err != nil {\n\t// \t\tlog.Errorf(\"Unable to find user when creating AccountService: %v\", userid)\n\t// \t\treturn nil, err\n\t// \t}\n\t// }\n\t//\n\t// service := &AccountService{User: user}\n\t//\n\t// return service, nil\n\treturn nil, nil\n}", "func NewService(db *gorm.DB, logger kitlog.Logger, configPath string) (Service, error) {\n\tvar qiniuViper = viper.New()\n\tqiniuViper.AddConfigPath(configPath)\n\tqiniuViper.SetConfigName(\"qiniu\")\n\tif err := qiniuViper.ReadInConfig(); err != nil {\n\t\treturn &serviceImpl{}, err\n\t}\n\n\tvar qiniuConfig qiniuConfig\n\tif err := qiniuViper.Unmarshal(&qiniuConfig); err != nil {\n\t\treturn &serviceImpl{}, err\n\t}\n\n\treturn &serviceImpl{\n\t\tdb: db,\n\t\tlogger: logger,\n\t\tqiniuConfig: &qiniuConfig,\n\t}, nil\n}", "func newUserProjectBindings(c *KubermaticV1Client) *userProjectBindings {\n\treturn &userProjectBindings{\n\t\tclient: c.RESTClient(),\n\t}\n}", "func newService(kogitoApp *v1alpha1.KogitoApp, deploymentConfig *appsv1.DeploymentConfig) (service *corev1.Service) {\n\tif deploymentConfig == nil {\n\t\t// we can't create a service without a DC\n\t\treturn nil\n\t}\n\n\tports := buildServicePorts(deploymentConfig)\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tservice = &corev1.Service{\n\t\tObjectMeta: *deploymentConfig.ObjectMeta.DeepCopy(),\n\t\tSpec: corev1.ServiceSpec{\n\t\t\tSelector: deploymentConfig.Spec.Selector,\n\t\t\tType: corev1.ServiceTypeClusterIP,\n\t\t\tPorts: ports,\n\t\t},\n\t}\n\n\tmeta.SetGroupVersionKind(&service.TypeMeta, meta.KindService)\n\taddDefaultMeta(&service.ObjectMeta, kogitoApp)\n\taddServiceLabels(&service.ObjectMeta, kogitoApp)\n\timportPrometheusAnnotations(deploymentConfig, service)\n\tservice.ResourceVersion = \"\"\n\treturn service\n}", "func createUserV2() *user {\n\tu := user{\n\t\tname: \"Bill\",\n\t\temail: \"[email protected]\",\n\t}\n\n\tprintln(\"V2\", &u)\n\n\treturn &u\n}", "func newService(namespace, name string) *v1.Service {\n\treturn &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labelMap(),\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: labelMap(),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{Name: \"port-1338\", Port: 1338, Protocol: \"TCP\", TargetPort: intstr.FromInt(1338)},\n\t\t\t\t{Name: \"port-1337\", Port: 1337, Protocol: \"TCP\", TargetPort: intstr.FromInt(1337)},\n\t\t\t},\n\t\t},\n\t}\n\n}", "func NewService(options ...ConfigOption) (auth.WebAuthnService, error) {\n\ts := WebAuthn{\n\t\tmaxDevices: defaultMaxDevices,\n\t}\n\n\tfor _, opt := range options {\n\t\topt(&s)\n\t}\n\n\tlib, err := webauthnLib.New(&webauthnLib.Config{\n\t\tRPDisplayName: s.displayName,\n\t\tRPID: s.domain,\n\t\tRPOrigin: s.requestOrigin,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.lib = lib\n\n\treturn &s, nil\n}", "func CreateUserService() *UserService {\n\tuserRepository := repositories.CreateUserRepository()\n\tuserService := NewUserService(userRepository)\n\treturn userService\n}", "func New() *CreatePaymentService {\n\tconn := c.Mysql()\n\n\tuserRepository := *u.Repo(conn)\n\tproductRepository := *p.Repo(conn)\n\ttokenRepository := *t.Repo(conn)\n\tpaymentRepository := *payment.Repo(conn)\n\tdiscountRepository := *d.Repo(conn)\n\temailService := e.Service{}\n\n\treturn &CreatePaymentService{\n\t\tuserRepository,\n\t\tproductRepository,\n\t\ttokenRepository,\n\t\tpaymentRepository,\n\t\tdiscountRepository,\n\t\temailService,\n\t}\n}", "func NewOpenVPNAuthd(cfg *AuthConfig) (OpenVPNAuthd, error) {\n\t//var err error\n\n\tglog.Infof(\"creating a new openvpn authd service, config: %s\", cfg)\n\n\tservice := new(openvpnAuthd)\n\tservice.config = cfg\n\n\t// step: create the vault client\n\tglog.V(3).Infof(\"creating the vault client, address: %s, username: %s\", cfg.VaultURL, cfg.VaultUsername)\n\tclient, err := NewVaultClient(cfg.VaultURL, cfg.VaultCaFile, cfg.VaultTLSVerify)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create a vault client, error: %s\", err)\n\t}\n\tservice.vault = client\n\n\t// step: attempt to authenticate to vault\n\terr = client.Authenticate(cfg.VaultUsername, cfg.VaultPassword)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to authenticate to vault, error: %s\", err)\n\t}\n\n\t// step: create the gin router\n\trouter := gin.New()\n\trouter.LoadHTMLGlob(\"templates/*\")\n\trouter.Use(gin.Logger())\n\trouter.Use(gin.Recovery())\n\trouter.GET(\"/health\", service.healthHandler)\n\trouter.GET(\"/\", service.openVPNHandler)\n\n\tservice.router = router\n\n\treturn service, nil\n}", "func NewUserService(\n\tlogger lib.Logger,\n\tuserRepository repository.UserRepository,\n\tuserRoleRepository repository.UserRoleRepository,\n\troleRepository repository.RoleRepository,\n\troleMenuRepository repository.RoleMenuRepository,\n\tmenuRepository repository.MenuRepository,\n\tmenuActionRepository repository.MenuActionRepository,\n\tcasbinService CasbinService,\n\tconfig lib.Config,\n) UserService {\n\treturn UserService{\n\t\tlogger: logger,\n\t\tconfig: config,\n\t\tuserRepository: userRepository,\n\t\tuserRoleRepository: userRoleRepository,\n\t\troleRepository: roleRepository,\n\t\troleMenuRepository: roleMenuRepository,\n\t\tmenuRepository: menuRepository,\n\t\tmenuActionRepository: menuActionRepository,\n\t\tcasbinService: casbinService,\n\t}\n}", "func (vc *VirtualCenter) NewClient(ctx context.Context, useragent string) (*govmomi.Client, error) {\n\tlog := logger.GetLogger(ctx)\n\tif vc.Config.Scheme == \"\" {\n\t\tvc.Config.Scheme = DefaultScheme\n\t}\n\n\turl, err := soap.ParseURL(net.JoinHostPort(vc.Config.Host, strconv.Itoa(vc.Config.Port)))\n\tif err != nil {\n\t\tlog.Errorf(\"failed to parse URL %s with err: %v\", url, err)\n\t\treturn nil, err\n\t}\n\n\tsoapClient := soap.NewClient(url, vc.Config.Insecure)\n\tif len(vc.Config.CAFile) > 0 && !vc.Config.Insecure {\n\t\tif err := soapClient.SetRootCAs(vc.Config.CAFile); err != nil {\n\t\t\tlog.Errorf(\"failed to load CA file: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t} else if len(vc.Config.Thumbprint) > 0 && !vc.Config.Insecure {\n\t\tsoapClient.SetThumbprint(url.Host, vc.Config.Thumbprint)\n\t\tlog.Debugf(\"using thumbprint %s for url %s \", vc.Config.Thumbprint, url.Host)\n\t}\n\n\tsoapClient.Timeout = time.Duration(vc.Config.VCClientTimeout) * time.Minute\n\tlog.Debugf(\"Setting vCenter soap client timeout to %v\", soapClient.Timeout)\n\tvimClient, err := vim25.NewClient(ctx, soapClient)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to create new client with err: %v\", err)\n\t\treturn nil, err\n\t}\n\terr = vimClient.UseServiceVersion(\"vsan\")\n\tif err != nil && vc.Config.Host != \"127.0.0.1\" {\n\t\t// Skipping error for simulator connection for unit tests.\n\t\tlog.Errorf(\"Failed to set vimClient service version to vsan. err: %v\", err)\n\t\treturn nil, err\n\t}\n\tvimClient.UserAgent = useragent\n\tclient := &govmomi.Client{\n\t\tClient: vimClient,\n\t\tSessionManager: session.NewManager(vimClient),\n\t}\n\n\terr = vc.login(ctx, client)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to login to vc. err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\ts, err := client.SessionManager.UserSession(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to get UserSession. err: %v\", err)\n\t\treturn nil, err\n\t}\n\t// Refer to this issue - https://github.com/vmware/govmomi/issues/2922\n\t// When Session Manager -> UserSession can return nil user session with nil error\n\t// so handling the case for nil session.\n\tif s == nil {\n\t\treturn nil, errors.New(\"nil session obtained from session manager\")\n\t}\n\tlog.Infof(\"New session ID for '%s' = %s\", s.UserName, s.Key)\n\n\tif vc.Config.RoundTripperCount == 0 {\n\t\tvc.Config.RoundTripperCount = DefaultRoundTripperCount\n\t}\n\tclient.RoundTripper = vim25.Retry(client.RoundTripper,\n\t\tvim25.TemporaryNetworkError(vc.Config.RoundTripperCount))\n\treturn client, nil\n}" ]
[ "0.5805183", "0.57359457", "0.5453349", "0.5439638", "0.54393923", "0.5420138", "0.54157877", "0.54116315", "0.5306999", "0.53007865", "0.5278734", "0.5274535", "0.52729315", "0.52683127", "0.52457994", "0.5242291", "0.5201245", "0.5189055", "0.51687616", "0.51545966", "0.51288295", "0.51270354", "0.51227117", "0.5117998", "0.5111676", "0.5102524", "0.50930333", "0.5087413", "0.50659394", "0.5064843", "0.5060086", "0.50565153", "0.5042968", "0.5033758", "0.50260997", "0.5021873", "0.5021178", "0.5012073", "0.5009567", "0.50088114", "0.50019664", "0.4985916", "0.49635538", "0.4960461", "0.49536395", "0.49524498", "0.4934927", "0.4926945", "0.49230412", "0.4919545", "0.49130183", "0.4905514", "0.49051043", "0.49014843", "0.48819202", "0.48781848", "0.48775375", "0.48769733", "0.48750082", "0.48667073", "0.4851507", "0.4848574", "0.4848206", "0.48477283", "0.48331425", "0.4821422", "0.48059002", "0.4805709", "0.4803439", "0.48030153", "0.48023114", "0.47984728", "0.47936594", "0.47916412", "0.4780466", "0.47779745", "0.4765106", "0.47634178", "0.47590828", "0.4752473", "0.47503066", "0.47484455", "0.47424474", "0.4727166", "0.47223118", "0.472086", "0.47123224", "0.4710204", "0.4707498", "0.46923617", "0.46884924", "0.46784413", "0.46757618", "0.46755826", "0.46706036", "0.46631953", "0.46589166", "0.46586788", "0.46575144", "0.4653244" ]
0.7328877
0
Get a specific VPN User in the current environment by their ID
func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) Get(id string) (*RemoteAccessVpnUser, error) { data, err := remoteAccessVpnUserApi.entityService.Get(id, map[string]string{}) if err != nil { return nil, err } return parseRemoteAccessVpnUser(data), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getUserByID(ctx context.Context, conn *storage.Conn, userID string) (*ent.Admin, error) {\n\treturn conn.Admin.Get(ctx, userID)\n}", "func (srv *Service) GetUserByID(id string) (*models.User, error) {\n\t//call driven adapter responsible for getting a deployment from mongo database\n\tresponse, err := srv.mongoRepository.GetUserByID(id)\n\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\tif response == nil { //user doesn't exist\n\t\treturn nil, &pkg.Error{Err: err, Code: http.StatusNotFound, Message: \"User with these credentials not found\"}\n\t}\n\n\treturn response, nil\n}", "func GetUser(id int) (components.User, error) {\n\treturn getUser(id)\n}", "func (p *UserPool) GetUser(id string) *store.User {\n\treturn p.users[id]\n}", "func (trello *Trello) UserById(userid string) string {\n return trello.userNamebyId[userid]\n}", "func GetUserByID(user *models.User, id uint) (err error) {\n\tif err = config.DB.Where(\"id = ?\", id).First(user).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUserByID(c *gin.Context) {\n\tuser, err := getUserFromParams(c)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func GetUser(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tvar result User\n\tdb.FindId(id).One(&result)\n\tresult.Token = \"\"\n\treturn result\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user models.User\n\terr := models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, user)\n\t}\n}", "func (s *Database) GetUser(id string) (*UserPartner, error) {\n\tuser := &UserPartner{Id: id}\n\tc, err := s.Engine.Get(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !c {\n\t\treturn nil, errors.New(\"Khong tim thay\")\n\t}\n\treturn user, nil\n}", "func GetUser(db sqlx.Queryer, id int64) (User, error) {\n\tvar user User\n\terr := sqlx.Get(db, &user, \"select \"+externalUserFields+\" from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn user, ErrDoesNotExist\n\t\t}\n\t\treturn user, errors.Wrap(err, \"select error\")\n\t}\n\n\treturn user, nil\n}", "func (p *Postgres) GetByID(id int) (*e.User, error) {\n\tdb := p.DB\n\tuser := e.User{}\n\n\terr := db.Model(&user).Where(\"id = ?\", id).Select()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &user, nil\n}", "func GetUserByID(id uint) (models.User, error) {\n\tvar u models.User\n\tresult := database.GetPostgresDB().First(&u, id)\n\tif result.Error != nil {\n\t\treturn models.User{}, result.Error\n\t}\n\treturn u, nil\n}", "func (c *Client) GetUser(ctx context.Context, id string) (*UserResponse, error) {\n\tvar resp struct {\n\t\tUser UserResponse `json:\"user\"`\n\t}\n\n\tvariables := make(map[string]interface{})\n\tvariables[\"id\"] = id\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery User($id: String!) {\n\t\t\tuser(id: $id) {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, variables, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resp.User, nil\n}", "func (dbh *DBHandler) GetUserByID(id int) *api.User {\n\tvar user *api.User\n\tresult, err := dbh.Connection.Query(`SELECT * FROM users WHERE telegram_id = ?;`, id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer result.Close()\n\tif result.Next() {\n\t\terr := result.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tuser = &api.User{}\n\t\t}\n\t}\n\treturn user\n}", "func (context Context) GetUserByID(id string) (result *types.User, err error) {\n\n\tif id == \"\" {\n\t\tid = types.UserThis\n\t}\n\n\tresp, err := context.sendAPIGetRequest(path.Join(\"users\", id), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttype getUserByIDResponse struct {\n\t\tData types.User `json:\"data\"`\n\t}\n\trespObject := getUserByIDResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(&respObject)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"JSON decode error\")\n\t}\n\n\treturn &respObject.Data, nil\n}", "func (s *usersService) GetByID(id int) (User, error) {\n\tusr, err := s.repo.GetById(id)\n\tif err != nil {\n\t\tlog.Printf(\"error getting user: %s\\n\", err)\n\t\treturn User{}, err\n\t}\n\treturn usr, nil\n}", "func GetUser(id string) *User {\n\tif user, ok := Users[id]; ok {\n\t\treturn user\n\t}\n\treturn nil\n}", "func GetUser(id string) (gimlet.User, bool, error) {\n\tenv := cedar.GetEnvironment()\n\n\tu := &User{ID: id}\n\tu.Setup(env)\n\tif err := u.Find(); err != nil {\n\t\treturn nil, false, errors.WithStack(err)\n\t}\n\n\treturn u, time.Since(u.LoginCache.TTL) < cedar.TokenExpireAfter, nil\n}", "func GetUserByID(person *Person, id string) (err error) {\n\tif err = Config.DB.Where(\"id = ?\", id).First(person).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (serv *AppServer) GetUser(uID int) User {\n\treturn *ParseUser(serv.ServerRequest([]string{\"GetUser\", strconv.Itoa(uID)}))\n}", "func (u *UserRepository) GetByID(ID uint) (*domain.User, error) {\n\targs := u.Called(ID)\n\treturn args.Get(0).(*domain.User), args.Error(1)\n}", "func GetLpBrookUserById(id int) (v *LpBrookUser, err error) {\n\to := orm.NewOrm()\n\tv = &LpBrookUser{Id: id}\n\tif err = o.Read(v); err == nil {\n\t\treturn v, nil\n\t}\n\tif err == orm.ErrNoRows { //判断是否 是 没有找到的错误\n\t\treturn nil, nil\n\t}\n\treturn nil, err\n}", "func (u *User) GetUser(id int) error {\n\tconn, err := db.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsql := `SELECT id,username,password,name,is_admin FROM users WHERE id = $1 LIMIT 1`\n\trow := conn.QueryRow(sql, id)\n\n\terr = row.Scan(&u.ID, &u.Username, &u.Password, &u.Name, &u.IsAdmin)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c Client) GetUser(ctx context.Context, id string) (api.User, error) {\n\t// TODO (erik): Make this function handle emails properly.\n\tvar user api.User\n\tif err := c.db.GetContext(ctx, &user, \"select * from users where id = ?\", id); err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func (u *UserCtr) GetUserByid(c *gin.Context) {\n\tid,err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tuser, err := model.UserByID(u.DB,id)\n\tif err != nil {\n\t\tresp := errors.New(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, resp)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": user,\n\t})\n\treturn\n\n}", "func ReadUserByID(id int64) structs_lwh.User {\n\tempty := WriteUser(\"\", \"\", \"\", -1, -1, \"\")\n\n\tif listU.Head != nil {\n\n\t\tfor node := listU.Head; node != nil; node = node.Next() {\n\n\t\t\tif node.Value().Gid == id {\n\n\t\t\t\treturn node.Value()\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn empty\n}", "func (u UserRepository) GetByID(id int) (interface{}, error) {\n\n\tvar sqlStm = `\n\t\tSELECT\ta.id, \n\t\t\t\ta.firstname, \n\t\t\t\ta.lastname, \n\t\t\t\ta.username, \n\t\t\t\ta.email, \n\t\t\t\ta.password, \n\t\t\t\ta.timestamp, \n\t\t\t\ta.updated \n\t\tFROM reservations_user a\n\t\tWHERE a.id = $1`\n\n\tvar user models.UserModel\n\n\tif err := u.DB.QueryRow(\n\t\tsqlStm,\n\t\tid,\n\t).Scan(\n\t\t&user.ID,\n\t\t&user.FirstName,\n\t\t&user.LastName,\n\t\t&user.UserName,\n\t\t&user.Email,\n\t\t&user.Password,\n\t\t&user.Timestamp,\n\t\t&user.Updated,\n\t); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err)\n\t}\n\n\treturn user, nil\n}", "func getUserById(id int) (User, error) {\n\tkeyString := fmt.Sprintf(\"user:%d\", id)\n\tfirstName, _ := redisConn.Hget(keyString, \"firstName\")\n\tlastName, _ := redisConn.Hget(keyString, \"lastName\")\n\temail, _ := redisConn.Hget(keyString, \"email\")\n\tuser := User{id, string(firstName), string(lastName), string(email)}\n\n\tmongoUser := User{}\n\tc := mongoClient.DB(\"cg\").C(\"users\")\n\terr := c.Find(bson.M{\"id\": id}).One(&mongoUser)\n\tif err != nil {\n\t\tlog.Printf(\"couldn't find user: \", err)\n\t} else {\n\t\tlog.Printf(\"mongo user: %v\", mongoUser)\n\t}\n\n\treturn user, nil\n}", "func GetUserById(context *fiber.Ctx) error {\n\tid, err := ParseId(context)\n\n\tif err != nil {\n\t\treturn context.Status(400).JSON(&fiber.Map{\"error\": err.Error()})\n\t}\n\n\tvar user = repository.GetUserById(id)\n\n\tif user.ID == 0 {\n\t\tlog.Printf(\"user not found: %d\", id)\n\t\treturn context.Status(404).JSON(&fiber.Map{\"response\": \"not found\"})\n\t} else {\n\t\treturn context.Status(200).JSON(user)\n\t}\n}", "func GetByID(w http.ResponseWriter, r *http.Request, DB *gorm.DB) {\n\tvar dbUser User\n\tparams := mux.Vars(r)\n\tuserID := params[\"id\"]\n\t//Need to make sure that the user that is requesting user info is either the user or an admin user\n\ttoken := r.Header.Get(\"Authorization\")\n\tresult, ID := utils.VerifyJWT(token)\n\tmyID := strconv.FormatUint(uint64(ID), 10)\n\t//results := utils.IsAdmin(token, DB)\n\t//fmt.Printf(\"%v\", results)\n\tif (result && userID == myID) || isAdmin(token, DB) {\n\t\tDB.Where(\"ID = ?\", userID).First(&dbUser)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(w).Encode(dbUser)\n\t} else {\n\t\tnotauthorizedResponse := response.JsonResponse(\"Not authorized\", 409)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(notauthorizedResponse)\n\t}\n\n}", "func (s *Store) GetUser(id bson.ObjectId) (*models.User, error) {\n\tvar user models.User\n\terr := s.Users.Find(bson.M{\"_id\": id}).One(&user)\n\treturn &user, err\n}", "func (rep *UserRepository) GetByID(userID int64) (user *models.User, err error) {\n\tuser = &models.User{}\n\terr = databaseConnection.First(user, \"id = ?\", userID).Error\n\treturn\n}", "func (p *UserProvider) UserByID(id string) (*kubermaticv1.User, error) {\n\tuser := &kubermaticv1.User{}\n\tif err := p.client.Get(context.Background(), ctrlruntimeclient.ObjectKey{Name: id}, user); err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func (u *USER_DB) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM USER WHERE Idx = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUserByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar user Models.User\n\terr := Models.GetUserByID(&user, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK,gin.H{\n\t\t\t\"data\" : user,\n\t\t\t\"status\": http.StatusOK,\n\t\t})\n\t}\n}", "func (a *UserAPI) GetUserByID(ctx *gin.Context) {\n\twithID(ctx, \"id\", func(id uint) {\n\t\tif user := a.DB.GetUserByID(uint(id)); user != nil {\n\t\t\tctx.JSON(200, toExternal(user))\n\t\t} else {\n\t\t\tctx.AbortWithError(404, errors.New(\"user does not exist\"))\n\t\t}\n\t})\n}", "func GetUserByID(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"getting user by id\")\n\tid := c.Params.ByName(\"id\")\n\tvar user entity.User\n\terr := model.GetUserByID(&user, id, client)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"id\": user.ID,\n\t\t\t\"first_name\": user.FirstName,\n\t\t\t\"last_name\": user.LastName,\n\t\t\t\"username\": user.Username,\n\t\t\t\"account_created\": user.AccountCreated,\n\t\t\t\"account_updated\": user.AccountUpdated,\n\t\t})\n\t}\n}", "func GetUserByID(id int, engine *xorm.Engine) (*User, error) {\n\n\tuser := new(User)\n\tok, err := engine.Where(\"id=?\", id).Get(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif ok {\n\t\treturn user, nil\n\t}\n\treturn nil, fmt.Errorf(\"user (%d) not exist\", id)\n}", "func (u *User) Get(id string) error {\n\tsession := mongoSession.Clone()\n\tdefer session.Close()\n\tcollection := session.DB(mongoDialInfo.Database).C(usersCollectionName)\n\t// TODO: handle error\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn errors.New(\"Invalid Object ID\")\n\t}\n\tobjectID := bson.ObjectIdHex(id)\n\terr := collection.FindId(objectID).One(u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUserById(id int) (v *User, err error) {\n\to := orm.NewOrm()\n\tv = &User{Id: id}\n\tif err = o.Read(v); err == nil {\n\t\treturn v, nil\n\t}\n\treturn nil, err\n}", "func (db *Database) GetUser(id int) (*User, error) {\n\trow := db.db.QueryRow(`\n\t\tSELECT id, username, owner FROM melodious.accounts WHERE id=$1;\n\t`, id)\n\tuser := &User{}\n\terr := row.Scan(&(user.ID), &(user.Username), &(user.Owner))\n\tif err != nil {\n\t\treturn &User{}, err\n\t}\n\treturn user, nil\n}", "func GetUserByID(svc *dynamodb.DynamoDB, id string) (User, error) {\n\n\tresult, err := svc.GetItem(&dynamodb.GetItemInput{\n\t\tTableName: aws.String(UserTableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"id\": {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\n\titem := User{}\n\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &item)\n\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\n\treturn item, nil\n}", "func (u *UserModel) GetUserById(id uint64) (*UserModel, error) {\n\td := DB.Self.Where(\"id = ?\", id).First(&u)\n\tfmt.Println(\"GetUser-d\", d)\n\treturn u, d.Error\n}", "func (s *Service) GetUser(id bson.ObjectId) (User, error) {\n\tsession := s.db.Copy()\n\tdefer session.Close()\n\n\tc := session.DB(\"\").C(userCollection)\n\tvar user User\n\terr := c.FindId(id).One(&user)\n\tif err != nil {\n\t\treturn user, fmt.Errorf(\"user not found: %v\", err)\n\t}\n\n\treturn user, nil\n}", "func GetUserByID(c *gin.Context) {\n\tvar user, condition Users\n\n\tuserID, _ := strconv.ParseUint(c.Param(\"id\"), 10, 64)\n\tcondition.ID = uint(userID)\n\tuser.FindOne(condition)\n\n\tif user.ID == 0 {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"message\": \"user is not found\",\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": http.StatusOK,\n\t\t\t\"data\": user,\n\t\t})\n\t}\n}", "func (dp *dataProvider) GetUserByID(user *models.User) error {\n\t//Where(\"id = ?id\")\n\treturn wrapError(dp.db.Select(user))\n}", "func (prof *Profiles) ByID(id_ interface{}) (*User, error) {\n\tvar id string\n\tswitch x := id_.(type) {\n\tcase int64:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase int:\n\t\tid = fmt.Sprintf(\"%d\", x)\n\tcase string:\n\t\tid = x\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid id, please provide a string or int(64)\")\n\t}\n\n\tbody, _, err := prof.insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: fmt.Sprintf(urlUserByID, id),\n\t\t},\n\t)\n\tif err == nil {\n\t\tresp := userResp{}\n\t\terr = json.Unmarshal(body, &resp)\n\t\tif err == nil {\n\t\t\tuser := &resp.User\n\t\t\tuser.insta = prof.insta\n\t\t\treturn user, err\n\t\t}\n\t}\n\treturn nil, err\n}", "func (us *usersService) GetUserByID(userID int64) (*users.User, *errors.RestError) {\n\tvar err *errors.RestError\n\tvar user = users.User{ID: userID}\n\tif err = user.Get(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &user, nil\n}", "func (u *User) GetUserByID(id string) *User {\n\tvar result User\n\n\terr := database.DB.Where(\"id = ?\", id).First(&result).Error\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &result\n}", "func (m *postgresDBRepo) GetUserById(id int) (models.User, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `select id, first_name, last_name, email, password,\n\t\t access_level, created_at, updated_at\n\t\tfrom users where id = $1`\n\n\trow := m.DB.QueryRowContext(ctx, query, id)\n\tvar u models.User\n\terr := row.Scan(&u.ID, &u.FirstName, &u.LastName, &u.Email, &u.Password, &u.AccessLevel, &u.CreatedAt, &u.UpdatedAt)\n\tif err != nil {\n\t\treturn u, err\n\t}\n\n\treturn u, nil\n}", "func GetUserByID(id int64) *User {\n\tuser := new(User)\n\trow := DB.QueryRow(\"SELECT * from user WHERE id=?\", id)\n\terr := row.Scan(&user.ID, &user.Email, &user.Password, &user.Fullname, &user.TSLastLogin, &user.TSCreate, &user.TSUpdate, &user.Permission)\n\tif err != nil {\n\t\tlog.Errorln(\"User SELECT by ID Err: \", err)\n\t\treturn nil\n\t}\n\treturn user\n}", "func (u *MyUserModel) GetById(id interface{}) error {\n\terr := dbmap.SelectOne(u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetClientByID(id int) (user User, err error) {\n\tuser = User{}\n\terr = Db.QueryRow(\"select * from user where id = $1\", id).Scan(&user.ID, &user.Name, &user.Email, &user.Password, &user.Status, &user.ActiveUntil, &user.Image, &user.Role)\nfmt.Println(user)\n\n\treturn\n}", "func (tx *Tx) GetUserByID(userID string) (*User, error) {\n\tvar user User\n\terr := tx.Get(&user, \"SELECT * FROM appuser WHERE id = $1;\", userID)\n\tif err != nil {\n\t\treturn nil, errors.InternalError(err)\n\t}\n\treturn &user, err\n}", "func (r *UserRepository) GetByID(ctx context.Context, id interface{}) (ent entity.User, err error) {\n\terr = r.DB(ctx).Take(&ent, id).Error\n\treturn ent, err\n}", "func UserByIDGet(c *gin.Context) {\n\tid, _ := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\tlog.Info(\"UserByIDGet \", id)\n\tm := model.UserByID(uint(id))\n\tginutils.WriteGinJSON(c, http.StatusOK, m)\n}", "func (_ *User) GetById(id uint) (interface{}, error) {\n\tuser := User{}\n\tif disableGetUserById || getTestDb().Where(\"id = ?\", id).Find(&user).RecordNotFound() {\n\t\treturn &user, errors.New(\"User not found\")\n\t}\n\treturn &user, nil\n}", "func (us *Users) Get(id int64) (*User, error) {\n\texp := fmt.Sprintf(\"user_id=%v\", id)\n\n\treturn getUserWhere(exp)\n}", "func (c *Client) GetUser(id string) (*dto.User, error) {\n\tvar user *dto.User\n\n\tr, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"users/%s\", id),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\t_, err = c.Do(r, &user)\n\treturn user, err\n}", "func getUser(req *http.Request) *grepbook.User {\n\tif rv := context.Get(req, UserKeyName); rv != nil {\n\t\tres := rv.(*grepbook.User)\n\t\treturn res\n\t}\n\treturn nil\n}", "func GetUser(id int) (User, error) {\n\tvar user User\n\trow := DB.QueryRow(\"select id, realname, username, email from users where id = $1\", id)\n\terr := row.Scan(&user.ID, &user.Realname, &user.Username, &user.Email)\n\treturn user, err\n}", "func GetUserByID(userID int64) (model.User, error) {\n\tGetConnection()\n\tvar foundUser model.User\n\tdb.Where(\"id = ?\", userID).First(&foundUser)\n\treturn foundUser, nil\n}", "func GetUserWithToken(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tvar result User\n\tdb.FindId(id).One(&result)\n\tresult.Payees = []bson.ObjectId{}\n\treturn result\n}", "func (*userRepo) ByID(userID string) (*contact.User, error) {\n\n\t// Use new restclient\n\trest := restclient.NewRestClient(\"http://api.internal.ml.com\")\n\tusersURL := fmt.Sprintf(\"/users/%s\", userID)\n\n\t// Do get request from users\n\tbytes, err := rest.DoGet(usersURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make object from response\n\tuserFromAPI := &user{}\n\tif err := json.Unmarshal(bytes, &userFromAPI); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &contact.User{\n\t\tName: userFromAPI.NickName,\n\t\tEmail: userFromAPI.Email,\n\t}, nil\n}", "func (d *DB) GetUser(id int) (User, error) {\n\tvar user User\n\terr := d.db.Find(&user, id).Error\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func GetUserByID(c echo.Context) error {\n\tID := c.Param(\"id\")\n\tdb := db.ConnectDB()\n\tusers := []models.User{}\n\tdb.Where(\"id= ?\", ID).Find(&users)\n\n\tif users == nil {\n\t\treturn c.JSON(http.StatusNotFound, \"Data Not Found\")\n\t}\n\n\treturn c.JSON(http.StatusOK, users)\n}", "func (s *Service) View(id uint) (*model.User, error) {\n\tuser, err := s.udb.View(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func GetUserByID(id int) (*UserByID, error) {\n\tres := &UserByID{}\n\terr := urlToStruct(fmt.Sprintf(\"/users/userbyid/%d\", id), res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (s UserStorage) GetOne(id string) (model.User, error) {\n\tintID, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\terrMessage := fmt.Sprintf(\"User id must be an integer: %s\", id)\n\t\treturn model.User{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusBadRequest)\n\t}\n\tvar user model.User\n\tstr := []string{GET_ALL, \"where users.user_id = $1 limit 1\"}\n\tGET_ONE := strings.Join(str, \" \")\n\terror := s.db.SelectOne(&user, GET_ONE, intID)\n\tif error == nil {\n\t\treturn user, nil\n\t} else {\n\t\treturn model.User{}, fmt.Errorf(\"User for id %s not found\", id)\n\t}\t\n\t// return s.getOneWithAssociations(intID)\n}", "func (r *Repo) GetUser(_ context.Context, id int64) (entities.User, error) {\n\tvar u entities.User\n\terr := r.Get(&u, \"SELECT * FROM users WHERE id = $1\", id)\n\tif err != nil {\n\t\treturn entities.User{}, fmt.Errorf(\"error getting user: %w\", err)\n\t}\n\treturn u, nil\n}", "func (*userSVC) find(id int) (*user, error) {\n\treturn &user{id: id, name: \"Anna Walker\"}, nil\n}", "func (r *UserRepoPostgres) GetByID(ID int64) (*entity.User, error) {\n\tvar (\n\t\tuser entity.User\n\t\terr error\n\t)\n\terr = r.readDB.QueryRow(\"select id, fullname, username, email, password, status, created_at from users where id = $1\", ID).Scan(&user.ID, &user.FullName, &user.UserName, &user.Email, &user.Password, &user.Status, &user.CreatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &user, nil\n}", "func (c *Client) GetUserByID(id string) (User, error) {\n\tvar (\n\t\turi = \"/rest/users/\" + id\n\t\tqueryParams = createQuery(&map[string]string{\n\t\t\t\"id\": id,\n\t\t})\n\t\tuser User\n\t)\n\n\tif id == \"\" {\n\t\treturn user, fmt.Errorf(\"id must not be empty\")\n\t}\n\n\tresponse, err := c.RestAPICall(rest.GET, uri, queryParams, nil)\n\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\tif err := json.Unmarshal([]byte(response), &user); err != nil {\n\t\treturn user, apiResponseError(response, err)\n\t}\n\n\treturn user, err\n}", "func (config *CrocConfig) GetUserByExternal(externalID string) (User, error) {\n\tvar user User\n\tendpoint := fmt.Sprintf(\"users/%s\", externalID)\n\n\t// get json bytes from the panel.\n\tubytes, err := config.queryPanelAPI(endpoint, \"get\", nil)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(ubytes, &user)\n\tif err != nil {\n\t\treturn user, err\n\t}\n\n\treturn user, nil\n}", "func GetUserByID(userID string) (*models.User, error) {\n\n\t// Connect to db\n\tdb, err := models.Connet()\n\tif err != nil {\n\t\tlog.Fatal(\"db connect error: \", err)\n\t}\n\tdefer db.Close()\n\n\tuser := new(models.User)\n\n\terr = db.QueryRow(\"SELECT id, account, nickname, email, created_by FROM users WHERE rec_status = 1 AND id = ?\", userID).\n\t\tScan(&user.ID, &user.Account, &user.Nickname, &user.Email, &user.CreateBy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func (s *UserService) GetUserByID(id interface{}) (*User, error) {\n\tuser, err := s.usersRepository.GetByID(id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}", "func (s *Client) Get(username, name string) (string, error) {\n\tvar value string\n\trow := s.db.QueryRow(`SELECT value FROM user_variables WHERE user_id = (SELECT id FROM users WHERE username = ?) AND key = ?;`, username, name)\n\tswitch err := row.Scan(&value); err {\n\tcase sql.ErrNoRows:\n\t\treturn \"\", fmt.Errorf(\"no %s variable found for user %s\", name, username)\n\tcase nil:\n\t\treturn value, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unknown sql error\")\n\t}\n}", "func GetUser(id int64) (*User, error) {\n\tuser := User{}\n\terr := meddler.QueryRow(db, &user, userFindIdStmt, id)\n\treturn &user, err\n}", "func (u *User) GetById(id interface{}) error {\n\tif err := DB().Where(\"id = ?\", id).First(&u).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetUserByID(db *sql.DB, ID int) (models.UserResponse, error) {\n\trows, err := db.Query(\"SELECT id, username, createdAt, email FROM users WHERE id = ?\", ID)\n\tif err != nil {\n\t\treturn models.UserResponse{}, err\n\t}\n\n\tif rows.Next() {\n\t\tvar id int\n\t\tvar username string\n\t\tvar createdAt time.Time\n\t\tvar email string\n\t\terr = rows.Scan(&id, &username, &createdAt, &email)\n\t\tif err != nil {\n\t\t\treturn models.UserResponse{}, err\n\t\t}\n\n\t\treturn models.UserResponse{ID: id, Username: username, CreatedAt: createdAt, Email: email}, nil\n\t}\n\treturn models.UserResponse{}, ErrUserNotFound\n}", "func (r *Repository) Get(userID int64) (*pb.User, error) {\n\treturn r.get(r.conn.NewSession(nil), userID)\n}", "func GetUserByID(c echo.Context) error {\n\tuser, err := model.GetByID(1)\n\tif err != nil {\n\t\treturn c.String(http.StatusNotFound, \"user not found\")\n\t}\n\treturn c.JSON(http.StatusOK, user)\n}", "func GetUserByID(user *entity.User, id string, client *statsd.Client) (err error) {\n\tt := client.NewTiming()\n\tif err = config.DB.Where(\"id = ?\", id).First(&user).Error; err != nil {\n\t\treturn err\n\t}\n\tt.Send(\"get_user_by_id.query_time\")\n\treturn nil\n}", "func GetUser(Id int32) (record *User, err error) {\n\trecord = &User{}\n\tif err = gdb.GetDB().First(record, Id).Error; err != nil {\n\t\terr = ErrNotFound\n\t\treturn record, err\n\t}\n\n\treturn record, nil\n}", "func (uc UserController) getSingleUserbyID(response http.ResponseWriter, request *http.Request, parameters httprouter.Params) {\n\tresponse.Header().Add(\"content-type\", \"application/json\")\n\tid_string := parameters.ByName(\"id\")\n\n\tid, _ := primitive.ObjectIDFromHex(id_string)\n\tvar user Users\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\terr := uc.collection.FindOne(ctx, bson.M{\"_id\": id}).Decode(&user)\n\tif err != nil {\n\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\tresponse.Write([]byte(`{\"message: \"` + err.Error() + `\"}\"`))\n\t\treturn\n\t}\n\t// Decrypting the password\n\t// password := []byte(user.Password)\n\t// key := []byte(\"This is a key for the very secret password\")\n\t// password, _ = decrypt(key, password)\n\t// user.Password = string(password)\n\t//\n\tjson.NewEncoder(response).Encode(user)\n}", "func GetUserBySlackID(id string) *User {\n\tstmt, err := db.Prepare(\"select first, last, slack, pronounce from users where slack = ?\")\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"can't select user\")\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\tvar (\n\t\tfirst string\n\t\tlast string\n\t\tslack string\n\t\tpronounce string\n\t)\n\terr = stmt.QueryRow(id).Scan(&first, &last, &slack, &pronounce)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"can't query user\")\n\t\treturn nil\n\t}\n\n\treturn &User{\n\t\tFirst: first,\n\t\tLast: last,\n\t\tSlack: slack,\n\t\tPronounce: pronounce,\n\t}\n}", "func GetByID(id uint64) (*User, error) {\n\treturn getBy(\"id\", strconv.FormatUint(id, 10))\n}", "func GetUser(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *UserState, opts ...pulumi.ResourceOption) (*User, error) {\n\tvar resource User\n\terr := ctx.ReadResource(\"gcp:sql/user:User\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (u *UserService) GetUser(id string) (*User, error) {\n\tuser := &User{}\n\terr := u.QueryRow(\"SELECT id, name, phone, email, password FROM users WHERE id=$1 LIMIT 1\", id).Scan(&user.ID, &user.Name, &user.Phone, &user.Email, &user.HashedPassword)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}", "func GetUser(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *UserState, opts ...pulumi.ResourceOption) (*User, error) {\n\tvar resource User\n\terr := ctx.ReadResource(\"alicloud:bastionhost/user:User\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (u UserModel) GetUserByID(id int64) (*User, error) {\n\terr := safelyConnect()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Database connection never established.\")\n\t}\n\tstmt, err := connection.Prepare(\n\t\t\"select id, name, password, salt, qr_secret from users where id=?\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\trows, err := stmt.Query(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar toRet *User = nil\n\tfor rows.Next() {\n\t\tif toRet != nil {\n\t\t\treturn toRet, fmt.Errorf(\"There should only be one user for name: '%s'.\", toRet.Name)\n\t\t}\n\t\tvar id int64\n\t\tvar name, password, salt, qr_secret string\n\t\terr := rows.Scan(&id, &name, &password, &salt, &qr_secret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttoRet = &User{id, name, password, salt, qr_secret}\n\t}\n\treturn toRet, nil\n}", "func (es *ExpenseStoreSQL) GetUser(id int) *User {\n\tvar user *User\n\n\trows, err := es.Query(\"SELECT * FROM users WHERE user_id = ?\", id)\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar (\n\t\tuserID int64\n\t\tfirstName string\n\t\tlastName string\n\t\temail string\n\t)\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(&userID, &firstName, &lastName, &email); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tuser = &User{userID, firstName, lastName, email}\n\t}\n\n\treturn user\n}", "func GetUser(id bson.ObjectId) (User, error) {\n\tvar (\n\t\tuser User\n\t\terr error\n\t)\n\n\tc := newUserCollection()\n\tdefer c.Close()\n\n\terr = c.Session.Find(bson.M{\"_id\": id}).One(&user)\n\treturn user, err\n}", "func (t TestRepo) GetUserByExternalID(id string) (*User, error) {\n\tt.ArgsIn[GetUserByExternalIDMethod][0] = id\n\tif specialFunc, ok := t.SpecialFuncs[GetUserByExternalIDMethod].(func(id string) (*User, error)); ok && specialFunc != nil {\n\t\treturn specialFunc(id)\n\t}\n\tvar user *User\n\tif t.ArgsOut[GetUserByExternalIDMethod][0] != nil {\n\t\tuser = t.ArgsOut[GetUserByExternalIDMethod][0].(*User)\n\t}\n\tvar err error\n\tif t.ArgsOut[GetUserByExternalIDMethod][1] != nil {\n\t\terr = t.ArgsOut[GetUserByExternalIDMethod][1].(error)\n\t}\n\treturn user, err\n}", "func (ss *SQLStore) GetByID(id int64) (*User, error) {\n\trows, err := ss.db.Query(\"select id, Email, PassHash, UserName, FirstName, LastName, PhotoURL from USERS\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to query.\")\n\t}\n\n\tdefer rows.Close()\n\n\tusers := User{}\n\n\tfor rows.Next() {\n\t\t// Scans row into users struct.\n\t\tif err := rows.Scan(&users.ID, &users.Email,\n\t\t\t&users.PassHash, &users.UserName, &users.FirstName,\n\t\t\t&users.LastName, &users.PhotoURL); err != nil {\n\t\t\treturn nil, errors.New(\"Error scanning row.\")\n\t\t}\n\n\t\t// checks the ID, and if it matches, return that user.\n\t\tif users.ID == id {\n\t\t\treturn &users, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"User with ID not found.\")\n}", "func (r *PostgresUserRepository) GetUser(id uuid.UUID) (models.User, error) {\n\tuser := new(models.User)\n\n\trow := r.db.QueryRow(\"SELECT * FROM user WHERE id=?\", id)\n\terr := row.Scan(&user.Id, &user.Email, &user.Name, &user.NotificationEndpoint)\n\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\treturn *user, err\n\tcase err != nil:\n\t\tlog.Fatal(err)\n\t\treturn *user, err\n\t}\n\n\tif !user.Validate() {\n\t\terr = errors.New(\"User is Malformed\")\n\t}\n\n\treturn *user, nil\n}", "func (r postgresRepository) GetUser(ctx context.Context, userID int) (models.User, error) {\n\tquery := `SELECT * FROM users WHERE id = $1`\n\n\trows, err := r.pool.Query(ctx, query, userID)\n\tif err != nil {\n\t\treturn models.User{}, err\n\t}\n\n\tuser := models.User{}\n\n\terr = rows.Scan(&user.UserID, &user.Email, &user.Name, &user.Password, &user.Type, &user.CreateAt)\n\tif err != nil {\n\t\treturn models.User{}, err\n\t}\n\n\treturn user, nil\n}", "func (us *UserService) GetByID(ctx context.Context, id string) (user.User, 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\tus.log.Error(err)\n\t\treturn user.User{}, response.ErrInvalidID\n\t}\n\n\tu, err := us.repository.GetByID(ctx, objectID)\n\tif err != nil {\n\t\tus.log.Error(err)\n\t\treturn user.User{}, err\n\t}\n\n\treturn u, nil\n}", "func (s *Service) GetByID(id int) (*User, error) {\n\t// Try to pull this User from the database.\n\tdbm, err := s.db.Users.GetByID(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new User.\n\tuser := &User{\n\t\tID: dbm.ID,\n\t\tEmail: dbm.Email,\n\t\tPassword: dbm.Password,\n\t}\n\n\treturn user, nil\n}" ]
[ "0.6548018", "0.65126157", "0.63681734", "0.636242", "0.63448846", "0.6291625", "0.62620175", "0.6243576", "0.6231236", "0.62088627", "0.6192227", "0.6181659", "0.6157036", "0.61529136", "0.6151022", "0.61471826", "0.61314756", "0.60998666", "0.6082055", "0.60755104", "0.60728085", "0.60619974", "0.6056411", "0.6054641", "0.6050052", "0.6045493", "0.6035216", "0.6019566", "0.6012491", "0.60055536", "0.6004505", "0.6002084", "0.599794", "0.5989239", "0.5985616", "0.59738237", "0.59724134", "0.59688866", "0.59492475", "0.59484184", "0.5945962", "0.5944477", "0.59384847", "0.59353805", "0.59319675", "0.59311396", "0.5930794", "0.59210414", "0.591298", "0.5911811", "0.59108984", "0.5908817", "0.58973104", "0.5890896", "0.58908445", "0.5885318", "0.58843946", "0.5883184", "0.5870436", "0.58676505", "0.5863107", "0.58602804", "0.58548766", "0.58434945", "0.58414805", "0.58411896", "0.58340657", "0.5821457", "0.5820745", "0.5817829", "0.5817796", "0.5815412", "0.58072037", "0.5803926", "0.5801838", "0.5796711", "0.57837325", "0.57810014", "0.57768553", "0.57733864", "0.5769095", "0.5767539", "0.5767369", "0.5765536", "0.57651377", "0.5765059", "0.57607925", "0.57585776", "0.57523286", "0.5752076", "0.5751699", "0.5751312", "0.5750906", "0.57385904", "0.57381576", "0.57333606", "0.57319343", "0.5730573", "0.57239765", "0.57208925" ]
0.69131124
0
List VPN Users for this environment
func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) List() ([]RemoteAccessVpnUser, error) { data, err := remoteAccessVpnUserApi.entityService.List(map[string]string{}) if err != nil { return nil, err } return parseRemoteAccessVpnUserList(data), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (us *UserService) List(ctx context.Context) ([]*resources.User, error) {\n\tdoc, err := us.list(ctx, \"one.userpool.info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\telements := doc.FindElements(\"USER_POOL/USER\")\n\n\tusers := make([]*resources.User, len(elements))\n\tfor i, e := range elements {\n\t\tusers[i] = resources.CreateUserFromXML(e)\n\t}\n\n\treturn users, nil\n}", "func listUsersVerbose(client *chef.Client) map[string]chef.UserVerboseResult {\n\tuserList, err := client.Users.VerboseList()\n\tfmt.Printf(\"VERBOSE LIST %+v\\n\", userList)\n\tif err != nil {\n\t\tfmt.Println(\"Issue listing verbose users:\", err)\n\t}\n\treturn userList\n}", "func (a *Server) ListUsers(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"lists all users\")\n}", "func (cli *OpsGenieUserV2Client) List(req userv2.ListUsersRequest) (*userv2.ListUsersResponse, error) {\n\tvar response userv2.ListUsersResponse\n\terr := cli.sendGetRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func ListAllUsers() ([]User, error) {\n\tusers := []User{}\n\tfor {\n\t\tpwent, err := C.getpwent()\n\t\tif pwent == nil {\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tusers = append(users, pwentToUser(pwent))\n\t}\n\tC.endpwent()\n\treturn users, nil\n}", "func (vns *VirtualNetworkService) ListAllForUser(ctx context.Context,\n\tuser resources.User) ([]*resources.VirtualNetwork, error) {\n\tuserID, err := user.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.list(ctx, userID, pageOffsetDefault, pageSizeDefault)\n}", "func listUsers(client *chef.Client, filters ...string) map[string]string {\n\tvar filter string\n\tif len(filters) > 0 {\n\t\tfilter = filters[0]\n\t}\n\tuserList, err := client.Users.List(filter)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Issue listing users:\", err)\n\t}\n\treturn userList\n}", "func (s *UserServer) List(ctx context.Context, in *pb.UserQuery) (*pb.UsersInfo, error) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tutils.GetLog().Error(\"rpc.user.List error: %+v\", err)\n\t\t}\n\t}()\n\n\tconfig := &users.Config{\n\t\tPageNum: int(in.Num),\n\t\tPageSize: int(in.Size),\n\t\tSearch: in.Search,\n\t\tIDs: in.IDs,\n\t}\n\n\tusers := users.NewUsers(config)\n\tif err = users.Do(); err != nil {\n\t\treturn nil, errors.New(users.ErrorCode().String())\n\t}\n\n\tsrvUsers := users.Users()\n\tcount := users.Count()\n\n\tvar pbUsers []*pb.UserInfo\n\tfor _, srvUser := range srvUsers {\n\t\tpbUser := srvUserToPbUser(srvUser)\n\t\tpbUsers = append(pbUsers, pbUser)\n\t}\n\n\treturn &pb.UsersInfo{Users: pbUsers, TotalNum: count}, nil\n}", "func (up *userProvider) List(ctx context.Context) ([]models.User, error) {\n\tusers, err := up.userStore.List(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (c *UsersController) List(ctx *app.ListUsersContext) error {\n\treturn proxy.RouteHTTP(ctx, c.config.GetAuthShortServiceHostName())\n}", "func (s *Shell) ListUsers(_ *cli.Context) (err error) {\n\tresp, err := s.HTTP.Get(\"/v2/users/\", nil)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := resp.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(resp, &AdminUsersPresenters{})\n}", "func getUserList() string {\n\tvar userlist string\n\tfmt.Println(len(Users))\n\tfor key, value := range Users {\n\t\tfmt.Println(\"key\", key, \"value\", value)\n\t\tuserlist = userlist + key + \"|\"\n\n\t}\n\treturn strings.TrimRight(userlist, \"|\")\n}", "func (t *CassandraUpgradeTest) listUsers() ([]string, error) {\n\tr, err := http.Get(fmt.Sprintf(\"http://%s/list\", net.JoinHostPort(t.ip, \"8080\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\tif r.StatusCode != http.StatusOK {\n\t\tb, err := io.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(string(b))\n\t}\n\tvar names []string\n\tif err := json.NewDecoder(r.Body).Decode(&names); err != nil {\n\t\treturn nil, err\n\t}\n\treturn names, nil\n}", "func (m *Mgr) List(ctx context.Context) ([]*User, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tusers, err := m.list(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// hide passwords\n\tfor _, u := range users {\n\t\tu.Password = \"\"\n\t}\n\treturn users, nil\n}", "func (h *ServiceUsersHandler) List(ctx context.Context, project, serviceName string) ([]*ServiceUser, error) {\n\t// Aiven API does not provide list operation for service users, need to get them via service info instead\n\tservice, err := h.client.Services.Get(ctx, project, serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service.Users, nil\n}", "func (vns *VirtualNetworkService) ListForUser(ctx context.Context, user resources.User, pageOffset int,\n\tpageSize int) ([]*resources.VirtualNetwork, error) {\n\tuserID, err := user.ID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vns.list(ctx, userID, (pageOffset-1)*pageSize, -pageSize)\n}", "func (s *Service) List() *ListOp {\n\treturn &ListOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"users\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func (s repoUserService) List(path string) ([]*api.User, error) {\n\trepoPath, err := api.NewRepoPath(path)\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\tusers, err := s.client.httpClient.ListRepoUsers(repoPath.GetNamespaceAndRepoName())\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\treturn users, nil\n}", "func (s *Service) List(c context.Context, req *user.ListReq) (*user.ListResp, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := s.auth.GetUser(c)\n\n\tlimit, offset := query.Paginate(req.Limit, req.Page)\n\n\tusers, err := s.udb.List(\n\t\ts.dbcl.WithContext(c),\n\t\tquery.ForTenant(u, req.TenantId),\n\t\tlimit,\n\t\toffset,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pu []*user.Resp\n\tfor _, v := range users {\n\t\tpu = append(pu, v.Proto())\n\t}\n\n\treturn &user.ListResp{Users: pu}, nil\n}", "func ListUsers(w http.ResponseWriter, r *http.Request) {\n\tusers, err := dal.GetUsers(\"\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcommon.WriteResponse(w, users)\n}", "func ListUsers(db *pg.DB) ([]*models.User, error) {\n\tvar users []*models.User\n\n\t_, err := db.Query(&users, `SELECT * FROM Users`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Print names and PK\n\tfor i, n := range users {\n\t\tfmt.Println(i, n.UserName, n.Password, n.Email)\n\t}\n\treturn users, nil\n}", "func ListUser(url, token string) {\n\tres, err := handleReadRequest(url, http.MethodGet, token)\n\tif err != nil {\n\t\tfmt.Println(\"Error\\n\")\n\t}\n\n\tvar apiResponse ListUsers\n\terr = json.Unmarshal(res, &apiResponse)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Print(\"List of users:\\n\")\n\tfor i:=0; i < len(apiResponse.Users); i++ {\n\t\tfmt.Print(apiResponse.Users[i],\"\\n\")\n\t}\n}", "func (u *UsersController) List(ctx *gin.Context) {\n\tcriteria := u.buildCriteria(ctx)\n\n\tvar listAsAdmin bool\n\tif isTatAdmin(ctx) {\n\t\tlistAsAdmin = true\n\t} else {\n\t\tuser, e := PreCheckUser(ctx)\n\t\tif e != nil {\n\t\t\tctx.AbortWithError(http.StatusInternalServerError, e)\n\t\t\treturn\n\t\t}\n\t\tlistAsAdmin = user.CanListUsersAsAdmin\n\t}\n\tcount, users, err := userDB.ListUsers(criteria, listAsAdmin)\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tout := &tat.UsersJSON{\n\t\tCount: count,\n\t\tUsers: users,\n\t}\n\tctx.JSON(http.StatusOK, out)\n}", "func (c *VirtLauncherClient) GetUsers() (v1.VirtualMachineInstanceGuestOSUserList, error) {\n\tuserList := []v1.VirtualMachineInstanceGuestOSUser{}\n\n\trequest := &cmdv1.EmptyRequest{}\n\tctx, cancel := context.WithTimeout(context.Background(), shortTimeout)\n\tdefer cancel()\n\n\tuResponse, err := c.v1client.GetUsers(ctx, request)\n\tvar response *cmdv1.Response\n\tif uResponse != nil {\n\t\tresponse = uResponse.Response\n\t}\n\n\tif err = handleError(err, \"GetUsers\", response); err != nil {\n\t\treturn v1.VirtualMachineInstanceGuestOSUserList{}, err\n\t}\n\n\tif uResponse.GetGuestUserListResponse() != \"\" {\n\t\tif err := json.Unmarshal([]byte(uResponse.GetGuestUserListResponse()), &userList); err != nil {\n\t\t\tlog.Log.Reason(err).Error(\"error unmarshalling guest user list response\")\n\t\t\treturn v1.VirtualMachineInstanceGuestOSUserList{}, err\n\t\t}\n\t}\n\n\tguestUserList := v1.VirtualMachineInstanceGuestOSUserList{\n\t\tItems: userList,\n\t}\n\n\treturn guestUserList, nil\n}", "func (e Endpoints) ListUsers(ctx context.Context, token string, args map[string]string) (users []registry.User, err error) {\n\trequest := ListUsersRequest{\n\t\tArgs: args,\n\t\tToken: token,\n\t}\n\tresponse, err := e.ListUsersEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListUsersResponse).Users, response.(ListUsersResponse).Err\n}", "func (a *API) listUsers(w http.ResponseWriter, req *http.Request) {\n\tvar (\n\t\tpath string\n\t\tusers cmap.ConcurrentMap\n\t\twg sync.WaitGroup\n\t)\n\t// Force reload policy to get the newest\n\t_ = a.policyEngine.LoadPolicy()\n\tif username := req.FormValue(\"name\"); username != \"\" {\n\t\tpath = common.Path(model.DefaultUsersPrefix, common.Hash(username, crypto.MD5))\n\t} else {\n\t\tpath = common.Path(model.DefaultUsersPrefix)\n\t}\n\tresp, err := a.etcdcli.DoGet(path, etcdv3.WithPrefix(),\n\t\tetcdv3.WithSort(etcdv3.SortByKey, etcdv3.SortAscend))\n\tif err != nil {\n\t\ta.respondError(w, apiError{\n\t\t\tcode: http.StatusInternalServerError,\n\t\t\terr: err,\n\t\t})\n\t\treturn\n\t}\n\tusers = cmap.New()\n\tfor _, ev := range resp.Kvs {\n\t\twg.Add(1)\n\t\tgo func(evv []byte) {\n\t\t\tdefer wg.Done()\n\t\t\tvar (\n\t\t\t\tu model.User\n\t\t\t\tp [][]string\n\t\t\t)\n\t\t\t_ = json.Unmarshal(evv, &u)\n\t\t\tp = a.policyEngine.GetFilteredPolicy(0, u.Username)\n\t\t\tfor i, v := range p {\n\t\t\t\t// The first element is username, so just remove it.\n\t\t\t\tp[i] = v[1:]\n\t\t\t}\n\t\t\tusers.Set(u.Username, p)\n\t\t}(ev.Value)\n\t}\n\twg.Wait()\n\ta.respondSuccess(w, http.StatusOK, users)\n}", "func (a *AdminAPI) ListUsers(ctx context.Context) ([]string, error) {\n\tvar users []string\n\treturn users, a.sendAny(ctx, http.MethodGet, usersEndpoint, nil, &users)\n}", "func (k *Keystone) ListUsersAPI(c echo.Context) error {\n\tclusterID := c.Request().Header.Get(xClusterIDKey)\n\tif ke := getKeystoneEndpoints(clusterID, k.endpointStore); len(ke) > 0 {\n\t\treturn k.proxyRequest(c)\n\t}\n\t_, err := k.validateToken(c.Request())\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = k.setAssignment(clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := c.QueryParam(\"name\")\n\tif n != \"\" {\n\t\tfor _, u := range k.Assignment.ListUsers() {\n\t\t\tif u.Name == n {\n\t\t\t\treturn c.JSON(http.StatusOK, &UserListResponse{\n\t\t\t\t\tUsers: []*keystone.User{u},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\treturn c.JSON(http.StatusOK, &UserListResponse{\n\t\t\tUsers: nil,\n\t\t})\n\t}\n\treturn c.JSON(http.StatusOK, &UserListResponse{\n\t\tUsers: k.Assignment.ListUsers(),\n\t})\n}", "func (m *userManager) UserList() []string {\n\tuserList := make([]string, 0)\n\tm.db.View(func(tx *bolt.Tx) error {\n\t\tusers := tx.Bucket(m.usersBucket)\n\t\treturn users.ForEach(func(username, v []byte) error {\n\t\t\tuserList = append(userList, string(username))\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn userList\n}", "func (c *UsersClient) List(ctx context.Context, filter string) (*[]models.User, int, error) {\n\tparams := url.Values{}\n\tif filter != \"\" {\n\t\tparams.Add(\"$filter\", filter)\n\t}\n\tresp, status, _, err := c.BaseClient.Get(ctx, base.GetHttpRequestInput{\n\t\tValidStatusCodes: []int{http.StatusOK},\n\t\tUri: base.Uri{\n\t\t\tEntity: \"/users\",\n\t\t\tParams: params,\n\t\t\tHasTenantId: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tvar data struct {\n\t\tUsers []models.User `json:\"value\"`\n\t}\n\tif err := json.Unmarshal(respBody, &data); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &data.Users, status, nil\n}", "func (store *Storage) ListUsers() ([]string, error) {\n\treturn store.Back.ListUsers()\n}", "func (c *Client) ListUsers() (*http.Response, error) {\n\treturn c.get(\"/user/listusers\", nil)\n}", "func (UserService) List(ctx context.Context, gdto dto.GeneralListDto) ([]model.User, int64) {\n\tcols := \"*\"\n\tgdto.Q, cols = dataPermService.DataPermFilter(ctx, \"users\", gdto)\n\treturn userDao.List(gdto, cols)\n}", "func (r Virtual_Guest) GetUsers() (resp []datatypes.User_Customer, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getUsers\", nil, &r.Options, &resp)\n\treturn\n}", "func (rep *UserRepo) List(ctx context.Context) ([]*User, error) {\n\tu := []*User{}\n\terr := rep.db.Query(\n\t\tctx,\n\t\trep.db.Select(\"*\").From(rep.table()),\n\t).Decode(&u)\n\treturn u, err\n}", "func (m *Mgr) list(ctx context.Context) (users []*User, err error) {\n\trows, err := m.db.QueryContext(ctx, `SELECT username, password FROM users`)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar u User\n\t\tif err = rows.Scan(&u.Username, &u.Password); err != nil {\n\t\t\treturn\n\t\t}\n\t\tusers = append(users, &u)\n\t}\n\treturn users, rows.Err()\n}", "func (c client) UserList() ([]*User, error) {\n\tdata := url.Values{}\n\tdata.Set(\"token\", c.conf.Token)\n\tres, err := http.PostForm(\"https://slack.com/api/users.list\", data)\n\tif err != nil {\n\t\treturn []*User{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar list userlist\n\tif err = json.NewDecoder(res.Body).Decode(&list); err != nil {\n\t\treturn []*User{}, err\n\t}\n\treturn list.Members, nil\n}", "func (r repository) List(ctx context.Context, list *ListUsersRequest) ([]model.User, error) {\n\tusers := make([]model.User, 0)\n\toffset := (list.Page - 1) * list.Limit\n\terr := r.db.Select(&users, ListUsersSQL, offset, list.Limit)\n\tif err != nil {\n\t\tr.logger.Errorf(\"Failed to select users %s\", err)\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func listUser(ctx sdk.Context, k Keeper) ([]byte, error) {\n\tvar userList []types.User\n\tstore := ctx.KVStore(k.storeKey)\n\titerator := sdk.KVStorePrefixIterator(store, []byte(types.UserPrefix))\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar user types.User\n\t\tk.cdc.MustUnmarshalBinaryLengthPrefixed(store.Get(iterator.Key()), &user)\n\t\tuserList = append(userList, user)\n\t}\n\tres := codec.MustMarshalJSONIndent(k.cdc, userList)\n\treturn res, nil\n}", "func (c *Client) ListUsers() ([]User, error) {\n\tusers := []User{}\n\t_, err := c.sling.Get(\"users\").ReceiveSuccess(&users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (client IdentityClient) listUsers(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/users\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListUsersResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *UsersService) List(opt *UsersOptions) ([]User, *http.Response, error) {\n\turi, err := addOptions(\"users\", opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tusers := new(Users)\n\tres, err := s.client.Get(uri, users)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\treturn users.Users, res, err\n}", "func (u *UserServiceHandler) List(ctx context.Context) ([]User, error) {\n\n\turi := \"/v1/user/list\"\n\n\treq, err := u.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar users []User\n\terr = u.client.DoWithContext(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn users, nil\n}", "func ListUsersPath() string {\n\treturn \"/api/v1/users\"\n}", "func (sys *IAMSys) ListUsers() (map[string]madmin.UserInfo, error) {\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil {\n\t\treturn nil, errServerNotInitialized\n\t}\n\n\tvar users = make(map[string]madmin.UserInfo)\n\n\tsys.RLock()\n\tdefer sys.RUnlock()\n\n\tfor k, v := range sys.iamUsersMap {\n\t\tusers[k] = madmin.UserInfo{\n\t\t\tPolicyName: sys.iamUserPolicyMap[k].Policy,\n\t\t\tStatus: madmin.AccountStatus(v.Status),\n\t\t}\n\t}\n\n\treturn users, nil\n}", "func (uc UsersController) List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tfmt.Fprintf(w, \"UsersList\")\n}", "func (c *Client) ListUsers(ctx context.Context) ([]*models.User, error) {\n\tvar resp struct {\n\t\tUsers []*models.User `json:\"users\"`\n\t}\n\n\terr := c.transport.Raw(ctx, `\n\t\tquery Users {\n\t\t\tusers {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\temail\n\t\t\t\trole {\n\t\t\t\t\tid\n\t\t\t\t\tlabel\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, nil, &resp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Users, nil\n}", "func (h *User) List(w http.ResponseWriter, r *http.Request) {\n\tlimit, offset := utils.GetPaginationParams(r.URL.Query())\n\tresp, err := h.Storage.GetUserList(limit, offset)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tif len(resp) < 1 {\n\t\tR.JSON404(w)\n\t\treturn\n\t}\n\n\tR.JSON200(w, resp)\n}", "func (u *UserService) List(ctx context.Context) ([]*User, *http.Response, error) {\n\treq, err := u.client.newRequest(\"GET\", \"user.list\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar users []*User\n\tresp, err := u.client.do(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn users, resp, nil\n}", "func (s *API) ListUsers(req *ListUsersRequest, opts ...scw.RequestOption) (*ListUsersResponse, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"name\", req.Name)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tif fmt.Sprint(req.InstanceID) == \"\" {\n\t\treturn nil, errors.New(\"field InstanceID cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/instances/\" + fmt.Sprint(req.InstanceID) + \"/users\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListUsersResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func userIndex(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tdb := co.DbConnection(dbc)\n\t// DB query to get all the users\n\tresults, err := db.Query(\"SELECT user_name FROM members\")\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tvar members []string\n\tfor results.Next() {\n\t\tvar name string\n\t\terr = results.Scan(&name)\n\t\tif err != nil {\n\t\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t\t}\n\t\tmembers = append(members, name)\n\t}\n\tresults.Close()\n\tdb.Close()\n\tjsonPrint(w, members)\n return\n}", "func (c *UsersController) List(ctx *app.ListUsersContext) error {\n\t// UsersController_List: start_implement\n\n\t// Put your logic here\n\tcognitoUserID := ctx.Params.Get(\"cognitoAuthUserId\")\n\tuserID, err := c.db.GetUserIDByCognitoUserID(cognitoUserID)\n\tif err != nil {\n\t\tlog.Errorf(\"[controller/user] failed to get user id: %v\", err)\n\t\treturn ctx.InternalServerError(&app.StandardError{\n\t\t\tCode: 500,\n\t\t\tMessage: \"could not retrieve user data\",\n\t\t})\n\t}\n\n\tuser := &types.User{\n\t\tID: userID,\n\t\tCognitoAuthUserID: cognitoUserID,\n\t}\n\n\tif user == nil {\n\t\tlog.Errorf(\"[controller/user] user not found: %v\", userID)\n\t\treturn ctx.NotFound(&app.StandardError{\n\t\t\tCode: 400,\n\t\t\tMessage: \"user not found\",\n\t\t})\n\t}\n\n\tres := &app.User{\n\t\tID: user.ID,\n\t\tCognitoAuthUserID: &user.CognitoAuthUserID,\n\t}\n\treturn ctx.OK(res)\n\t// UsersController_List: end_implement\n}", "func (retUser) List(ctx context.Context, db *sqlx.DB) ([]User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.user.list\")\n\tdefer span.End()\n\n\tusers := []User{}\n\tconst q = `SELECT * FROM users`\n\n\tif err := db.SelectContext(ctx, &users, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting users\")\n\t}\n\n\treturn users, nil\n}", "func userList(w http.ResponseWriter, r *http.Request) {}", "func (c *client) ListUsers(\n\topt *glab.ListUsersOptions,\n\topts ...glab.RequestOptionFunc,\n) ([]*glab.User, *glab.Response, error) {\n\treturn c.c.Users.ListUsers(opt, opts...)\n}", "func ListUsers(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\trepo := users.NewUserRepository(db)\n\tutils.JsonResponse(w, repo.GetAllUsers([]users.User{}), http.StatusOK)\n}", "func (cs *UserService) List() ([]UsersResponse, error) {\n\n\treq, err := cs.client.NewRequest(\"GET\", \"/users\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := cs.client.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := validateResponse(resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBytes, _ := ioutil.ReadAll(resp.Body)\n\tbodyString := string(bodyBytes)\n\n\tu := &listUsersJSONResponse{}\n\terr = json.Unmarshal([]byte(bodyString), &u)\n\n\treturn u.Users, err\n}", "func (c *Client) ListUser(ctx context.Context, path string) (*http.Response, error) {\n\tvar body io.Reader\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\tc.SignerJWT.Sign(ctx, req)\n\treturn c.Client.Do(ctx, req)\n}", "func (us *UserService) List(p *Pagination) ([]User, error) {\n\treturn us.Datasource.List(p)\n}", "func (pool *Pool) GetUserList() []string {\n\tpool.mu.Lock()\n\tusernames := make([]string, 0)\n\n\tfor client := range pool.Clients {\n\t\tusernames = append(usernames, client.Account.Username)\n\t}\n\n\tpool.mu.Unlock()\n\treturn usernames\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request){\n\n\trows, err:= db.Query(\"SELECT * FROM users LIMIT 20\")\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tlistUsers := Users{}\n\tfor rows.Next() {\n\t\tp := User{}\n\t\tif err := rows.Scan(&p.ID, &p.Name, &p.Score); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlistUsers = append(listUsers, p)\n\n\t}\n\tdefer rows.Close()\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tjson.NewEncoder(w).Encode(listUsers)\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Mohomaaf ...dsb\", nil, nil)\n\t\t}\n\t}()\n\n\tfLog := userMgmtLogger.WithField(\"func\", \"ListAllUsers\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Listing Users\")\n\tpageRequest, err := helper.NewPageRequestFromRequest(r)\n\tif err != nil {\n\t\tfLog.Errorf(\"helper.NewPageRequestFromRequest got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tusers, page, err := UserRepo.ListUser(r.Context(), pageRequest)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.ListUser got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tsusers := make([]*SimpleUser, len(users))\n\tfor i, v := range users {\n\t\tsusers[i] = &SimpleUser{\n\t\t\tRecID: v.RecID,\n\t\t\tEmail: v.Email,\n\t\t\tEnabled: v.Enabled,\n\t\t\tSuspended: v.Suspended,\n\t\t}\n\t}\n\tret := make(map[string]interface{})\n\tret[\"users\"] = susers\n\tret[\"page\"] = page\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"List of all user paginated\", nil, ret)\n}", "func (h UserHTTP) List(w http.ResponseWriter, r *http.Request) {\n\tlistRequest := listRequestDecoder(r)\n\tusers, err := h.svc.ListUsers(r.Context(), listRequest)\n\tif err != nil {\n\t\th.logger.With(r.Context()).Errorf(\"list users error : %s\", err)\n\t\trender.Render(w, r, e.BadRequest(err, \"bad request\"))\n\t\treturn\n\t}\n\trender.Respond(w, r, users)\n}", "func (u *User) List() ([]*UserListRes, error) {\n\tvar users []db.Users\n\tif err := u.Sess.Asc(\"id\").Find(&users); err != nil {\n\t\treturn nil, err\n\t}\n\tres := make([]*UserListRes, len(users))\n\tfor i := 0; i < len(users); i++ {\n\t\tuser := users[i]\n\t\tres[i] = &UserListRes{ID: user.Id, Name: user.Name}\n\t}\n\treturn res, nil\n}", "func usersConfig(port int) Ifx {\n\treturn Ifx{\n\t\tFor: \"users\",\n\t\tName: fmt.Sprintf(\"swp%d\", port),\n\t\tBridgeDefs: []string{\n\t\t\t\"bridge-vids 2002 2003 2005\",\n\t\t\t\"bridge-allow-untagged no\",\n\t\t}}\n}", "func ShowUsers(baseURL string) int {\n\tif utils.LoginCheck() {\n\t\t// HTTP\n\t\tt := utils.GetToken()\n\t\tclient := &http.Client{}\n\t\treq, _ := http.NewRequest(\"GET\", baseURL+\"/v1/users?token=\"+t, nil)\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tr := &UserList{}\n\t\terr = json.Unmarshal([]byte(string(body)), &r)\n\t\tif err != nil {\n\t\t\tutils.PrintError(err.Error())\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tfor i := 0; i < len(r.Data); i++ {\n\t\t\t\tprintUser(r.Data[i])\n\t\t\t}\n\t\t\treturn 0\n\t\t}\n\n\t\tif resp.StatusCode == 401 {\n\t\t\tfmt.Println(r.Message)\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 1\n\t} else {\n\t\tfmt.Println(\"Please Login First\")\n\t\treturn 1\n\t}\n}", "func List(ctx context.Context, dbConn *db.DB) ([]User, error) {\n\tu := []User{}\n\n\tf := func(collection *mgo.Collection) error {\n\t\treturn collection.Find(nil).All(&u)\n\t}\n\tif err := dbConn.MGOExecute(ctx, usersCollection, f); err != nil {\n\t\treturn nil, errors.Wrap(err, \"db.users.find()\")\n\t}\n\n\treturn u, nil\n}", "func ListUsers(client *Client, full bool) (*[]ConfigUser, error) {\n\tvar err error\n\tvar userList []interface{}\n\tif full {\n\t\tuserList, err = listUsersFull(client)\n\t} else {\n\t\tuserList, err = listUsersPartial(client)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ConfigUser{}.mapToArray(userList), nil\n}", "func ListUserPath() string {\n\n\treturn fmt.Sprintf(\"/users\")\n}", "func (u *userController) List() {\n\tres, err := u.userUsecase.List()\n\tencoder := json.NewEncoder(u.Context.w)\n\tif err != nil {\n\t\tu.Context.w.WriteHeader(http.StatusBadGateway)\n\t\tencoder.Encode(err)\n\t\treturn\n\t}\n\tu.Context.w.WriteHeader(http.StatusOK)\n\tencoder.Encode(res)\n\treturn\n}", "func (rbac *RBAC) ListUsers() []User {\n\trbac.mutex.RLock()\n\tdefer rbac.mutex.RUnlock()\n\n\tout := make([]User, 0, len(rbac.registeredUsers))\n\tfor u := range rbac.registeredUsers {\n\t\tout = append(out, u)\n\t}\n\treturn out\n}", "func ListUser(email, password string) []User {\n\tvar u []User\n\tDb.Find(&u)\n\treturn u\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn c.Render(200, r.JSON(users))\n}", "func (s *Database) ListUser() ([]*UserPartner, error) {\n\tvar users []*UserPartner\n\terr := s.Engine.Desc(\"id\").Find(&users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users) == 0 {\n\t\treturn nil, errors.New(\"Database rong\")\n\t}\n\treturn users, nil\n}", "func (u *User) List(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.User.List\")\n\tdefer span.End()\n\n\tusers, err := user.List(ctx, u.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn web.Respond(ctx, w, users, http.StatusOK)\n}", "func (u *UserCalculator) ActiveUsers() []string { return u.active }", "func (e *EndpointUsers) listUsers(writer http.ResponseWriter, request *http.Request) {\n\t_, usr := validate(e.sessions, e.users, e.permissions, writer, request, user.LIST_USERS)\n\tif usr == nil {\n\t\treturn\n\t}\n\n\tusers, err := e.users.List()\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tres := &userListDTO{}\n\tfor _, u := range users {\n\t\tres.List = append(res.List, newUserDTO(u))\n\t}\n\tWriteJSONBody(writer, res)\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn fmt.Errorf(\"no transaction found\")\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn err\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(http.StatusOK, r.Auto(c, users))\n}", "func listNodes() (string, error) {\n\tvar ret string\n\n\tlist, err := getAllNodes()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t// Prettify the response for output.\n\tif len(list.Nodes) == 0 {\n\t\tret = \"No nodes to list\\n\"\n\t\treturn ret, nil\n\t}\n\tvar out bytes.Buffer\n\tout.WriteString(\"ID\\tName\\tModel\\tStatus\\tLHVPN.Address\\tFW.Version\\tConn.Status\\tErrors\\n\")\n\tfor _, v := range list.Nodes {\n\t\tout.WriteString(fmt.Sprintf(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t\t\tv.ID,\n\t\t\tv.Name,\n\t\t\tv.Model,\n\t\t\tv.Status,\n\t\t\tv.LHVPNAddress,\n\t\t\tv.Version,\n\t\t\tv.RuntimeStatus.ConnectionStatus,\n\t\t\tv.RuntimeStatus.ActionErr,\n\t\t))\n\t}\n\tret = out.String()\n\treturn ret, err\n}", "func (r *RestAPI) ListUsers(desiredAttrs []string) ([]internal.Person, error) {\n\terrLog := make(chan string, 1000)\n\tpeople := make(chan internal.Person, 20000)\n\tvar wg sync.WaitGroup\n\tr.logHttpTimeout()\n\n\tattributesToRead := internal.AddStringToSlice(r.IDAttribute, desiredAttrs)\n\tfor _, f := range r.Filters {\n\t\tattributesToRead = internal.AddStringToSlice(f.Attribute, attributesToRead)\n\t}\n\tfor _, p := range r.setConfig.Paths {\n\t\twg.Add(1)\n\t\tgo r.listUsersForPath(attributesToRead, p, &wg, people, errLog)\n\t}\n\n\twg.Wait()\n\tclose(people)\n\tclose(errLog)\n\n\tif len(errLog) > 0 {\n\t\tvar errs []string\n\t\tfor msg := range errLog {\n\t\t\terrs = append(errs, msg)\n\t\t}\n\t\treturn []internal.Person{}, fmt.Errorf(\"errors listing users from %s: %s\", r.BaseURL, strings.Join(errs, \",\"))\n\t}\n\n\treturn r.filterPeople(people)\n}", "func List(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tlistHandler(w, authUser, false)\n}", "func showUsers(ctx context.Context, client *api.Client, path string, ifModifiedSince *string, ifNoneMatch *string) (*http.Response, error) {\n\treq, err := newShowUsersRequest(ctx, client, path, ifModifiedSince, ifNoneMatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.Do(ctx, req)\n}", "func UserListAll(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar pageSize int\n\tvar paginatedUsers auth.PaginatedUsers\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefRoles := gorillaContext.Get(r, \"auth_roles\").([]string)\n\n\t// Grab url path variables\n\turlValues := r.URL.Query()\n\tpageToken := urlValues.Get(\"pageToken\")\n\tstrPageSize := urlValues.Get(\"pageSize\")\n\tprojectName := urlValues.Get(\"project\")\n\tprojectUUID := \"\"\n\n\tif projectName != \"\" {\n\t\tprojectUUID = projects.GetUUIDByName(projectName, refStr)\n\t\tif projectUUID == \"\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif strPageSize != \"\" {\n\t\tif pageSize, err = strconv.Atoi(strPageSize); err != nil {\n\t\t\tlog.Errorf(\"Pagesize %v produced an error while being converted to int: %v\", strPageSize, err.Error())\n\t\t\terr := APIErrorInvalidData(\"Invalid page size\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// check that user is indeed a service admin in order to be priviledged to see full user info\n\tpriviledged := auth.IsServiceAdmin(refRoles)\n\n\t// Get Results Object - call is always priviledged because this handler is only accessible by service admins\n\tif paginatedUsers, err = auth.PaginatedFindUsers(pageToken, int32(pageSize), projectUUID, priviledged, refStr); err != nil {\n\t\terr := APIErrorInvalidData(\"Invalid page token\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := paginatedUsers.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func (m *publicUser) GetUserList(c *gin.Context) (int, interface{}) {\n\tuser := plugins.CurrentPlugin(c, m.config.LoginVersion)\n\tuserList, err := user.GetUserList(c, m.config.ConfigMap)\n\trspBody := metadata.LonginSystemUserListResult{}\n\tif nil != err {\n\t\trspBody.Code = common.CCErrCommHTTPDoRequestFailed\n\t\trspBody.ErrMsg = err.Error()\n\t\trspBody.Result = false\n\t}\n\trspBody.Result = true\n\trspBody.Data = userList\n\treturn 200, rspBody\n}", "func GetAll(c *gin.Context) {\n\tusers, err := services.UsersService.GetAllUsers()\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, users.Marshal(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func (r *UsersService) List() *UsersListCall {\n\tc := &UsersListCall{s: r.s, opt_: make(map[string]interface{})}\n\treturn c\n}", "func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"listing users\"))\n}", "func (h *handler) Users(w http.ResponseWriter, r *http.Request) {\n\tapiReq, err := http.NewRequest(\"GET\", h.serverAddress+\"/users\", nil)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\tclient := &http.Client{}\n\tres, err := client.Do(apiReq)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tvar uis []socialnet.UserItem\n\terr = json.NewDecoder(res.Body).Decode(&uis)\n\tif err != nil {\n\t\tserverError(w, err)\n\t\treturn\n\t}\n\n\terr = h.template.ExecuteTemplate(w, \"users.html\", uis)\n\tif err != nil {\n\t\tserverError(w, fmt.Errorf(\"failed to execute template users.html: %s\", err))\n\t\treturn\n\t}\n}", "func (c *DefaultIdentityProvider) ListUsers(ctx context.Context, options *metainternal.ListOptions) (*auth.UserList, error) {\n\tkeyword := \"\"\n\tlimit := 50\n\tif options.FieldSelector != nil {\n\t\tkeyword, _ = options.FieldSelector.RequiresExactMatch(auth.KeywordQueryTag)\n\t\tlimitStr, _ := options.FieldSelector.RequiresExactMatch(auth.QueryLimitTag)\n\t\tif li, err := strconv.Atoi(limitStr); err == nil && li > 0 {\n\t\t\tlimit = li\n\t\t}\n\t}\n\n\t_, tenantID := authentication.GetUsernameAndTenantID(ctx)\n\tif tenantID != \"\" && tenantID != c.tenantID {\n\t\treturn nil, apierrors.NewBadRequest(\"must in the same tenant\")\n\t}\n\n\tallList, err := c.localIdentityLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localIdentityList []*authv1.LocalIdentity\n\tfor i, item := range allList {\n\t\tif item.Spec.TenantID == c.tenantID {\n\t\t\tlocalIdentityList = append(localIdentityList, allList[i])\n\t\t}\n\t}\n\n\tif keyword != \"\" {\n\t\tvar newList []*authv1.LocalIdentity\n\t\tfor i, val := range localIdentityList {\n\t\t\tif strings.Contains(val.Name, keyword) || strings.Contains(val.Spec.Username, keyword) || strings.Contains(val.Spec.DisplayName, keyword) {\n\t\t\t\tnewList = append(newList, localIdentityList[i])\n\t\t\t}\n\t\t}\n\t\tlocalIdentityList = newList\n\t}\n\n\titems := localIdentityList[0:min(len(localIdentityList), limit)]\n\n\tuserList := auth.UserList{}\n\tfor _, item := range items {\n\t\tuser := convertToUser(item)\n\t\tuserList.Items = append(userList.Items, user)\n\t}\n\n\treturn &userList, nil\n}", "func ListMyOrgs(username string, token string) []string {\n\tresp, err := GetFromGitHub(username, token, \"/user/orgs\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar orgList []Org\n\tjsonErr := json.Unmarshal(resp, &orgList)\n\tif jsonErr != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar returnList []string\n\tfor _, s := range orgList {\n\t\treturnList = append(returnList, s.Login)\n\t}\n\treturn returnList\n}", "func (h *userHandler) showUsers(ctx context.Context, rw http.ResponseWriter) {\n\n\tusers, err := h.serv.DB.UserCol.FindAll(ctx)\n\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\th.serv.writeResponsePlus(ctx, rw, \"users\", http.StatusOK, nil, users)\n}", "func listCmdMain(cmd *cobra.Command, args []string) {\n\tvalidateConfig()\n\n\tproject := viper.GetString(\"project\")\n\tregion := viper.GetString(\"region\")\n\tservice := scarab.NewService()\n\n\ttuns, err := service.VpnTunnels.List(project, region).Do()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, tun := range tuns.Items {\n\t\tlog.Println(tun.Name, tun.PeerIp, tun.DetailedStatus)\n\t}\n}", "func (r *Repository) UsersList(opts ...usersListOption) ([]User, *PagesInfo, error) {\n\tlist := make(Users, 0)\n\n\toptions := newUsersListOptions(opts)\n\n\tquery, params := usersApplyFilters(\"SELECT * FROM users\", options.UsersFilters)\n\tpageQuery, params := paginate(query, params, options.Pagination)\n\n\tstmt, err := r.db.PrepareNamed(pageQuery)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif err := stmt.Select(&list, params); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpi, err := r.pagesInfo(query, params, options.Pagination, list)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn list, pi, nil\n}", "func listUsersPartial(client *Client) ([]interface{}, error) {\n\treturn client.GetItemListInterfaceArray(\"/access/users\")\n}", "func ListUsers() ([]*User, error) {\n\tvar users []*User\n\terr := meddler.QueryAll(db, &users, userStmt)\n\treturn users, err\n}", "func (s *UsersService) List() *UsersListCall {\n\tvar call UsersListCall\n\tcall.service = s\n\treturn &call\n}", "func (s *Store) ListUsers() (*[]models.User, error) {\n\tvar users []models.User\n\terr := s.Users.Find(bson.M{}).All(&users)\n\treturn &users, err\n}", "func (m *TestTooDB) ListUser(ctx context.Context) []*app.User {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"user\", \"listuser\"}, time.Now())\n\n\tvar native []*TestToo\n\tvar objs []*app.User\n\terr := m.Db.Scopes().Table(m.TableName()).Find(&native).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error listing TestToo\", \"error\", err.Error())\n\t\treturn objs\n\t}\n\n\tfor _, t := range native {\n\t\tobjs = append(objs, t.TestTooToUser())\n\t}\n\n\treturn objs\n}", "func (service *UserService) ListUsers() ([]models.User, error) {\n\tvar list []models.User\n\tfor _, v := range service.UserList {\n\t\tlist = append(list, v)\n\t}\n\treturn list, nil\n}", "func UserListByToken(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlToken := urlVars[\"token\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tresult, err := auth.GetUserByToken(urlToken, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := result.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}" ]
[ "0.63678443", "0.6296972", "0.61648804", "0.6100317", "0.6076037", "0.5979606", "0.59017223", "0.5899384", "0.58572346", "0.58432597", "0.58376485", "0.5795592", "0.5794831", "0.5789411", "0.57877797", "0.57757306", "0.5759303", "0.5753402", "0.5746834", "0.57361245", "0.5732818", "0.5712002", "0.570307", "0.56679", "0.56614184", "0.5649723", "0.56277716", "0.5612968", "0.56059253", "0.5580906", "0.55696946", "0.5564709", "0.5535531", "0.5533623", "0.55301994", "0.5525051", "0.55163693", "0.55111897", "0.5509477", "0.5491021", "0.54902273", "0.5479047", "0.547625", "0.54607403", "0.54435056", "0.5436815", "0.5429069", "0.5421869", "0.5410013", "0.5396383", "0.5378597", "0.53723776", "0.53686047", "0.5368271", "0.5357316", "0.5329517", "0.5291126", "0.5290473", "0.5290329", "0.52884096", "0.5284829", "0.5283322", "0.5278168", "0.5269758", "0.52694565", "0.52684915", "0.52438504", "0.52317405", "0.52292436", "0.52188593", "0.5218712", "0.5218258", "0.5212559", "0.52024674", "0.5201124", "0.51871336", "0.518476", "0.51688004", "0.51565826", "0.5129139", "0.5128824", "0.51272243", "0.5119576", "0.5119004", "0.51069397", "0.51060987", "0.5104429", "0.5100982", "0.5099194", "0.5083505", "0.50805986", "0.5078478", "0.507781", "0.50763553", "0.5074502", "0.5074061", "0.50660926", "0.50645167", "0.5060761", "0.50530833" ]
0.7021634
0
Create a VPN User in the current environment
func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) Create(remoteAccessVpnUser RemoteAccessVpnUser) (bool, error) { send, merr := json.Marshal(remoteAccessVpnUser) if merr != nil { return false, merr } _, err := remoteAccessVpnUserApi.entityService.Create(send, map[string]string{}) return err == nil, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Session) createUser() error {\n\tlog := s.context.Log()\n\n\t// Create local user\n\tcommandArgs := []string{\"net\", \"user\", \"/add\", appconfig.DefaultRunAsUserName}\n\tcmd := exec.Command(appconfig.PowerShellPluginCommandName, commandArgs...)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Errorf(\"Failed to create %s: %v\", appconfig.DefaultRunAsUserName, err)\n\t\treturn err\n\t}\n\tlog.Infof(\"Successfully created %s\", appconfig.DefaultRunAsUserName)\n\n\t// Add to admins group\n\tcommandArgs = []string{\"net\", \"localgroup\", administrators, appconfig.DefaultRunAsUserName, \"/add\"}\n\tcmd = exec.Command(appconfig.PowerShellPluginCommandName, commandArgs...)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Errorf(\"Failed to add %s to %s group: %v\", appconfig.DefaultRunAsUserName, administrators, err)\n\t\treturn err\n\t}\n\tlog.Infof(\"Successfully added %s to %s group\", appconfig.DefaultRunAsUserName, administrators)\n\treturn nil\n}", "func CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"CreateNewUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Creating new user\")\n\treq := &CreateNewUserRequest{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, req)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tisValidPassphrase := passphrase.Validate(req.Passphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\tuser, err := UserRepo.CreateUserRecord(r.Context(), req.Email, req.Passphrase)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.CreateUserRecord got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := &CreateNewUserResponse{\n\t\tRecordID: user.RecID,\n\t\tEmail: user.Email,\n\t\tEnabled: user.Enabled,\n\t\tSuspended: user.Suspended,\n\t\tLastSeen: user.LastSeen,\n\t\tLastLogin: user.LastLogin,\n\t\tTotpEnabled: user.Enable2FactorAuth,\n\t}\n\tfLog.Warnf(\"Sending email\")\n\tmailer.Send(r.Context(), &mailer.Email{\n\t\tFrom: config.Get(\"mailer.from\"),\n\t\tFromName: config.Get(\"mailer.from.name\"),\n\t\tTo: []string{user.Email},\n\t\tCc: nil,\n\t\tBcc: nil,\n\t\tTemplate: \"EMAIL_VERIFY\",\n\t\tData: user,\n\t})\n\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"Success creating user\", nil, resp)\n\treturn\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func createUser(name, password, passwordUpdateRequest string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"User\",\n \"name\": \"%s\",\n \"credential\": {\n \"type\": \"PasswordCredential\",\n\t\t\"password\": \"%s\",\n\t\t\"passwordUpdateRequest\": \"%s\"\n }\n}`, name, password, passwordUpdateRequest)\n}", "func (helper *vpnHelper) CreateDefaultUser() derrors.Error {\n\t//Create user\n\tcmd := exec.Command(command, cmdMode, defaultVPNServer, hub, cmdCmd, userCreateCmd, defaultVPNUser, group, realName, note)\n\tlog.Debug().Str(\"Server\", defaultVPNServer).Str(\"Username\", defaultVPNUser).Msg(\"Default user created in VPN Server\")\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn derrors.NewGenericError(\"error executing UserCreate command\", err)\n\t}\n\n\t// Execute UserPasswordSet command for Username\n\tcmd = exec.Command(command, cmdMode, defaultVPNServer, hub, cmdCmd, userPasswordSetCmd, defaultVPNUser, userPassword+defaultVPNPassword)\n\tlog.Debug().Str(\"Server\", defaultVPNServer).Str(\"Username\", defaultVPNUser).Msg(\"Password for default user created\")\n\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn derrors.NewGenericError(\"error executing UserDelete userPasswordSet command\", err)\n\t}\n\n\treturn nil\n}", "func CreateUser(c *gin.Context) {}", "func createUserV1() user {\n\tu := user{\n\t\tname: \"Bill\",\n\t\temail: \"[email protected]\",\n\t}\n\n\tprintln(\"V1\", &u)\n\n\treturn u\n}", "func Create(newuser User) error {\n\t// Check if the new user exists\n\tif stt := Find(newuser.UserID); stt == \"Unavailable\" {\n\t\treturn errors.New(\"Exists\")\n\t}\n\n\tif newuser.CallerID == \"\" {\n\t\tnewuser.CallerID = newuser.UserID\n\t}\n\n\tif newuser.Context == \"\" {\n\t\tnewuser.Context = defaultContext\n\t}\n\n\ttmpl, err := template.ParseFiles(userConfTempl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuserconf := userConfPath + newuser.UserID + \".conf\"\n\tf, err := os.OpenFile(userconf, os.O_CREATE|os.O_RDWR, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\terr = tmpl.Execute(f, newuser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = writeToDB(newuser); err != nil {\n\t\treturn err\n\t}\n\n\t// Check if the new user is created\n\tif stt := Find(newuser.UserID); stt == \"Unavailable\" {\n\t\treturn nil\n\t}\n\n\tif err = PjsipReload(); err != nil {\n\t\treturn err\n\t}\n\n\treturn errors.New(\"Failed\")\n}", "func newUser() string {\n\treturn goherokuname.Haikunate()\n}", "func createUser() {\n\tconn, err := createConnection()\n\tif conn != nil {\n\t\tdefer conn.Close()\n\t}\n\taccountClient := NewAccountClient(conn)\n\tcreateUserMessage := &CreateUserMessage{Username: \"politrons\", UserMessage: &UserMessage{Name: \"Paul\", Age: \"38\", Sex: \"Male\"}}\n\tctx, _ := context.WithTimeout(context.Background(), 500*time.Millisecond)\n\tresponse, err := accountClient.CreateUser(ctx, createUserMessage)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error in creation process: %s\", err)\n\t}\n\tlog.Printf(\"Response, User created with info:\")\n\tlog.Printf(\"Name: %s\", response.Name)\n\tlog.Printf(\"Age: %s\", response.Age)\n\tlog.Printf(\"Sex: %s\", response.Sex)\n}", "func (rCon *RedisConnection) CreateUser(un, pw string) (err error) {\n\n\tRanV := GenRandNumber(12)\n\tsalt := fmt.Sprintf(\"%x\", RanV)\n\n\tpwHash := fmt.Sprintf(\"%x\", pbkdf2.Key([]byte(pw), []byte(salt), NIterations, 64, sha256.New))\n\tkey := fmt.Sprintf(\"qr-auth:%s\", un)\n\n\terr = rCon.SetRedis(key, pwHash)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to set user authenication: %s\", err)\n\t}\n\n\tkey = fmt.Sprintf(\"qr-salt:%s\", un)\n\terr = rCon.SetRedis(key, salt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to set user authenication/salt: %s\", err)\n\t}\n\n\treturn nil\n}", "func createVhostUserEndpoint(netInfo NetworkInfo, socket string) (*VhostUserEndpoint, error) {\n\n\tvhostUserEndpoint := &VhostUserEndpoint{\n\t\tSocketPath: socket,\n\t\tHardAddr: netInfo.Iface.HardwareAddr.String(),\n\t\tIfaceName: netInfo.Iface.Name,\n\t\tEndpointType: VhostUserEndpointType,\n\t}\n\treturn vhostUserEndpoint, nil\n}", "func newUser(vres *hyuserviews.UserView) *User {\n\tres := &User{\n\t\tUserID: vres.UserID,\n\t\tUserName: vres.UserName,\n\t\tEmail: vres.Email,\n\t}\n\treturn res\n}", "func createUser(u *User) error {\n\tif u.Status == 0 {\n\t\treturn errors.New(\"Invalid user value\")\n\t}\n\n\treturn nil\n}", "func CreateVmmUser() (string, error) {\n\tvar (\n\t\terr error\n\t\tuserName string\n\t)\n\n\tuseraddPath, err := FirstValidExecutable([]string{\"/usr/sbin/useradd\", \"/sbin/useradd\", \"/bin/useradd\"})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tnologinPath, err := FirstValidExecutable([]string{\"/usr/sbin/nologin\", \"/sbin/nologin\", \"/bin/nologin\"})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Add retries to mitigate temporary errors and race conditions. For example, the user already exists\n\t// or another instance of the runtime is also creating a user.\n\tmaxAttempt := 5\n\trand.Seed(time.Now().UnixNano())\n\tfor i := 0; i < maxAttempt; i++ {\n\t\tuserName = fmt.Sprintf(\"kata-%v\", rand.Intn(100000))\n\t\t_, err = RunCommand([]string{useraddPath, \"-M\", \"-s\", nologinPath, userName, \"-c\", \"\\\"Kata Containers temporary hypervisor user\\\"\"})\n\t\tif err == nil {\n\t\t\treturn userName, nil\n\t\t}\n\t\tutilsLog.WithField(\"attempt\", i+1).WithField(\"username\", userName).\n\t\t\tWithError(err).Warn(\"failed to add user, will try again\")\n\t}\n\treturn \"\", fmt.Errorf(\"could not create VMM user: %v\", err)\n}", "func createUserV2() *user {\n\tu := user{\n\t\tname: \"Bill\",\n\t\temail: \"[email protected]\",\n\t}\n\n\tprintln(\"V2\", &u)\n\n\treturn &u\n}", "func (a *Server) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"create a new user\")\n}", "func CreateUserHandler(w http.ResponseWriter, req *http.Request) {\n // Validate internal token.\n if internalToken := req.Header.Get(app.Config.AuthHeaderName); internalToken != app.Config.RestApiToken {\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n\n // Parse & validate payload.\n var pl payload.CreateUserPayload\n\n if !pl.Validate(req) {\n respond.Error(w, errmsg.InvalidPayload())\n return\n }\n\n // Check if the executor is using the USER_CREATION_HASH to create this user.\n usingUserCreationPw := pl.ExecutorEmail == \"\" && app.Config.UserCreationHash != \"\" &&\n crypt.VerifySha256(pl.ExecutorPassword, app.Config.UserCreationHash)\n\n // If not using USER_CREATION_HASH for auth, verify executor exists using email/pw.\n if !usingUserCreationPw {\n // Get executor user by email.\n executorUser, err := usersvc.FromEmail(pl.ExecutorEmail)\n\n if err != nil {\n app.Log.Errorln(err.Error())\n respond.Error(w, errmsg.UserNotFound())\n return\n }\n\n // Ensure executor user's password is correct.\n if !crypt.VerifyBcrypt(pl.ExecutorPassword, executorUser.HashedPw) {\n app.Log.Errorln(\"error creating new User: invalid executor user password\")\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n\n // Only admin users can create other users.\n if !executorUser.Admin {\n app.Log.Errorln(\"error creating new User: executor user must be an admin\")\n respond.Error(w, errmsg.Unauthorized())\n return\n }\n }\n\n // Hash provided user password.\n hashedPw, err := crypt.BcryptHash(pl.NewPassword)\n\n if err != nil {\n app.Log.Errorf(\"error creating new User: bcrypt password hash failed with %s\\n\", err.Error())\n respond.Error(w, errmsg.ISE())\n return\n }\n\n // Create new User.\n newUser, err := usersvc.Create(pl.NewEmail, hashedPw, pl.Admin)\n\n if err != nil {\n app.Log.Errorln(err.Error())\n pqError, ok := err.(*pq.Error)\n\n if ok && pqError.Code.Name() == \"unique_violation\" {\n respond.Error(w, errmsg.EmailNotAvailable())\n } else {\n respond.Error(w, errmsg.UserCreationFailed())\n }\n\n return\n }\n\n // Create response payload and respond.\n respData := successmsg.UserCreationSuccess\n respData[\"uid\"] = newUser.Uid\n\n respond.Created(w, respData)\n}", "func (cli *OpsGenieUserV2Client) Create(req userv2.CreateUserRequest) (*userv2.CreateUserResponse, error) {\n\tvar response userv2.CreateUserResponse\n\terr := cli.sendPostRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (t *OpetCode) createUser(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 2 {\n return shim.Error(\"Incorrect number of arguments. Expecting 2\")\n }\n\n uid := args[0]\n json_props := args[1]\n user_key, _ := APIstub.CreateCompositeKey(uid, []string{USER_KEY})\n\n if _, err := t.loadUser(APIstub, user_key); err == nil {\n return shim.Error(\"Account already exists\")\n }\n new_user := new(User)\n new_user.Uid = uid\n new_user.Data = make(map[string]string)\n err := json.Unmarshal([]byte(json_props), &new_user.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_user_json, _ := json.Marshal(new_user)\n APIstub.PutState(user_key, new_user_json)\n\n return shim.Success(nil)\n}", "func createUser(u *models.User, db *sql.DB) error {\n\tif err := u.CryptPwd(); err != nil {\n\t\treturn fmt.Errorf(\"Cryptage du mot de passe de %s : %v\", u.Name, err)\n\t}\n\tif err := u.Create(db); err != nil {\n\t\treturn fmt.Errorf(\"Création en base de données de %s : %v\", u.Name, err)\n\t}\n\treturn nil\n}", "func CreateUser(user User) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\ttoken, _ := exec.Command(\"uuidgen\").Output()\n\tuser.Token = strings.Trim(string(token), \"\\n\")\n\tdb.Insert(user)\n\tvar result User\n\tdb.Find(bson.M{\"username\": user.Username}).One(&result)\n\treturn result\n}", "func pushToNSS(ctx context.Context, user, p12Path string) error {\n\tupath, err := cryptohome.UserPath(ctx, user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnssdb := filepath.Join(upath, \".pki\", \"nssdb\")\n\tcmd := testexec.CommandContext(ctx, \"pk12util\", \"-d\", \"sql:\"+nssdb, \"-i\", p12Path, \"-W\", \"\" /* password */)\n\tif err := cmd.Run(); err != nil {\n\t\tcmd.DumpLog(ctx)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}", "func createNewUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tvar userInfo UserBody\n\t//decode the json object and store the values in userInfo\n\terr := json.NewDecoder(r.Body).Decode(&userInfo)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR DECODING JSON OBJ FROM CREATE NEW USER\")\n\t}\n\tresult := post.CreateUser(params[\"id\"], userInfo.FirstName, userInfo.LastName, userInfo.Email)\n\tjson.NewEncoder(w).Encode(map[string]bool{\n\t\t\"result\": result,\n\t})\n}", "func createTempUser(host string, adminToken string) (user ssUser, err error) {\n\t//double duty as unique name/login\n\tsuffix, err := diceware.Generate(2)\n\tif err != nil {\n\t\tsuffix = []string{string(time.Now().Nanosecond()), string(time.Now().UnixNano())}\n\t}\n\tpassword, err := diceware.Generate(3)\n\tif err != nil {\n\t\tpassword = []string{string(time.Now().Nanosecond()), os.Getenv(\"OPS_TEAM_NAME\"), string(time.Now().UnixNano())}\n\t}\n\terr = nil\n\tuser.login = os.Getenv(\"OPS_TEAM_NAME\") + \"-\" + strings.Join(suffix, \"\")\n\tuser.password = strings.Join(password, \"\")\n\n\tcreatePostForm := url.Values{}\n\tcreatePostForm.Set(\"login\", user.login)\n\tcreatePostForm.Set(\"name\", user.login)\n\tcreatePostForm.Set(\"password\", user.password)\n\n\treq, err := http.NewRequest(\"POST\", host+\"/api/users/create\", strings.NewReader(createPostForm.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(adminToken, \"\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tcreateResp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer createResp.Body.Close()\n\tif createResp.StatusCode != 200 {\n\t\terr = errors.New(\"Failed to create user, expected status code 200 got\" + string(createResp.StatusCode))\n\t}\n\treturn\n}", "func CreateNewUser(name, password string) error {\n\tif AllUsers[Username(name)] != nil {\n\t\treturn UserExists(name)\n\t}\n\ttoken, err := NewAuthToken([]byte(password))\n\tif err != nil {\n\t\treturn err\n\t}\n\tAllUsers[Username(name)] = &token\n\treturn SyncAllUsers()\n}", "func CreateUser(user model.User) {\n\tfmt.Println(user)\n}", "func (client IdentityClient) createUser(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/users\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateUserResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func RegisterNewUser(user *model.RegisterUserRequest) error {\n\tdb, err := connectDB()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn errors.New(\"Cannat connect to database\")\n\t}\n\n\tdefer db.Close()\n\tinsertStmt := `INSERT INTO users.members \n\t\t\t\t\t\t(p_token, username, firstname, lastname, email, phone) \n\t\t\t\t VALUES \n\t\t\t\t\t\t($1, $2, $3, $4, $5, $6);`\n\n\t_, err = db.Exec(insertStmt, user.PToken, user.UserName, user.FirstName, user.LastName, user.Email, user.Phone)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn errors.New(\"Cannot register new user\")\n\t}\n\n\treturn nil\n}", "func setupUserWithPIN(ctx, ctxForCleanUp context.Context, userName string, cmdRunner *hwsecremote.CmdRunnerRemote, helper *hwsecremote.CmdHelperRemote, userParam pinWeaverWithAuthAPIParam) error {\n\tcryptohomeHelper := helper.CryptohomeClient()\n\n\t// Start an Auth session and get an authSessionID.\n\t_, authSessionID, err := cryptohomeHelper.StartAuthSession(ctx, userName, false /*ephemeral*/, uda.AuthIntent_AUTH_INTENT_DECRYPT)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to start auth session for PIN authentication\")\n\t}\n\tdefer cryptohomeHelper.InvalidateAuthSession(ctx, authSessionID)\n\n\tif err = cryptohomeHelper.CreatePersistentUser(ctx, authSessionID); err != nil {\n\t\treturn errors.Wrap(err, \"failed to create persistent user with auth session\")\n\t}\n\n\tif err = cryptohomeHelper.PreparePersistentVault(ctx, authSessionID, false); err != nil {\n\t\treturn errors.Wrap(err, \"failed to prepare persistent user with auth session\")\n\t}\n\tdefer cryptohomeHelper.Unmount(ctx, userName)\n\n\tif userParam.useAuthFactor {\n\t\terr = cryptohomeHelper.AddAuthFactor(ctx, authSessionID, passwordAuthFactorLabel, passwordAuthFactorSecret)\n\t} else {\n\t\terr = cryptohomeHelper.AddCredentialsWithAuthSession(ctx, userName, passwordAuthFactorSecret, passwordAuthFactorLabel, authSessionID, false /*kiosk*/)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to add password auth factor\")\n\t}\n\n\tleCredsBeforeAdd, err := getLeCredsFromDisk(ctx, cmdRunner)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get le creds from disk before add\")\n\t}\n\n\t// Add a PIN auth factor to the user.\n\tif userParam.useLegacyAddAPIForPin {\n\t\terr = cryptohomeHelper.AddVaultKey(ctx, userName, passwordAuthFactorSecret, passwordAuthFactorLabel, correctPINSecret, authFactorLabelPIN, true)\n\t} else {\n\t\tif userParam.useAuthFactor {\n\t\t\terr = cryptohomeHelper.AddPinAuthFactor(ctx, authSessionID, authFactorLabelPIN, correctPINSecret)\n\t\t} else {\n\t\t\terr = cryptohomeHelper.AddPinCredentialsWithAuthSession(ctx, authFactorLabelPIN, correctPINSecret, authSessionID)\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to add le credential\")\n\t}\n\tleCredsAfterAdd, err := getLeCredsFromDisk(ctx, cmdRunner)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get le creds from disk after add\")\n\t}\n\n\tif diff := cmp.Diff(leCredsAfterAdd, leCredsBeforeAdd); diff == \"\" {\n\t\treturn errors.Wrap(err, \"le cred file did not change after add\")\n\t}\n\treturn nil\n}", "func (server Server) CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User // make a user\n\tvar res models.APIResponse // make a response\n\n\terr := json.NewDecoder(r.Body).Decode(&user) //decode the user\n\tif err != nil {\n\t\tlog.Printf(\"Unable to decode the request body. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to decode the request body\", nil)\n\t}\n\tif user.Name == \"\" || user.Email == \"\" || user.Password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Blank users cannot be created\", nil)\n\t} else {\n\t\tinsertID := insertUser(user, server.db) // call insert user function and pass the note\n\t\tres = models.BuildAPIResponseSuccess(fmt.Sprintf(\"User Created with %d id\", insertID), nil) // format a response object\n\t}\n\tjson.NewEncoder(w).Encode(res)\n\n}", "func makeUserHost(listenPort int, target string, randseed int64) (host.Host, error) {\n\n\t// seed == 0, real cryptographic randomness\n\t// else, deterministic randomness source to make generated keys stay the same across multiple runs\n\tvar r io.Reader\n\tif randseed == 0 {\n\t\tr = rand.Reader\n\t} else {\n\t\tr = mrand.New(mrand.NewSource(randseed))\n\t}\n\n\t// Generate a key pair for this host. We will use it to obtain a valid host ID.\n\tpriv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate the libp2p host\n\tbasicHost, err := libp2p.New(\n\t\tcontext.Background(),\n\t\tlibp2p.ListenAddrStrings(fmt.Sprintf(\"/ip4/127.0.0.1/tcp/%d\", listenPort)),\n\t\tlibp2p.Identity(priv),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Printf(\"I am user node %s\\n\", basicHost.ID().Pretty())\n\tfmt.Printf(\"\\nNow run this on a different terminal in the user directory in order to connect to the same region node:\\ngo run *.go -port %d -peer %s\\n\\n\", listenPort+1, target)\n\n\treturn basicHost, nil\n}", "func (s *service) createUser(ctx context.Context, newUser *auth.User) error {\n\treturn s.repoMngr.User().Create(ctx, newUser)\n}", "func (server *Server) CreateUserPreferences(c *gin.Context) {\n\n\t//clear previous error if any\n\terrList = map[string]string{}\n\n\tuserPref := models.UserPreferences{}\n\n\tuid, err := auth.ExtractTokenID(c.Request)\n\tif err != nil {\n\t\terrList[\"Unauthorized\"] = \"Unauthorized\"\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"status\": http.StatusUnauthorized,\n\t\t\t\"error\": errList,\n\t\t})\n\t\treturn\n\t}\n\n\t// check if the user exist:\n\tuser := models.User{}\n\terr = server.DB.Debug().Model(models.User{}).Where(\"id = ?\", uid).Take(&user).Error\n\tif err != nil {\n\t\terrList[\"Unauthorized\"] = \"Unauthorized\"\n\t\tc.JSON(http.StatusUnauthorized, gin.H{\n\t\t\t\"status\": http.StatusUnauthorized,\n\t\t\t\"error\": errList,\n\t\t})\n\t\treturn\n\t}\n\n\tuserPref.UserID = uid //the authenticated user is the one creating the user preference\n\n\tuserPref.Prepare()\n\n\tuserPrefCreated, err := userPref.SaveUserPreferences(server.DB)\n\tif err != nil {\n\t\terrList := formaterror.FormatError(err.Error())\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"error\": errList,\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, gin.H{\n\t\t\"status\": http.StatusCreated,\n\t\t\"response\": userPrefCreated,\n\t})\n}", "func NewUser(c *fiber.Ctx) error {\n\tgetStatus(c, 200, \"success\")\n\treturn nil\n}", "func (s *Shell) CreateUser(c *cli.Context) (err error) {\n\tresp, err := s.HTTP.Get(\"/v2/users/\", nil)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := resp.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\tvar links jsonapi.Links\n\tvar users AdminUsersPresenters\n\tif err := s.deserializeAPIResponse(resp, &users, &links); err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tfor _, user := range users {\n\t\tif strings.EqualFold(user.Email, c.String(\"email\")) {\n\t\t\treturn s.errorOut(fmt.Errorf(\"user with email %s already exists\", user.Email))\n\t\t}\n\t}\n\n\tfmt.Println(\"Password of new user:\")\n\tpwd := s.PasswordPrompter.Prompt()\n\n\trequest := struct {\n\t\tEmail string `json:\"email\"`\n\t\tRole string `json:\"role\"`\n\t\tPassword string `json:\"password\"`\n\t}{\n\t\tEmail: c.String(\"email\"),\n\t\tRole: c.String(\"role\"),\n\t\tPassword: pwd,\n\t}\n\n\trequestData, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\n\tbuf := bytes.NewBuffer(requestData)\n\tresponse, err := s.HTTP.Post(\"/v2/users\", buf)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := response.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(response, &AdminUsersPresenter{}, \"Successfully created new API user\")\n}", "func UserCreate(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := auth.GetUserFromJSON(body)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"User\")\n\t\trespondErr(w, err)\n\t\tlog.Error(string(body[:]))\n\t\treturn\n\t}\n\n\tuuid := uuid.NewV4().String() // generate a new uuid to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\t// Get Result Object\n\tres, err := auth.CreateUser(uuid, urlUser, postBody.FirstName, postBody.LastName, postBody.Organization, postBody.Description,\n\t\tpostBody.Projects, token, postBody.Email, postBody.ServiceRoles, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"duplicate\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"invalid\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func createUser(username string, attrs User) bool {\n\tlog.Printf(\"Creating user: %s\", username)\n\t// ensure directory containing homedir exists\n\tif _, err := os.Stat(path.Dir(attrs.Home)); err != nil {\n\t\texec.Command(\"mkdir\", \"-p\", path.Dir(attrs.Home)).Run()\n\t}\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", fmt.Sprintf(addUserCommand, username))\n\tif _, err := cmd.CombinedOutput(); err != nil {\n\t\tlog.Printf(\"Error: Can't create user: %s: %s\", username, err)\n\t\treturn false\n\t}\n\treturn true\n}", "func Create(user User) error {\n\t\n}", "func CreateUser(person *Person) (err error) {\n\tif err = Config.DB.Create(person).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewUser(v bool) predicate.Session {\n\treturn predicate.Session(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldNewUser), v))\n\t})\n}", "func CreateUser(context *fiber.Ctx) error {\n\tnew_user := new(models.User)\n\tif err := context.BodyParser(new_user); err != nil {\n\t\treturn context.Status(503).SendString(err.Error())\n\t}\n\n\thash, err := hashPassword(new_user.Pswd)\n\tif err != nil {\n\t\tmy_error := new(my_error)\n\t\tmy_error.My_error = \"failed to make a hash for password\"\n\t\tmy_error.Error = err.Error()\n\t\treturn context.JSON(my_error)\n\t}\n\tnew_user.Pswd = hash\n\n\tcreation := queries.CreateUser(new_user)\n\tif creation != \"OK\" {\n\t\treturn context.Status(503).SendString(creation)\n\t}\n\treturn context.JSON(new_user)\n}", "func (s *BasePlSqlParserListener) EnterCreate_user(ctx *Create_userContext) {}", "func NewUser(vres *hyuserviews.User) *User {\n\tvar res *User\n\tswitch vres.View {\n\tcase \"default\", \"\":\n\t\tres = newUser(vres.Projected)\n\tcase \"id\":\n\t\tres = newUserID(vres.Projected)\n\t}\n\treturn res\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\trequestBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tvar user models.User\n\tif err = json.Unmarshal(requestBody, &user); err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tdb, err := database.OpenDbConnection()\n\tif err != nil {\n\t\tlog.Fatal(\"error\")\n\t}\n\n\trepository := repositories.UserRepository(db)\n\trepository.Create(user)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tdata := authInfo{}\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tutils.JSONRespnseWithErr(w, &utils.ErrPostDataNotCorrect)\n\t\treturn\n\t}\n\tmessage := models.SignUp(data.Email, data.Password, data.RoleID)\n\tutils.JSONResonseWithMessage(w, message)\n}", "func RegisterNewUser(c *soso.Context) {\n\treq := c.RequestMap\n\trequest := &auth_protocol.NewUserRequest{}\n\n\tif value, ok := req[\"source\"].(string); ok {\n\t\trequest.Source = value\n\t}\n\n\tif value, ok := req[\"phone\"].(string); ok {\n\t\trequest.PhoneNumber = value\n\t}\n\n\tif value, ok := req[\"instagram_username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid instagram name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.InstagramUsername = value\n\t}\n\n\tif value, ok := req[\"username\"].(string); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\\t\")\n\t\tif !nameValidator.MatchString(value) {\n\t\t\tlog.Debug(\"name '%v' isn't valid\", value)\n\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Invalid user name\"))\n\t\t\treturn\n\t\t}\n\t\trequest.Username = value\n\t}\n\n\tif request.InstagramUsername == \"\" && request.Username == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User name or instagram name is required\"))\n\t\treturn\n\t}\n\n\tif request.PhoneNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"User phone number is required\"))\n\t\treturn\n\t}\n\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := authClient.RegisterNewUser(ctx, request)\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"ErrorCode\": resp.ErrorCode,\n\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t})\n}", "func CreateVMWithUserAssignedID(ctx context.Context, vmName, nicName, username, password string, id msi.Identity) (vm compute.VirtualMachine, err error) {\n\tnic, _ := network.GetNic(ctx, nicName)\n\tvmClient := getVMClient()\n\tfuture, err := vmClient.CreateOrUpdate(\n\t\tctx,\n\t\tconfig.GroupName(),\n\t\tvmName,\n\t\tcompute.VirtualMachine{\n\t\t\tLocation: to.StringPtr(config.Location()),\n\t\t\tIdentity: &compute.VirtualMachineIdentity{\n\t\t\t\tType: compute.ResourceIdentityTypeUserAssigned,\n\t\t\t\tUserAssignedIdentities: map[string]*compute.VirtualMachineIdentityUserAssignedIdentitiesValue{\n\t\t\t\t\t*id.ID: &compute.VirtualMachineIdentityUserAssignedIdentitiesValue{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVirtualMachineProperties: &compute.VirtualMachineProperties{\n\t\t\t\tHardwareProfile: &compute.HardwareProfile{\n\t\t\t\t\tVMSize: compute.VirtualMachineSizeTypesBasicA0,\n\t\t\t\t},\n\t\t\t\tStorageProfile: &compute.StorageProfile{\n\t\t\t\t\tImageReference: &compute.ImageReference{\n\t\t\t\t\t\tPublisher: to.StringPtr(publisher),\n\t\t\t\t\t\tOffer: to.StringPtr(offer),\n\t\t\t\t\t\tSku: to.StringPtr(sku),\n\t\t\t\t\t\tVersion: to.StringPtr(\"latest\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOsProfile: &compute.OSProfile{\n\t\t\t\t\tComputerName: to.StringPtr(vmName),\n\t\t\t\t\tAdminUsername: to.StringPtr(username),\n\t\t\t\t\tAdminPassword: to.StringPtr(password),\n\t\t\t\t},\n\t\t\t\tNetworkProfile: &compute.NetworkProfile{\n\t\t\t\t\tNetworkInterfaces: &[]compute.NetworkInterfaceReference{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: nic.ID,\n\t\t\t\t\t\t\tNetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{\n\t\t\t\t\t\t\t\tPrimary: to.BoolPtr(true),\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\tif err != nil {\n\t\treturn vm, errors.Wrap(err, \"failed to create VM\")\n\t}\n\terr = future.WaitForCompletionRef(ctx, vmClient.Client)\n\tif err != nil {\n\t\treturn vm, errors.Wrap(err, \"failed waiting for async operation to complete\")\n\t}\n\treturn future.Result(vmClient)\n}", "func CreateUser(response http.ResponseWriter, request *http.Request) {\n\n\t\n\t\trequest.ParseForm()\n\t\tdecoder := json.NewDecoder(request.Body)\n\t\tvar newUser User\n\t\t\n\t\terr := decoder.Decode(&newUser)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t\n newUser.Password=hashAndSalt([]byte(newUser.Password))\n\t\t\n\t\tinsertUser(newUser)\n\t\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n\tuser := new(User)\n\tuser.Token = validateToken(r.FormValue(\"token\"))\n\tuser.PasswordHash = validatePassHash(r.FormValue(\"passHash\"))\n\tuser.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n\tuser.PublicHash = computePublicHash(user.PublicKey)\n\tuser.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n\tlog.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n\tif !SaveUser(user) {\n\t\thttp.Error(w, \"That username is taken\", http.StatusBadRequest)\n\t}\n}", "func (rt *RestTester) CreateUser(username string, channels []string) {\n\tresponse := rt.SendAdminRequest(http.MethodPut, \"/{{.db}}/_user/\"+username, GetUserPayload(rt.TB, \"\", RestTesterDefaultUserPassword, \"\", rt.GetSingleTestDatabaseCollection(), channels, nil))\n\tRequireStatus(rt.TB, response, http.StatusCreated)\n}", "func (s *Service) CreateUser(c *tokay.Context) {\n\tuParams := userStruct{}\n\n\terr = c.BindJSON(&uParams)\n\tif errorAlert(\"Bind fall down\", err, c) {\n\t\treturn\n\t}\n\tuParams.ID = ai.Next(\"user\")\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(uParams.Hash), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn\n\t}\n\tuParams.Hash = string(hash)\n\n\ttime := time.Now().Format(\"Jan 2, 2006 at 3:04pm\")\n\tuParams.RegistrationTime = time\n\n\terr = db.UserCol.Insert(uParams)\n\tif errorAlert(\"Error: Input parameteres already used\", err, c) {\n\t\treturn\n\t}\n\n\tc.JSON(200, obj{\"ok\": \"true\"})\n}", "func (s *server) CreateUser(ctx context.Context, in *pb.UserRequest) (*pb.UserResponse, error) {\n\n\tlog.Printf(\"Received: %v\", \"create user\")\n\tif len(in.HashPassword) <= 6 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Invalid password\")\n\t}\n\thash, salt := hash(in.HashPassword)\n\n\temail, id, err := addUser(in.Email, hash, salt)\n\n\tid = id\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, \"database problem\")\n\t}\n\ttoken := GenerateSecureToken(32)\n\tis, err := CreateSession(in.Email, token)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, \"db problem\")\n\t}\n\n\t// add to profiles db\n\tCreateUser(email, token, \"Plese input your name\", \"Your description\")\n\t/*if res == false{\n\t\tlog.Printf(\"can create: %v\", err)\n\t\treturn nil,status.Error(codes.Internal,\"cant create\")\n\t}\n\t*/\n\n\treturn &pb.UserResponse{IsUser: is, Token: token}, nil\n}", "func (v *vpconnect) create() error {\n\tprint(&msg{Message: \"v.create(): Entering\", LogLevel: \"debug\"})\n\tdefer print(&msg{Message: \"v.create(): Returning\", LogLevel: \"debug\"})\n\n\tprint(&msg{Message: \"v.create(): Creating config for VPN type\", LogLevel: \"debug\"})\n\treturn v.createIpsecConfig()\n}", "func CreateNewUser(user model.User, password string) error {\n\n\t//Maybe we want to do this asynchronous\n\thash, err := bcrypt.GenerateFromPassword([]byte(password), 12)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser.HashedPassword = hash\n\n\taccess := data.CreateDataAccess()\n\terr = access.CreateUser(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//Created\n\treturn nil\n\n}", "func (p *AccumuloProxyClient) CreateLocalUser(login []byte, user string, password []byte) (err error) {\n\tif err = p.sendCreateLocalUser(login, user, password); err != nil {\n\t\treturn\n\t}\n\treturn p.recvCreateLocalUser()\n}", "func (app *appContext) newUser(req newUserDTO, confirmed bool) (f errorFunc, success bool) {\n\texistingUser, _, _ := app.jf.UserByName(req.Username, false)\n\tif existingUser.Name != \"\" {\n\t\tf = func(gc *gin.Context) {\n\t\t\tmsg := fmt.Sprintf(\"User %s already exists\", req.Username)\n\t\t\tapp.info.Printf(\"%s: New user failed: %s\", req.Code, msg)\n\t\t\trespond(401, \"errorUserExists\", gc)\n\t\t}\n\t\tsuccess = false\n\t\treturn\n\t}\n\tvar discordUser DiscordUser\n\tdiscordVerified := false\n\tif discordEnabled {\n\t\tif req.DiscordPIN == \"\" {\n\t\t\tif app.config.Section(\"discord\").Key(\"required\").MustBool(false) {\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Discord verification not completed\", req.Code)\n\t\t\t\t\trespond(401, \"errorDiscordVerification\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tdiscordUser, discordVerified = app.discord.verifiedTokens[req.DiscordPIN]\n\t\t\tif !discordVerified {\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Discord PIN was invalid\", req.Code)\n\t\t\t\t\trespond(401, \"errorInvalidPIN\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tvar matrixUser MatrixUser\n\tmatrixVerified := false\n\tif matrixEnabled {\n\t\tif req.MatrixPIN == \"\" {\n\t\t\tif app.config.Section(\"matrix\").Key(\"required\").MustBool(false) {\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Matrix verification not completed\", req.Code)\n\t\t\t\t\trespond(401, \"errorMatrixVerification\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tuser, ok := app.matrix.tokens[req.MatrixPIN]\n\t\t\tif !ok || !user.Verified {\n\t\t\t\tmatrixVerified = false\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Matrix PIN was invalid\", req.Code)\n\t\t\t\t\trespond(401, \"errorInvalidPIN\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmatrixVerified = user.Verified\n\t\t\tmatrixUser = *user.User\n\n\t\t}\n\t}\n\ttelegramTokenIndex := -1\n\tif telegramEnabled {\n\t\tif req.TelegramPIN == \"\" {\n\t\t\tif app.config.Section(\"telegram\").Key(\"required\").MustBool(false) {\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Telegram verification not completed\", req.Code)\n\t\t\t\t\trespond(401, \"errorTelegramVerification\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tfor i, v := range app.telegram.verifiedTokens {\n\t\t\t\tif v.Token == req.TelegramPIN {\n\t\t\t\t\ttelegramTokenIndex = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif telegramTokenIndex == -1 {\n\t\t\t\tf = func(gc *gin.Context) {\n\t\t\t\t\tapp.debug.Printf(\"%s: New user failed: Telegram PIN was invalid\", req.Code)\n\t\t\t\t\trespond(401, \"errorInvalidPIN\", gc)\n\t\t\t\t}\n\t\t\t\tsuccess = false\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tif emailEnabled && app.config.Section(\"email_confirmation\").Key(\"enabled\").MustBool(false) && !confirmed {\n\t\tclaims := jwt.MapClaims{\n\t\t\t\"valid\": true,\n\t\t\t\"invite\": req.Code,\n\t\t\t\"email\": req.Email,\n\t\t\t\"username\": req.Username,\n\t\t\t\"password\": req.Password,\n\t\t\t\"telegramPIN\": req.TelegramPIN,\n\t\t\t\"exp\": time.Now().Add(time.Hour * 12).Unix(),\n\t\t\t\"type\": \"confirmation\",\n\t\t}\n\t\ttk := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\t\tkey, err := tk.SignedString([]byte(os.Getenv(\"JFA_SECRET\")))\n\t\tif err != nil {\n\t\t\tf = func(gc *gin.Context) {\n\t\t\t\tapp.info.Printf(\"Failed to generate confirmation token: %v\", err)\n\t\t\t\trespond(500, \"errorUnknown\", gc)\n\t\t\t}\n\t\t\tsuccess = false\n\t\t\treturn\n\t\t}\n\t\tinv := app.storage.invites[req.Code]\n\t\tinv.Keys = append(inv.Keys, key)\n\t\tapp.storage.invites[req.Code] = inv\n\t\tapp.storage.storeInvites()\n\t\tf = func(gc *gin.Context) {\n\t\t\tapp.debug.Printf(\"%s: Email confirmation required\", req.Code)\n\t\t\trespond(401, \"confirmEmail\", gc)\n\t\t\tmsg, err := app.email.constructConfirmation(req.Code, req.Username, key, app, false)\n\t\t\tif err != nil {\n\t\t\t\tapp.err.Printf(\"%s: Failed to construct confirmation email: %v\", req.Code, err)\n\t\t\t} else if err := app.email.send(msg, req.Email); err != nil {\n\t\t\t\tapp.err.Printf(\"%s: Failed to send user confirmation email: %v\", req.Code, err)\n\t\t\t} else {\n\t\t\t\tapp.info.Printf(\"%s: Sent user confirmation email to \\\"%s\\\"\", req.Code, req.Email)\n\t\t\t}\n\t\t}\n\t\tsuccess = false\n\t\treturn\n\t}\n\n\tuser, status, err := app.jf.NewUser(req.Username, req.Password)\n\tif !(status == 200 || status == 204) || err != nil {\n\t\tf = func(gc *gin.Context) {\n\t\t\tapp.err.Printf(\"%s New user failed (%d): %v\", req.Code, status, err)\n\t\t\trespond(401, app.storage.lang.Admin[app.storage.lang.chosenAdminLang].Notifications.get(\"errorUnknown\"), gc)\n\t\t}\n\t\tsuccess = false\n\t\treturn\n\t}\n\tapp.storage.loadProfiles()\n\tinvite := app.storage.invites[req.Code]\n\tapp.checkInvite(req.Code, true, req.Username)\n\tif emailEnabled && app.config.Section(\"notifications\").Key(\"enabled\").MustBool(false) {\n\t\tfor address, settings := range invite.Notify {\n\t\t\tif settings[\"notify-creation\"] {\n\t\t\t\tgo func() {\n\t\t\t\t\tmsg, err := app.email.constructCreated(req.Code, req.Username, req.Email, invite, app, false)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tapp.err.Printf(\"%s: Failed to construct user creation notification: %v\", req.Code, err)\n\t\t\t\t\t} else if err := app.email.send(msg, address); err != nil {\n\t\t\t\t\t\tapp.err.Printf(\"%s: Failed to send user creation notification: %v\", req.Code, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tapp.info.Printf(\"%s: Sent user creation notification to %v\", req.Code, address)\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t}\n\t}\n\tid := user.ID\n\tif invite.Profile != \"\" {\n\t\tapp.debug.Printf(\"Applying settings from profile \\\"%s\\\"\", invite.Profile)\n\t\tprofile, ok := app.storage.profiles[invite.Profile]\n\t\tif !ok {\n\t\t\tprofile = app.storage.profiles[\"Default\"]\n\t\t}\n\t\tif profile.Policy.BlockedTags != nil {\n\t\t\tapp.debug.Printf(\"Applying policy from profile \\\"%s\\\"\", invite.Profile)\n\t\t\tstatus, err = app.jf.SetPolicy(id, profile.Policy)\n\t\t\tif !((status == 200 || status == 204) && err == nil) {\n\t\t\t\tapp.err.Printf(\"%s: Failed to set user policy (%d): %v\", req.Code, status, err)\n\t\t\t}\n\t\t}\n\t\tif profile.Configuration.GroupedFolders != nil && len(profile.Displayprefs) != 0 {\n\t\t\tapp.debug.Printf(\"Applying homescreen from profile \\\"%s\\\"\", invite.Profile)\n\t\t\tstatus, err = app.jf.SetConfiguration(id, profile.Configuration)\n\t\t\tif (status == 200 || status == 204) && err == nil {\n\t\t\t\tstatus, err = app.jf.SetDisplayPreferences(id, profile.Displayprefs)\n\t\t\t}\n\t\t\tif !((status == 200 || status == 204) && err == nil) {\n\t\t\t\tapp.err.Printf(\"%s: Failed to set configuration template (%d): %v\", req.Code, status, err)\n\t\t\t}\n\t\t}\n\t}\n\t// if app.config.Section(\"password_resets\").Key(\"enabled\").MustBool(false) {\n\tif req.Email != \"\" {\n\t\tapp.storage.emails[id] = EmailAddress{Addr: req.Email, Contact: true}\n\t\tapp.storage.storeEmails()\n\t}\n\tif app.config.Section(\"ombi\").Key(\"enabled\").MustBool(false) {\n\t\tapp.storage.loadOmbiTemplate()\n\t\tif len(app.storage.ombi_template) != 0 {\n\t\t\terrors, code, err := app.ombi.NewUser(req.Username, req.Password, req.Email, app.storage.ombi_template)\n\t\t\tif err != nil || code != 200 {\n\t\t\t\tapp.info.Printf(\"Failed to create Ombi user (%d): %s\", code, err)\n\t\t\t\tapp.debug.Printf(\"Errors reported by Ombi: %s\", strings.Join(errors, \", \"))\n\t\t\t} else {\n\t\t\t\tapp.info.Println(\"Created Ombi user\")\n\t\t\t}\n\t\t}\n\t}\n\texpiry := time.Time{}\n\tif invite.UserExpiry {\n\t\tapp.storage.usersLock.Lock()\n\t\tdefer app.storage.usersLock.Unlock()\n\t\texpiry = time.Now().AddDate(0, invite.UserMonths, invite.UserDays).Add(time.Duration((60*invite.UserHours)+invite.UserMinutes) * time.Minute)\n\t\tapp.storage.users[id] = expiry\n\t\tif err := app.storage.storeUsers(); err != nil {\n\t\t\tapp.err.Printf(\"Failed to store user duration: %v\", err)\n\t\t}\n\t}\n\tif discordEnabled && discordVerified {\n\t\tdiscordUser.Contact = req.DiscordContact\n\t\tif app.storage.discord == nil {\n\t\t\tapp.storage.discord = map[string]DiscordUser{}\n\t\t}\n\t\tapp.storage.discord[user.ID] = discordUser\n\t\tif err := app.storage.storeDiscordUsers(); err != nil {\n\t\t\tapp.err.Printf(\"Failed to store Discord users: %v\", err)\n\t\t} else {\n\t\t\tdelete(app.discord.verifiedTokens, req.DiscordPIN)\n\t\t}\n\t}\n\tif telegramEnabled && telegramTokenIndex != -1 {\n\t\ttgToken := app.telegram.verifiedTokens[telegramTokenIndex]\n\t\ttgUser := TelegramUser{\n\t\t\tChatID: tgToken.ChatID,\n\t\t\tUsername: tgToken.Username,\n\t\t\tContact: req.TelegramContact,\n\t\t}\n\t\tif lang, ok := app.telegram.languages[tgToken.ChatID]; ok {\n\t\t\ttgUser.Lang = lang\n\t\t}\n\t\tif app.storage.telegram == nil {\n\t\t\tapp.storage.telegram = map[string]TelegramUser{}\n\t\t}\n\t\tapp.storage.telegram[user.ID] = tgUser\n\t\tif err := app.storage.storeTelegramUsers(); err != nil {\n\t\t\tapp.err.Printf(\"Failed to store Telegram users: %v\", err)\n\t\t} else {\n\t\t\tapp.telegram.verifiedTokens[len(app.telegram.verifiedTokens)-1], app.telegram.verifiedTokens[telegramTokenIndex] = app.telegram.verifiedTokens[telegramTokenIndex], app.telegram.verifiedTokens[len(app.telegram.verifiedTokens)-1]\n\t\t\tapp.telegram.verifiedTokens = app.telegram.verifiedTokens[:len(app.telegram.verifiedTokens)-1]\n\t\t}\n\t}\n\tif matrixVerified {\n\t\tmatrixUser.Contact = req.MatrixContact\n\t\tdelete(app.matrix.tokens, req.MatrixPIN)\n\t\tif app.storage.matrix == nil {\n\t\t\tapp.storage.matrix = map[string]MatrixUser{}\n\t\t}\n\t\tapp.storage.matrix[user.ID] = matrixUser\n\t\tif err := app.storage.storeMatrixUsers(); err != nil {\n\t\t\tapp.err.Printf(\"Failed to store Matrix users: %v\", err)\n\t\t}\n\t}\n\tif (emailEnabled && app.config.Section(\"welcome_email\").Key(\"enabled\").MustBool(false) && req.Email != \"\") || telegramTokenIndex != -1 || discordVerified {\n\t\tname := app.getAddressOrName(user.ID)\n\t\tapp.debug.Printf(\"%s: Sending welcome message to %s\", req.Username, name)\n\t\tmsg, err := app.email.constructWelcome(req.Username, expiry, app, false)\n\t\tif err != nil {\n\t\t\tapp.err.Printf(\"%s: Failed to construct welcome message: %v\", req.Username, err)\n\t\t} else if err := app.sendByID(msg, user.ID); err != nil {\n\t\t\tapp.err.Printf(\"%s: Failed to send welcome message: %v\", req.Username, err)\n\t\t} else {\n\t\t\tapp.info.Printf(\"%s: Sent welcome message to \\\"%s\\\"\", req.Username, name)\n\t\t}\n\t}\n\tapp.jf.CacheExpiry = time.Now()\n\tsuccess = true\n\treturn\n}", "func (p *politeiawww) processNewUser(nu www.NewUser) (*www.NewUserReply, error) {\n\tlog.Tracef(\"processNewUser: %v\", nu.Username)\n\n\t// Format and validate user credentials\n\tnu.Email = strings.ToLower(nu.Email)\n\tif !validEmail.MatchString(nu.Email) {\n\t\tlog.Debugf(\"processNewUser: invalid email '%v'\", nu.Email)\n\t\treturn nil, www.UserError{\n\t\t\tErrorCode: www.ErrorStatusMalformedEmail,\n\t\t}\n\t}\n\terr := validatePubKey(nu.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnu.Username = formatUsername(nu.Username)\n\terr = validateUsername(nu.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The client should be hashing the password before\n\t// sending it to politeiawww. This validation is only\n\t// relevant if the client failed to hash the password\n\t// or does not include a password in the request.\n\terr = validatePassword(nu.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if user already exists\n\tu, err := p.userByEmail(nu.Email)\n\tswitch err {\n\tcase nil:\n\t\t// User exists\n\n\t\t// Return if the user is already verified\n\t\tif u.NewUserVerificationToken == nil {\n\t\t\tlog.Debugf(\"processNewUser: '%v' already verified\",\n\t\t\t\tnu.Username)\n\t\t\treturn &www.NewUserReply{}, nil\n\t\t}\n\n\t\t// User is not already verified. Check if the verification token\n\t\t// has expired. If the token has not expired yet, we simply return.\n\t\t// The user will have to wait until the token expires before a\n\t\t// new one will be sent. If the token has expired, we update the\n\t\t// user in the database and send the user a new token. The user\n\t\t// identity will be updated if the request specifies a new public\n\t\t// key.\n\t\tif u.NewUserVerificationExpiry > time.Now().Unix() {\n\t\t\tlog.Debugf(\"processNewUser: '%v' not verified, \"+\n\t\t\t\t\"token not expired\", nu.Username)\n\t\t\treturn &www.NewUserReply{}, nil\n\t\t}\n\n\t\t// Ensure public key is unique\n\t\tusr, err := p.db.UserGetByPubKey(nu.PublicKey)\n\t\tif err != nil {\n\t\t\tif err == user.ErrUserNotFound {\n\t\t\t\t// Pubkey is unique, but is not the same pubkey that\n\t\t\t\t// the user originally signed up with. This is fine.\n\t\t\t\t// The user's identity just needs to be updated.\n\t\t\t\tid, err := user.NewIdentity(nu.PublicKey)\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 = u.AddIdentity(*id)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tswitch {\n\t\t\tcase usr.ID.String() == u.ID.String():\n\t\t\t\t// Pubkey exists and belongs to this user. This is\n\t\t\t\t// ok. It just means that the user is requesting a\n\t\t\t\t// new verification token using the same identity\n\t\t\t\t// that they signed up with. Continue.\n\t\t\tdefault:\n\t\t\t\t// Pubkey exists and belongs to another user\n\t\t\t\treturn nil, www.UserError{\n\t\t\t\t\tErrorCode: www.ErrorStatusDuplicatePublicKey,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Generate a new verification token\n\t\ttokenb, expiry, err := newVerificationTokenAndExpiry()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Email the verification token before updating the\n\t\t// database. If the email fails, the database won't\n\t\t// be updated.\n\t\terr = p.emailNewUserVerificationLink(u.Email,\n\t\t\thex.EncodeToString(tokenb), u.Username)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"processNewUser: mail verification \"+\n\t\t\t\t\"token failed for '%v': %v\", u.Email, err)\n\t\t\treturn &www.NewUserReply{}, nil\n\t\t}\n\n\t\t// Update user record with the verification token and\n\t\t// the new identity if one was set.\n\t\tu.NewUserVerificationToken = tokenb\n\t\tu.NewUserVerificationExpiry = expiry\n\t\terr = p.db.UserUpdate(*u)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Send reply. Only return the verification token in\n\t\t// the reply if the mail server has been disabled.\n\t\tvar t string\n\t\tif p.smtp.disabled {\n\t\t\tt = hex.EncodeToString(u.NewUserVerificationToken)\n\t\t}\n\t\treturn &www.NewUserReply{\n\t\t\tVerificationToken: t,\n\t\t}, nil\n\tcase user.ErrUserNotFound:\n\t\t// User doesn't exist; continue\n\tdefault:\n\t\t// All other errors\n\t\treturn nil, err\n\t}\n\n\t// User does not exist. Create a new user.\n\n\t// Ensure username is unique\n\t_, err = p.db.UserGetByUsername(nu.Username)\n\tswitch err {\n\tcase nil:\n\t\t// Duplicate username\n\t\treturn nil, www.UserError{\n\t\t\tErrorCode: www.ErrorStatusDuplicateUsername,\n\t\t}\n\tcase user.ErrUserNotFound:\n\t\t// Username does not exist; continue\n\tdefault:\n\t\treturn nil, err\n\t}\n\n\t// Ensure public key is unique\n\t_, err = p.db.UserGetByPubKey(nu.PublicKey)\n\tswitch err {\n\tcase user.ErrUserNotFound:\n\t\t// Pubkey is unique; continue\n\tcase nil:\n\t\t// Duplicate pubkey\n\t\treturn nil, www.UserError{\n\t\t\tErrorCode: www.ErrorStatusDuplicatePublicKey,\n\t\t}\n\tdefault:\n\t\t// All other errors\n\t\treturn nil, err\n\t}\n\n\t// Create user\n\thashedPass, err := p.hashPassword(nu.Password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttokenb, expiry, err := newVerificationTokenAndExpiry()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewUser := user.User{\n\t\tEmail: nu.Email,\n\t\tUsername: nu.Username,\n\t\tHashedPassword: hashedPass,\n\t\tNewUserVerificationToken: tokenb,\n\t\tNewUserVerificationExpiry: expiry,\n\t}\n\tid, err := user.NewIdentity(nu.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = newUser.AddIdentity(*id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Try to email the verification link first; if it fails,\n\t// then the new user won't be created.\n\t//\n\t// This is conditional on the email server being setup.\n\terr = p.emailNewUserVerificationLink(newUser.Email,\n\t\thex.EncodeToString(tokenb), newUser.Username)\n\tif err != nil {\n\t\tlog.Errorf(\"processNewUser: mail verification token \"+\n\t\t\t\"failed for '%v': %v\", newUser.Email, err)\n\t\treturn &www.NewUserReply{}, nil\n\t}\n\n\t// Save new user to the database\n\terr = p.db.UserNew(newUser)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set paywall info for the user. This had to wait until after the\n\t// user was already created in the db because the db sets the\n\t// paywall address index when the user is created, and the paywall\n\t// address index is used to generate the paywall info. Lookup the\n\t// user from the db to get the paywall address index.\n\tu, err = p.db.UserGetByUsername(newUser.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = p.GenerateNewUserPaywall(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Update memory cache\n\tp.setUserEmailsCache(u.Email, u.ID)\n\n\tlog.Infof(\"New user created: %v\", u.Username)\n\n\t// Only return the verification token in the reply\n\t// if the mail server has been disabled.\n\tvar t string\n\tif p.smtp.disabled {\n\t\tt = hex.EncodeToString(u.NewUserVerificationToken)\n\t}\n\treturn &www.NewUserReply{\n\t\tVerificationToken: t,\n\t}, nil\n}", "func CreateCurrentUserRsvp(w http.ResponseWriter, r *http.Request) {\n\tid := r.Header.Get(\"HackIllinois-Identity\")\n\n\tif id == \"\" {\n\t\terrors.WriteError(w, r, errors.MalformedRequestError(\"Must provide id in request.\", \"Must provide id in request.\"))\n\t\treturn\n\t}\n\n\tisAccepted, isActive, err := service.IsApplicantAcceptedAndActive(id)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not determine status of applicant decision, which is needed to create an RSVP for the user.\"))\n\t\treturn\n\t}\n\n\tif !isAccepted {\n\t\terrors.WriteError(w, r, errors.AttributeMismatchError(\"Applicant not accepted.\", \"Applicant must be accepted to RSVP.\"))\n\t\treturn\n\t}\n\n\tif !isActive {\n\t\terrors.WriteError(w, r, errors.AttributeMismatchError(\"Applicant decision has expired.\", \"Applicant decision has expired.\"))\n\t\treturn\n\t}\n\n\trsvp := datastore.NewDataStore(config.RSVP_DEFINITION)\n\terr = json.NewDecoder(r.Body).Decode(&rsvp)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not decode user rsvp information. Failure in JSON validation or incorrect rsvp definition.\"))\n\t\treturn\n\t}\n\n\trsvp.Data[\"id\"] = id\n\n\tregistration_data, err := service.GetRegistrationData(id)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not retrieve registration data.\"))\n\t\treturn\n\t}\n\n\trsvp.Data[\"registrationData\"] = registration_data\n\n\terr = service.CreateUserRsvp(id, rsvp)\n\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not create an RSVP for the user.\"))\n\t\treturn\n\t}\n\n\tisAttending, ok := rsvp.Data[\"isAttending\"].(bool)\n\n\tif !ok {\n\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Failure in parsing user rsvp\"))\n\t\treturn\n\t}\n\n\tif isAttending {\n\t\terr = service.AddAttendeeRole(id)\n\n\t\tif err != nil {\n\t\t\terrors.WriteError(w, r, errors.AuthorizationError(err.Error(), \"Could not add Attendee role to applicant.\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tupdated_rsvp, err := service.GetUserRsvp(id)\n\tif err != nil {\n\t\terrors.WriteError(w, r, errors.DatabaseError(err.Error(), \"Could not get user's RSVP.\"))\n\t\treturn\n\t}\n\n\tif isAttending {\n\t\tmail_template := \"rsvp_confirmation\"\n\t\terr = service.SendUserMail(id, mail_template)\n\n\t\tif err != nil {\n\t\t\terrors.WriteError(w, r, errors.InternalError(err.Error(), \"Could not send user RSVP confirmation mail.\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tjson.NewEncoder(w).Encode(updated_rsvp)\n}", "func (c *Client) createUser(ctx context.Context, user *UserToCreate) (string, error) {\n\tif user == nil {\n\t\tuser = &UserToCreate{}\n\t}\n\n\trequest, err := user.validatedRequest()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcall := c.is.Relyingparty.SignupNewUser(request)\n\tc.setHeader(call)\n\tresp, err := call.Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", handleServerError(err)\n\t}\n\treturn resp.LocalId, nil\n}", "func CreateUser(db *mongo.Client, w http.ResponseWriter, r *http.Request) {\n\tuser, err := parseUser(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tuser.Password = encryptPassword([]byte(user.Password))\n\t_, err = db.Database(\"charon\").Collection(\"users\").InsertOne(context.TODO(), user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tio.WriteString(w, \"User successfully added.\")\n}", "func CreateUser(ns string, login string, name string, email string) *jenkinsv1.User {\n\tid := naming.ToValidName(login)\n\tuser := &jenkinsv1.User{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: id,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tSpec: jenkinsv1.UserDetails{\n\t\t\tLogin: login,\n\t\t\tName: name,\n\t\t\tEmail: email,\n\t\t},\n\t}\n\treturn user\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqID(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t}\n\n\tu := model.UserModel{\n\t\t//BaseModel: model.BaseModel{},\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\t//fmt.Println()\n\t//log.Info(r.Username)\n\t//log.Info(r.Password)\n\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t}\n\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t}\n\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatabase, nil)\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\tSendResponse(c, nil, rsp)\n}", "func CreateUser(connection fiGo.IConnection, figoUser FigoUser) (string, error) {\n\tvar recoveryPassword string\n\n\t// setup new figo-user\n\tanswerByte, err := connection.CreateUser(figoUser.Username, figoUser.Email, figoUser.Password)\n\tif err != nil {\n\t\tlog.Println(string(answerByte))\n\t\treturn recoveryPassword, err\n\t}\n\n\t// try to get recoveryPassword\n\tjsonParsed, err := gabs.ParseJSON(answerByte)\n\trecoveryPassword, ok := jsonParsed.Path(\"recovery_password\").Data().(string)\n\tif !ok {\n\t\treturn recoveryPassword, ErrRecoveryPassword\n\t}\n\treturn recoveryPassword, nil\n}", "func (e *env) NewUserToken(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tw.Write([]byte(\"User token:\" + e.authState.GenerateRegisterToken(\"user\")))\n\t\treturn\n\tdefault:\n\t}\n}", "func (s *initServer) CreateUser(ctx context.Context, in *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {\t\n\tresp := createUserResp(ctx)\n\n\tc := newConn(\"createUser:user\")\n\tu := pbUser.NewUserServiceClient(c)\n\tdefer c.Close()\n\n\tcode, err := handleAuthCheck(ctx, u); \n\tif err != nil {\n\t\treturn resp(err.Error(), code)\n\t}\n\n\tres, err := u.UserCreate(ctx, &pbUser.UserCreateRequest{\n\t\tLogin: in.GetLogin(),\n\t\tName: in.GetName(),\n\t\tEmail: in.GetEmail(),\n\t\tPassword: in.GetPassword(),\n\t})\n\n\tif err != nil {\n\t\treturn resp(err.Error(), res.Code)\n\t}\n\n\treturn resp(res.GetMessage(), res.Code)\n}", "func CreateRemoteUser(settings *playfab.Settings, postData *CreateRemoteUserRequestModel, entityToken string) (*CreateRemoteUserResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/MultiplayerServer/CreateRemoteUser\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &CreateRemoteUserResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func (_obj *DataService) CreateUser(wx_id string, userInfo *UserInfo, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_string(wx_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = userInfo.WriteBlock(_os, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"createUser\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (c *Client) NewUser(nu *www.NewUser) (*www.NewUserReply, error) {\n\tresponseBody, err := c.makeRequest(http.MethodPost,\n\t\twww.PoliteiaWWWAPIRoute, www.RouteNewUser, nu)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar nur www.NewUserReply\n\terr = json.Unmarshal(responseBody, &nur)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal NewUserReply: %v\", err)\n\t}\n\n\tif c.cfg.Verbose {\n\t\terr := prettyPrintJSON(nur)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &nur, nil\n}", "func (h *Handler) SignUpUser(args []string) error {\n\tif h.CurrentUser.Root {\n\t\t//fmt.Println(args)\n\t\tswitch len(args) {\n\t\tcase 3:\n\t\t\tname := args[1]\n\t\t\tpassword := args[2]\n\t\t\terr := models.CreateUser(name, password, false)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = h.writeToUser(\"Password for %s is set!\", name)\n\t\t\treturn err\n\t\t\t//TODO - not working, because `h.Term.ReadPassword` behaves unconsistent\n\t\t\t//\t\tcase 2:\n\t\t\t//\t\t\tname := args[1]\n\t\t\t//\t\t\t//\t\t\tfmt.Println(\"Waiting for password\")\n\t\t\t//\t\t\t//\t\t\th.Term.Write([]byte(fmt.Sprintf(\"\\nEnter password for ordinary user %s:\\n\", name)))\n\t\t\t//\t\t\tpassword, err := h.Term.ReadPassword(fmt.Sprintf(\"Enter password for user `%s`:\", name))\n\t\t\t//\t\t\th.Term.SetPrompt(h.PrintPrompt())\n\t\t\t//\t\t\tif err != nil {\n\t\t\t//\t\t\t\treturn err\n\t\t\t//\t\t\t}\n\t\t\t//\t\t\t//\t\t\tfmt.Println(\"Password recieved\", password)\n\t\t\t//\t\t\t//\t\t\tfmt.Println(\"Prompt updated, creating user\")\n\t\t\t//\t\t\treturn models.CreateUser(name, password, false)\n\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Try `\\\\r someUserName [newPassword]` to sign up or change password for somebody!\")\n\t\t}\n\t}\n\treturn fmt.Errorf(\"You have to be root to signing up/registering/changing password!\")\n}", "func (w *ServerInterfaceWrapper) CreateUser(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.CreateUser(ctx)\n\treturn err\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\n\tuser, err := json.Marshal(map[string]string{\n\t\t\"name\": r.FormValue(\"name\"),\n\t\t\"email\": r.FormValue(\"email\"),\n\t\t\"nick\": r.FormValue(\"nick\"),\n\t\t\"password\": r.FormValue(\"password\"),\n\t})\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\turl := fmt.Sprintf(\"%s/users\", config.APIURL)\n\tresponse, err := http.Post(url, \"application/json\", bytes.NewBuffer(user))\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, response.StatusCode, nil)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tu := User{}\n\terr := json.NewDecoder(r.Body).Decode(&u)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = SaveUser(u.FullName, u.NickName, u.Email, u.Balance)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func CreateUserHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Debug(\"userservice.CreateUserHandler called\")\n\tusername, err := apiserver.Authn(apiserver.CREATE_USER_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.CreateUserRequest\n\t_ = json.NewDecoder(r.Body).Decode(&request)\n\n\tresp := msgs.CreateUserResponse{}\n\n\tvar ns string\n\tns, err = apiserver.GetNamespace(apiserver.Clientset, username, request.Namespace)\n\tif err != nil {\n\t\tresp.Status.Code = msgs.Error\n\t\tresp.Status.Msg = apiserver.VERSION_MISMATCH_ERROR\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tif request.ClientVersion != msgs.PGO_VERSION {\n\t\tresp.Status.Code = msgs.Error\n\t\tresp.Status.Msg = apiserver.VERSION_MISMATCH_ERROR\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tresp = CreateUser(&request, ns)\n\tjson.NewEncoder(w).Encode(resp)\n\n}", "func newUser(data userData, conn Connection) (User, error) {\n\tif data.Name == \"\" {\n\t\treturn nil, WithStack(InvalidArgumentError{Message: \"data.Name is empty\"})\n\t}\n\tif conn == nil {\n\t\treturn nil, WithStack(InvalidArgumentError{Message: \"conn is nil\"})\n\t}\n\treturn &user{\n\t\tdata: data,\n\t\tconn: conn,\n\t}, nil\n}", "func DemoUser() {\n\tu := new(User)\n\tu.SetFirstName(\"Roger\")\n\tu.SetAge(35)\n\tfmt.Println(u) // &{Roger 35}\n\n\tvip := new(VipUser)\n\tvip.SetFirstName(\"Ken\")\n\tvip.SetAge(35)\n\tvip.SetCs(\"Judy\")\n\tfmt.Println(vip.GetCs(), \"is customer service to\", vip.GetFirstName())\n}", "func (c APIClient) CreateUser(u *User) error {\n\treturn c.doHTTPBoth(\"PUT\", fmt.Sprintf(\"https://api.nsone.net/v1/account/users/%s\", u.Username), &u)\n}", "func (u *User) Create(c echo.Context, req *schemago.ReqCreateUser) (*schemago.SUser, error) {\n\t// if err := u.rbac.AccountCreate(c, req.RoleID, req.CompanyID, req.LocationID); err != nil {\n\t// \treturn nil, err\n\t// }\n\treq.Password = u.sec.Hash(req.Password)\n\treturn u.udb.Create(u.db, u.ce, req)\n}", "func NewUser(ctx *pulumi.Context,\n\tname string, args *UserArgs, opts ...pulumi.ResourceOption) (*User, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.InstanceId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceId'\")\n\t}\n\tif args.Source == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Source'\")\n\t}\n\tif args.UserName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'UserName'\")\n\t}\n\tif args.Password != nil {\n\t\targs.Password = pulumi.ToSecret(args.Password).(pulumi.StringPtrInput)\n\t}\n\tsecrets := pulumi.AdditionalSecretOutputs([]string{\n\t\t\"password\",\n\t})\n\topts = append(opts, secrets)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource User\n\terr := ctx.RegisterResource(\"alicloud:bastionhost/user:User\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (user *User) CreateUser(ctx context.Context, privateKey *rsa.PrivateKey, fullname string) (*User, error) {\n\tpbts, err := x509.MarshalPKIXPublicKey(privateKey.Public())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparas := map[string]interface{}{\n\t\t\"session_secret\": base64.StdEncoding.EncodeToString(pbts),\n\t\t\"full_name\": fullname,\n\t}\n\n\tvar u User\n\tif err := user.Request(ctx, \"POST\", \"/users\", paras, &u); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.privateKey = privateKey\n\treturn &u, nil\n}", "func createUser() (resp *iam.CreateUserOutput) {\n\n\treturn resp\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\t// create an empty user of type models.User\n\tvar user models.User\n\n\t// decode the json request to user\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to decode the request body. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !user.Valid() {\n\t\thttp.Error(w, \"Invalid User\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// set the header to content type x-www-form-urlencoded\n\t// Allow all origin to handle cors issue\n\tw.Header().Set(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\t//set the hash\n\thashedPass, err := user.HashPassword()\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create hash of the given password. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// call insert user function and pass the user\n\terr = database.InsertUser(user.Email, hashedPass, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to insert user. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttkn, err := models.CreateToken(user.Email)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create token. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// format a response object\n\tres := models.TokenResponse{\n\t\tToken: tkn,\n\t}\n\t// send the response\n\terr = json.NewEncoder(w).Encode(res)\n\tif err != nil {\n\t\tlogrus.Errorf(err.Error())\n\t\treturn\n\t}\n}", "func createUser_u(client *chef.Client, user chef.User) chef.UserResult {\n\tusrResult, err := client.Users.Create(user)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Issue creating user %+v\\n\", err)\n\t\tif cerr, ok := err.(*chef.ErrorResponse); ok {\n\t\t\tfmt.Fprintf(os.Stderr, \"Issue creating user err: %+v\\n\", cerr.Error())\n\t\t\tfmt.Fprintf(os.Stderr, \"Issue creating user code: %+v\\n\", cerr.StatusCode())\n\t\t\tfmt.Fprintf(os.Stderr, \"Issue creating user method: %+v\\n\", cerr.StatusMethod())\n\t\t\tfmt.Fprintf(os.Stderr, \"Issue creating user url: %+v\\n\", cerr.StatusURL().String())\n\t\t}\n\t}\n\treturn usrResult\n}", "func createContext(t *testing.T, role browser.Role, lic bool) context.Context {\n\tt.Helper()\n\n\tu := &browser.User{\n\t\tRole: role,\n\t\tLicense: lic,\n\t}\n\treturn context.WithValue(context.Background(), browser.UserContextKey, u)\n}", "func (m *Manager) Create(ctx context.Context, tx *sql.Tx, user v0.User) error {\n\t_, err := tx.ExecContext(ctx, `\n\t\t\t\tINSERT INTO users (\n\t\t\t\t\tname, \n\t\t\t\t\temail, \n\t\t\t\t\tprimary_public_key, \n\t\t\t\t\trecovery_public_key, \n\t\t\t\t\tsuper_user, \n\t\t\t\t\tauth_level, \n\t\t\t\t\tweight,\n\t\t\t\t\tuser_set\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\tuser.Name,\n\t\tuser.Email,\n\t\tuser.PrimaryPublicKey,\n\t\tuser.RecoveryPublicKey,\n\t\tuser.SuperUser,\n\t\tuser.AuthLevel,\n\t\tuser.Weight,\n\t\tuser.Set,\n\t)\n\treturn err\n}", "func Create(c *gin.Context) {\n\tlog.Info(\"User Create function called.\", lager.Data{\"X-Request-Id\": util.GetReqId(c)})\n\tvar r CreateRequest\n\tif err := c.Bind(&r); err != nil {\n\t\tSendResponse(c, errno.ErrBind, nil)\n\t\treturn\n\t}\n\n\tu := model.UserModel{\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n\n\t// Validate the data.\n\tif err := u.Validate(); err != nil {\n\t\tSendResponse(c, errno.ErrValidation, nil)\n\t\treturn\n\t}\n\n\t// Encrypt the user password.\n\tif err := u.Encrypt(); err != nil {\n\t\tSendResponse(c, errno.ErrEncrypt, nil)\n\t\treturn\n\t}\n\n\t// Insert the user to the database.\n\tif err := u.Create(); err != nil {\n\t\tSendResponse(c, errno.ErrDatebase, nil)\n\t\treturn\n\t}\n\n\trsp := CreateResponse{\n\t\tUsername: r.Username,\n\t}\n\n\t// Show the user information.\n\tSendResponse(c, nil, rsp)\n}", "func (s *service) SignUp(w http.ResponseWriter, r *http.Request) (interface{}, error) {\n\tctx := r.Context()\n\n\treq, err := decodeSignupRequest(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewUser := req.ToUser()\n\tuser, err := s.repoMngr.User().ByIdentity(ctx, req.UserAttribute(), req.Identity)\n\n\tif isUserCheckFailed(err) {\n\t\treturn nil, fmt.Errorf(\"failed to check user identity: %w\", err)\n\t}\n\n\tif isUserVerified(user, err) {\n\t\t// TODO To prevent user enumeration this should trigger\n\t\t// the OTP step for password reset instead of the signup OTP\n\t\t// step. Until password reset has been implemented, we will just\n\t\t// return a general error.\n\t\treturn nil, auth.ErrBadRequest(\"cannot register user\")\n\t}\n\n\tif isUserNotVerified(user, err) {\n\t\terr = s.reCreateUser(ctx, user.ID, newUser)\n\t}\n\n\tif isUserNonExistent(user, err) {\n\t\terr = s.createUser(ctx, newUser)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjwtToken, err := s.token.Create(\n\t\tctx,\n\t\tnewUser,\n\t\tauth.JWTPreAuthorized,\n\t\ttoken.WithOTPDeliveryMethod(req.Type),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.respond(ctx, w, newUser, jwtToken)\n}", "func CreateNewUser(username, password string) (userID string, err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var checkIfTheUserAlreadyExists = func(username string, userData map[string]interface{}) (err error) {\n var salt = userData[\"_salt\"].(string)\n var loginUsername = userData[\"_username\"].(string)\n\n if SHA256(username, salt) == loginUsername {\n err = createError(020)\n }\n\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n for _, userData := range users {\n err = checkIfTheUserAlreadyExists(username, userData.(map[string]interface{}))\n if err != nil {\n return\n }\n }\n\n var defaults = defaultsForNewUser(username, password)\n userID = defaults[\"_id\"].(string)\n users[userID] = defaults\n\n saveDatabase(data)\n\n return\n}", "func createUser() *User {\n\tcurUID++\n\tu := new(User)\n\tu.id = curUID\n\tu.cash = 0\n\tu.assets = make([]int, 0)\n\tu.sharesOwned = make(map[int]int)\n\treturn u\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tuid, err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest)\n\tif err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusCreated, gin.H{\n\t\t\"id\": uid,\n\t}))\n}", "func CreateUser(name string) (int, error) {\n\tlock, err := flock.NewLocker(lockfileName)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tdefer lock.Release()\n\n\tif err := lock.Acquire(time.Second * 10); err != nil {\n\t\treturn -1, err\n\t}\n\n\tuid, err := getVacantUid()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tout, err := exec.Command(\n\t\t\"/usr/sbin/useradd\",\n\t\t\"--shell=/bin/false\",\n\t\tfmt.Sprintf(\"--uid=%d\", uid),\n\t\t\"--gid=nogroup\",\n\t\tname,\n\t).CombinedOutput()\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"%s: %s\", err, out)\n\t}\n\n\treturn uid, nil\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user schema.User\n\n\t// we decode our body request params in JSON\n\t_ = json.NewDecoder(r.Body).Decode(&user)\n\n\tresult, err := users.InsertOne(context.TODO(), user)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// we decode the recieved params in JSON\n\tjson.NewEncoder(w).Encode(result)\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tif err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusOK))\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n user := new(User)\n user.Token = validateToken(r.FormValue(\"token\"))\n user.PasswordHash = validateHash(r.FormValue(\"passHash\"))\n user.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n user.PublicHash = computePublicHash(user.PublicKey)\n user.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n log.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n if !SaveUser(user) {\n http.Error(w, \"That username is taken\", http.StatusBadRequest)\n }\n}", "func (c *Client) CreateUser(data, fingerprint, ipAddress string, idempotencyKey ...string) (*User, error) {\n\tlog.info(\"========== CREATE USER ==========\")\n\tvar user User\n\tuser.request = Request{\n\t\tclientID: c.ClientID,\n\t\tclientSecret: c.ClientSecret,\n\t\tfingerprint: fingerprint,\n\t\tipAddress: ipAddress,\n\t}\n\n\turl := buildURL(path[\"users\"])\n\tres, err := user.do(\"POST\", url, data, idempotencyKey)\n\tmapstructure.Decode(res, &user)\n\tuser.Response = res\n\n\treturn &user, err\n}", "func CreateNewUser(db *sql.DB, userName string, password string) string {\n\t_, err := db.Query(\"INSERT INTO user (user_name, password) VALUES (?, ?)\", userName, password)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn \"Success\"\n}", "func (s *Store) CreateUser(name, password string, admin bool) (*UserInfo, error) {\n\t// Hash the password before serializing it.\n\thash, err := HashPassword(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Serialize command and send it to the leader.\n\tif err := s.exec(internal.Command_CreateUserCommand, internal.E_CreateUserCommand_Command,\n\t\t&internal.CreateUserCommand{\n\t\t\tName: proto.String(name),\n\t\t\tHash: proto.String(string(hash)),\n\t\t\tAdmin: proto.Bool(admin),\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.User(name)\n}", "func (t *HackidfChaincode) CreateUser(stub shim.ChaincodeStubInterface, args []string)pb.Response{\n\tvar UserID = args[0]\n\tvar Username = args[1]\n\tvar Email = args[2]\n\t// checking for an error or if the user already exists\n\tUserAsBytes, err := stub.GetState(Username)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get Username:\" + err.Error())\n\t}else if UserAsBytes != nil{\n\t\treturn shim.Error(\"User with current username already exists\")\n\t}\n\tvar User = &User{Username:Username, Email:Email}\n\tUserJsonAsBytes, err :=json.Marshal(User)\n\tif err != nil {\n\t\tshim.Error(\"Error encountered while Marshalling\")\n\t}\n\terr = stub.PutState(UserID, UserJsonAsBytes)\n\tif err != nil {\n\t\tshim.Error(\"Error encountered while Creating User\")\n\t}\n\tfmt.Println(\"Ledger Updated Successfully\")\n\treturn shim.Success(nil)\n}", "func (uic *UserInviteCode) Create(r *http.Request, currentUser UserPostgres) (*UserInviteCode, error) {\n\t// Create user\n\tuic.CreatedBy = currentUser.Id\n\tuic.Created = time.Now()\n\tuic.IsUsed = false\n\n\t_, err := db.DB.Model(uic).Returning(\"*\").Insert()\n\treturn uic, err\n}" ]
[ "0.6267547", "0.62496465", "0.62179583", "0.61971134", "0.61795163", "0.61232007", "0.6099473", "0.59052324", "0.5877333", "0.58692676", "0.58533084", "0.581048", "0.5762119", "0.57558155", "0.5728573", "0.5718425", "0.569958", "0.56609297", "0.56410146", "0.56376344", "0.5608655", "0.55688965", "0.555233", "0.55448145", "0.5536554", "0.5535635", "0.55310124", "0.5530538", "0.54956734", "0.5481923", "0.54770136", "0.5459472", "0.5449309", "0.54403585", "0.54348594", "0.5429095", "0.54233503", "0.5411859", "0.54104173", "0.54103166", "0.53997123", "0.5391607", "0.5379394", "0.5378086", "0.53758645", "0.5358037", "0.53578556", "0.53538924", "0.5352562", "0.5350853", "0.53468525", "0.5345398", "0.5344311", "0.5337143", "0.53357536", "0.53312796", "0.53294075", "0.53286064", "0.53258044", "0.53253037", "0.5317849", "0.5316997", "0.53155226", "0.53080636", "0.53052855", "0.5303368", "0.5298327", "0.5293682", "0.52935934", "0.5281868", "0.5278179", "0.5259112", "0.52557176", "0.52484155", "0.5244584", "0.5244122", "0.524089", "0.52393466", "0.52392954", "0.5233521", "0.5226391", "0.5219984", "0.5218208", "0.5217735", "0.520963", "0.5208848", "0.5206527", "0.52051896", "0.5204747", "0.51827675", "0.5182601", "0.5181262", "0.51787883", "0.5175805", "0.51698655", "0.5168889", "0.5163147", "0.5159442", "0.51571757", "0.515657" ]
0.6184066
4
Delete a specific VPN User in the current environment by their ID
func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) Delete(remoteAccessVpnUser RemoteAccessVpnUser) (bool, error) { send, merr := json.Marshal(remoteAccessVpnUser) if merr != nil { return false, merr } _, err := remoteAccessVpnUserApi.entityService.Delete(remoteAccessVpnUser.Id, send, map[string]string{}) return err == nil, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteUser(person *Person, id string) (err error) {\n\tConfig.DB.Where(\"id = ?\", id).Delete(person)\n\treturn nil\n}", "func DeleteUser(c *gin.Context) {}", "func DeleteUser(id int) {\n\tvar i int\n\ti = GetIndexOfUser(id)\n\tDeleteUserFromDatabase(i)\n}", "func deleteUser(w http.ResponseWriter, r *http.Request) {\r\n\tparams := mux.Vars(r)\r\n\tstmt, err := db.Prepare(\"DELETE FROM users WHERE id = ?\")\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\t_, err = stmt.Exec(params[\"id\"])\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\tfmt.Fprintf(w, \"User with id = %s was deleted\", params[\"id\"])\r\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Delete user endpoint hit\")\n\t\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\n\tvar user models.User\n\n\tmessage := user.Destroy(id)\n\n json.NewEncoder(w).Encode(message)\n}", "func DeleteUser(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tid := vars[\"id\"]\n\n\tif err := db.Remove(id); err != nil {\n\t\thandleError(err, \"Failed to remove User: %v\", w)\n\t\treturn\n\t}\n\n\tw.Write([]byte(\"OK\"))\n}", "func delete_specific_user(c client, id uint16, delete_thumb bool) uint8 {\n\tlogger_id(PRINT_NORMAL, c.deviceId, \"deleting user id = \", id)\n\tresponse_chan := make(chan Ipc_packet)\n\tsite_mux_reg_cmd(c.deviceId, response_chan)\n\n\tvar ipc Ipc_packet\n\n\tif delete_thumb {\n\t\tipc = create_ipc_cmd_dlt_usr_helper(c.deviceId, id, true)\n\t} else {\n\t\tipc = create_ipc_cmd_dlt_usr_helper(c.deviceId, id, false)\n\t}\n\tipc.ClientId = c.ClientId\n\tvar resp Ipc_packet\n\n\tgo be_handle_command(ipc)\n\n\tselect {\n\tcase resp = <-response_chan:\n\t\tbreak\n\tcase <-time.After(time.Second * COMMAND_TIMEOUT_TIME):\n\t\tsite_mux_unreg_cmd(c.deviceId)\n\t\tlogger(PRINT_FATAL, \"Timed out delting a user\")\n\t}\n\n\tsite_mux_unreg_cmd(c.deviceId)\n\n\tcmd_rsp := packet_cmd_response_unpack(resp.P.Data)\n\treturn cmd_rsp.Cmd_status\n}", "func (serv *AppServer) DeleteUser(delID int) {\n\tserv.ServerRequest([]string{\"DeleteUser\", strconv.Itoa(delID)})\n}", "func DeleteUser(props neoism.Props) error {\n\n\t// return error if user is not found in the database\n\tif u, _ := FindUser(props); u == nil {\n\t\treturn errors.New(\"user not found\")\n\t}\n\n\tdb := vantaadb.Connect()\n\tcq := neoism.CypherQuery{\n\t\tStatement: `MATCH (u:User)\n OPTIONAL MATCH (s:Session)-[r]->(u)\n WHERE ` + vantaadb.PropString(\"u\", props) + `DELETE u, s, r`,\n\t\tParameters: props,\n\t}\n\tif err := db.Cypher(&cq); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteUserByID(svc *dynamodb.DynamoDB, id string) error {\n\n\tinput := &dynamodb.DeleteItemInput{\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"id\": {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(UserTableName),\n\t}\n\n\t_, err := svc.DeleteItem(input)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func DeleteUser(userid int64) error {\n _, err := model.Database.Exec(\"DELETE FROM users WHERE userid = ? AND isadmin = ?\", userid, false)\n if err != nil {\n return err\n }\n return nil\n}", "func DeleteLpBrookUser(id int) (err error) {\n\to := orm.NewOrm()\n\tv := LpBrookUser{Id: id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Delete(&LpBrookUser{Id: id}); err == nil {\n\t\t\tfmt.Println(\"Number of records deleted in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\n\tuserID, err := strconv.ParseInt(params[\"id\"], 10, 64)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuserIDToken, err := authentication.ExtractUserId(r)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnauthorized, err)\n\t\treturn\n\t}\n\n\tif userIDToken != userID {\n\t\tresponses.Error(w, http.StatusForbidden, errors.New(\"não é possível manipular usuário de terceiros\"))\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tif err := repository.DeleteUser(userID); err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusNoContent, nil)\n}", "func DeleteUser(id bson.ObjectId) User {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"reimburse-me\").C(\"user\")\n\tdb.Remove(bson.M{\"_id\": id})\n\tvar result User\n\tdb.Find(id).One(result)\n\treturn result\n}", "func deleteUser(res http.ResponseWriter, req *http.Request, p httprouter.Params) {\n\t_, err := db.Exec(`\n\t\tDELETE FROM accounts\n\t\tWHERE username = $1;`, p.ByName(\"username\"),\n\t)\n\tif err != nil {\n\t\tlog.Println(\"deleteUser:\", err)\n\t}\n\n\twriteJSON(res, 200, jsMap{\"status\": \"OK\"})\n}", "func (client IdentityClient) deleteUser(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/users/{userId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteUserResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func deleteUser(c *gin.Context) {\n\tvar user user\n\tuserID := c.Param(\"id\")\n\n\tdb.First(&user, userID)\n\n\tif user.Id == 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": http.StatusNotFound, \"message\": \"No user found!\"})\n\t\treturn\n\t}\n\n\tdb.Delete(&user)\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"message\": \"User deleted successfully!\"})\n}", "func DeleteUser(pid int) {\n\tstmt, err := database.Prepare(`DELETE FROM USER_INFO WHERE pid = ?;`)\n\tdefer stmt.Close()\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n\n\t_, err = stmt.Exec(pid)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t}\n}", "func db_delete_user(username string) {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n\n err := os.Remove(file_path)\n \n if err != nil {\n fmt.Println(err.Error())\n return\n }\n fmt.Println(\"User Removed: \", username)\n}", "func DeleteUser(user *models.User, id string) (err error) {\n\tconfig.DB.Where(\"id = ?\", id).Delete(user)\n\treturn nil\n}", "func (app *App) deleteUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tuser := &users.User{ID: int64(id)}\n\terr = user.DeleteUser(app.Db)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusNotFound, err.Error())\n\t\treturn\n\t}\n\n\trespondWithJSON(w, http.StatusOK, map[string]string{\"message\": \"User deleted successfully\"})\n}", "func DeleteUser(db *pg.DB, pk int64) error {\n\n\tuser := models.User{ID: pk}\n\n\tfmt.Println(\"Deleting User...\")\n\n\terr := db.Delete(&user)\n\n\treturn err\n}", "func (p *UserPool) DeleteUser(id string) {\n\tdelete(p.users, id)\n\treturn\n}", "func DeleteUser(c *gin.Context) {\n\tvar user models.User\n\tid := c.Params.ByName(\"id\")\n\terr := models.DeleteUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"id\" + id: \"is deleted\"})\n\t}\n}", "func (pc UserController) Delete(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar u repository.UserRepository\n\tidInt, _ := strconv.Atoi(id)\n\tif err := u.DeleteByID(idInt); err != nil {\n\t\tc.AbortWithStatus(403)\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"success\": \"ID\" + id + \"のユーザーを削除しました\"})\n\treturn\n}", "func Delete(c *gin.Context) {\n\tuserID, err := getUserID(c.Param(\"user_id\"))\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tif err := services.UserServ.DeleteUser(userID); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func DeleteUser(c *gin.Context) {\n\tvar user Models.User\n\tid := c.Params.ByName(\"id\")\n\terr := Models.DeleteUser(&user, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else { \n\t\tc.JSON(http.StatusOK, gin.H{\"id\":\"is deleted\"})\n\t}\n}", "func DeleteUser(c *gin.Context) {\n\tid := c.Param(\"id\")\n\tlog.Printf(\"DeleteUser in db %v\", id)\n\tvar user models.User\n\tdb := db.GetDB()\n\n\tif err := db.Where(\"id = ?\", id).First(&user).Error; err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\tlog.Println(\"Failed to DeleteUser in db\")\n\t\treturn\n\t}\n\n\tdb.Delete(&user)\n}", "func (s *Server) deleteUser(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// get user-id and put into temp\n\tuserId := request.PathParameter(\"user-id\")\n\tif err := s.dataStore.DeleteUser(userId); err != nil {\n\t\tinternalServerError(response, err)\n\t\treturn\n\t}\n\tok(response, Success{RowAffected: 1})\n}", "func Delete(ctx context.Context, dbConn *db.DB, userID string) error {\n\tif !bson.IsObjectIdHex(userID) {\n\t\treturn errors.Wrapf(web.ErrInvalidID, \"bson.IsObjectIdHex: %s\", userID)\n\t}\n\n\tq := bson.M{\"user_id\": userID}\n\n\tf := func(collection *mgo.Collection) error {\n\t\treturn collection.Remove(q)\n\t}\n\tif err := dbConn.MGOExecute(ctx, usersCollection, f); err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn web.ErrNotFound\n\t\t}\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"db.users.remove(%s)\", db.Query(q)))\n\t}\n\n\treturn nil\n}", "func (s *Server) deleteUser(request *restful.Request, response *restful.Response) {\n\t// Authorize\n\tif !s.auth(request, response) {\n\t\treturn\n\t}\n\t// get user-id and put into temp\n\tuserId := request.PathParameter(\"user-id\")\n\tif err := s.DataStore.DeleteUser(userId); err != nil {\n\t\tinternalServerError(response, err)\n\t\treturn\n\t}\n\tok(response, Success{RowAffected: 1})\n}", "func deleteUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tresult := delete.DeleteUserData(params[\"id\"])\n\tjson.NewEncoder(w).Encode(map[string]string{\n\t\t\"result\": result,\n\t})\n}", "func (db *Database) DeleteUserID(id int) error {\n\t_, err := db.db.Exec(`\n\t\tDELETE FROM melodious.accounts WHERE id=$1;\n\t`, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func UserDelete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\n}", "func Delete(c *gin.Context) {\n\tuserId, idErr := getUserID(c.Param(\"user_id\"))\n\tif idErr != nil {\n\t\tc.JSON(idErr.Status, idErr)\n\t\treturn\n\t}\n\n\tif err := services.UsersService.DeleteUser(userId); err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"deleted\"})\n}", "func DeleteUser(c *gin.Context) {\n\tnID := c.Param(\"user_id\")\n\tdb := dbConn()\n\tstatement, _ := db.Prepare(\"CALL delete_user(?)\")\n\tstatement.Exec(nID)\n\tdefer db.Close()\n}", "func (us *UserStorage) DeleteUser(id string) error {\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn model.ErrorWrongDataFormat\n\t}\n\ts := us.db.Session(UsersCollection)\n\tdefer s.Close()\n\n\terr := s.C.RemoveId(bson.ObjectIdHex(id))\n\treturn err\n}", "func DeleteUser(db *gorm.DB, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tid := vars[\"id\"]\n\tuser := getUserByID(db, id, w, r)\n\tif user == nil {\n\t\treturn\n\t}\n\tif err := db.Delete(&user).Error; err != nil {\n\t\tRespondError(w, http.StatusInternalServerError, \"\")\n\t\treturn\n\t}\n\tRespondJSON(w, http.StatusNoContent, nil)\n}", "func DeleteUser(c echo.Context) error {\n\tid := c.FormValue(\"id\")\n\n\tconvID, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\tresult, err := models.DeleteUser(convID)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn c.JSON(http.StatusOK, result)\n}", "func (userRepository UserRepository) Delete(userId uint64) error {\n\tstatement, err := userRepository.db.Prepare(\n\t\t\"delete from users where id = ?\",\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\n\tif _, err = statement.Exec(userId); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteUser(id string) error {\n\t_, err := db.Exec(\"DELETE FROM web_users WHERE ID = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deleteUser(username string) int {\n\tif isServerAlive() {\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\t\treply, err := rpcCaller.DeleteUser(ctx, &pb.Credentials{Uname: username, Broadcast: true})\n\t\tif err == nil {\n\t\t\tfmt.Println(\"Delete User RPC successful\", reply)\n\t\t\treturn 0\n\t\t} else {\n\t\t\tfmt.Println(\"Delete User RPC failed\", reply, err)\n\t\t\treturn -1\n\t\t}\n\t} else {\n\t\tdebugPrint(\"Debug: Primary server down, cant process requests\")\n\t\treturn -1\n\t}\n}", "func DeleteUserByID(id uint) error {\n\t_, err := GetUserByID(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := DeleteAllRefreshTokensForUser(id); err != nil {\n\t\treturn err\n\t}\n\n\tresult := database.GetPostgresDB().Unscoped().Delete(&models.User{}, id)\n\tif result.Error != nil {\n\t\treturn result.Error\n\t}\n\treturn nil\n}", "func (server Server) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r) //mux params\n\tid, err := strconv.Atoi(vars[\"id\"]) // convert the id in string to int\n\tvar res models.APIResponse // make a response\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to convert the string into int. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to convert the string into int\", nil)\n\t} else {\n\t\tdeletedRows := deleteUser(int64(id), server.db) // call the deleteUser, convert the int to int64\n\t\tres = models.BuildAPIResponseSuccess(\"User updated successfully.\", deletedRows)\n\t}\n\t// send the response\n\tjson.NewEncoder(w).Encode(res)\n}", "func (b *BizDAO) DeleteUserByID(id string) error {\n\tquery := bson.M{\"_id\": bson.ObjectIdHex(id)}\n\terr := db.C(UCOLLECTION).Remove(query)\n\treturn err\n}", "func DeleteUser(id int) error {\n\tq := \"DELETE FROM users WHERE id=$1\"\n\t_, err := dbConn.Exec(q, id)\n\treturn err\n}", "func (u *usecase) Delete(ctx context.Context, id string) error {\n\tif err := u.repository.Delete(ctx, id); err != nil {\n\t\treturn errors.Wrap(err, \"error deleting user\")\n\t}\n\treturn nil\n}", "func DeleteUser(c *gin.Context) {\n\tuuid := c.Params.ByName(\"uuid\")\n\tvar user models.User\n\tdb := db.GetDB()\n\tif uuid != \"\" {\n\n\t\tjwtClaims := jwt.ExtractClaims(c)\n\t\tauthUserAccessLevel := jwtClaims[\"access_level\"].(float64)\n\t\tauthUserUUID := jwtClaims[\"uuid\"].(string)\n\t\tif authUserAccessLevel != 1 {\n\t\t\tif authUserUUID != uuid {\n\t\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\n\t\t\t\t\t\"error\": \"Sorry but you can't delete user, ONLY admins can\",\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// DELETE FROM users WHERE uuid= user.uuid\n\t\t// exemple : UPDATE users SET deleted_at=date.now WHERE uuid = user.uuid;\n\t\tif err := db.Where(\"uuid = ?\", uuid).Delete(&user).Error; err != nil {\n\t\t\t// error handling...\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Display JSON result\n\t\t// c.JSON(200, gin.H{\"success\": \"User #\" + uuid + \" deleted\"})\n\t\tc.JSON(200, gin.H{\"success\": \"User successfully deleted\"})\n\t} else {\n\t\t// Display JSON error\n\t\tc.JSON(404, gin.H{\"error\": \"User not found\"})\n\t}\n\n}", "func (uc UserController) DeleteUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tid := p.ByName(\"id\")\n\n\tif _, ok := users[id]; !ok {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t// Delete user\n\tdelete(users, id)\n\n\tw.WriteHeader(http.StatusOK) // 200\n\tfmt.Fprint(w, \"Deleted user\", id, \"\\n\")\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\r\n\tdefer r.Body.Close()\r\n\tuser := r.Context().Value(\"user\").(string)\r\n\r\n\tif err := dao.DBConn.RemoveUserByEmail(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"User doesn't exist or has already been deleted\")\r\n\t\treturn\r\n\t}\r\n\r\n\tif err := dao.DBConn.RemoveUserExpenses(user); err != nil {\r\n\t\tlog.Println(err)\r\n\t\tu.RespondWithError(w, http.StatusBadRequest, \"User doesn't exist or has already been deleted\")\r\n\t\treturn\r\n\t}\r\n\r\n\tu.RespondWithJSON(w, http.StatusOK, \"User deleted\")\r\n}", "func (ps *UserService) Delete(loggedInUser string, id string) error {\n\terr := ps.repository.Delete(id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn err\n}", "func (ur *UserRepository) Delete(ctx context.Context, id uint) error {\n\tq := `\n\tDELETE FROM users WHERE id=$1;\n\t`\n\n\tstmt, err := ur.Data.DB.PrepareContext(ctx, q)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.ExecContext(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ur *UserRepository) Delete(ctx context.Context, id uint) error {\n\tq := `\n\tDELETE FROM users WHERE id=$1;\n\t`\n\n\tstmt, err := ur.Data.DB.PrepareContext(ctx, q)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.ExecContext(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteUser(dbmap *gorp.DbMap, id string) error {\n\tvar u User\n\terr := dbmap.SelectOne(&u, \"SELECT * FROM user WHERE object_id = ?\", id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx, err := dbmap.Begin()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t_, err = tx.Exec(\"DELETE FROM user_session WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"DELETE FROM user_role WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"DELETE FROM domain_user WHERE user_id = ?;\", u.PK)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Delete(&u)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (uv *userValidator) Delete(id uint) error {\n\tvar user User\n\tuser.ID = id\n\terr := runUserValFuncs(&user, uv.idGreaterThan(0))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (uv *userValidator) Delete(id uint) error {\n\tvar user User\n\tuser.ID = id\n\terr := runUserValFuncs(&user, uv.idGreaterThan(0))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func DeleteUser(db sqlx.Execer, id int64) error {\n\tres, err := db.Exec(\"delete from \\\"user\\\" where id = $1\", id)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete error\")\n\t}\n\tra, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get rows affected error\")\n\t}\n\tif ra == 0 {\n\t\treturn ErrDoesNotExist\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"id\": id,\n\t}).Info(\"user deleted\")\n\treturn nil\n}", "func (pdb *UserPostgresDb) DeleteUser(id int) (int64, error) {\n\tconn, err := pdb.Pool.Acquire(context.Background())\n\tif err != nil {\n\t\tpdb.log.Error(\"Unable to acquire DB connection. \\n\", err)\n\t\treturn -1, err\n\t}\n\tdefer conn.Release()\n\n\tct, err := conn.Exec(context.Background(),\n\t\t\"DELETE FROM users WHERE id = $1\",\n\t\tid)\n\n\tif err != nil {\n\t\tpdb.log.Errorf(\"Failed to delete user with ID:%d \\n %v\", id, err)\n\t\treturn -1, err\n\t}\n\tpdb.log.Printf(\"User with ID:%d deleted \\n\", id)\n\n\treturn ct.RowsAffected(), nil\n}", "func (uv *userValidator) Delete(id uint) error{\n\tvar user User\n\tuser.ID = id\n\terr := runUserValidatorFunction(&user, uv.idGreaterThan(0))\n\tif err != nil{\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (uh *UserHandler) Delete(c echo.Context) error {\n\tid_, err := strconv.Atoi(c.Param(\"id\"))\n\tid := uint(id_)\n\n\terr = uh.UserUseCase.Delete(id)\n\n\tif err != nil {\n\t\treturn c.JSON(GetStatusCode(err), ResponseError{Message: err.Error()})\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}", "func DeleteUser(c *gin.Context) {\n\t// Get model if exist\n\tvar user models.User\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&user).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\tmodels.DB.Delete(&user)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func (config *CrocConfig) DeleteUser(userID int) error {\n\tendpoint := fmt.Sprintf(\"users/%d\", userID)\n\n\t// get json bytes from the panel.\n\t_, err := config.queryPanelAPI(endpoint, \"delete\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteUser(id int) (err error) {\n\to := orm.NewOrm()\n\tv := User{Id: id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Delete(&User{Id: id}); err == nil {\n\t\t\tfmt.Println(\"Number of records deleted in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func DeleteUser(\n\tctx context.Context,\n\ttx *sql.Tx,\n\trequest *models.DeleteUserRequest) error {\n\tdeleteQuery := deleteUserQuery\n\tselectQuery := \"select count(uuid) from user where uuid = ?\"\n\tvar err error\n\tvar count int\n\tuuid := request.ID\n\tauth := common.GetAuthCTX(ctx)\n\tif auth.IsAdmin() {\n\t\trow := tx.QueryRowContext(ctx, selectQuery, uuid)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"not found\")\n\t\t}\n\t\trow.Scan(&count)\n\t\tif count == 0 {\n\t\t\treturn errors.New(\"Not found\")\n\t\t}\n\t\t_, err = tx.ExecContext(ctx, deleteQuery, uuid)\n\t} else {\n\t\tdeleteQuery += \" and owner = ?\"\n\t\tselectQuery += \" and owner = ?\"\n\t\trow := tx.QueryRowContext(ctx, selectQuery, uuid, auth.ProjectID())\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"not found\")\n\t\t}\n\t\trow.Scan(&count)\n\t\tif count == 0 {\n\t\t\treturn errors.New(\"Not found\")\n\t\t}\n\t\t_, err = tx.ExecContext(ctx, deleteQuery, uuid, auth.ProjectID())\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"delete failed\")\n\t}\n\n\terr = common.DeleteMetaData(tx, uuid)\n\tlog.WithFields(log.Fields{\n\t\t\"uuid\": uuid,\n\t}).Debug(\"deleted\")\n\treturn err\n}", "func (g *Game) deleteUser(user *User) {\n\tdelete(g.Players, (*user).Name)\n\tlog.Println(\"Deleted user \" + (*user).Name)\n}", "func DeleteUser(id int) error {\n\tuser := User{ID: id}\n\t_, err := db.Model(&user).WherePK().Delete()\n\treturn err\n}", "func DeleteUser(user *entity.User, id string, client *statsd.Client) (err error) {\n\tt := client.NewTiming()\n\tif config.DB.Where(\"id = ?\", id).First(&user); user.ID == \"\" {\n\t\treturn errors.New(\"the user doesn't exist!!!\")\n\t}\n\tconfig.DB.Where(\"id = ?\", id).Delete(&user)\n\tt.Send(\"delete_user.query_time\")\n\treturn nil\n}", "func (config *AppConfig) DeleteUser(userID int) (err error) {\n\t// get json bytes from the panel.\n\t_, err = config.queryApplicationAPI(fmt.Sprintf(\"users/%d\", userID), \"delete\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (m *Manager) Delete(ctx context.Context, tx *sql.Tx, user v0.User) error {\n\tresult, err := tx.ExecContext(ctx, `\n\t\t\t\tUPDATE users \n\t\t\t\tSET deleted_at = ?, \n\t\t\t\tdeleted = TRUE \n\t\t\t\tWHERE primary_public_key = ?;`,\n\t\ttime.Now(),\n\t\tuser.PrimaryPublicKey,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\taffected, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif affected == 0 {\n\t\treturn ErrUserDoesNotExists\n\t}\n\treturn nil\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\n\thttpext.SuccessAPI(w, \"ok\")\n}", "func (a *Server) DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"delete a user\")\n}", "func (userservice Userservice) Delete(id string) error {\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\toid, erroid := primitive.ObjectIDFromHex(id)\n\tif erroid != nil {\n\t\treturn erroid\n\t}\n\n\tdb := db.ConfigDB()\n\terr := db.Collection(\"users\").FindOneAndDelete(ctx, bson.M{\"_id\": oid}).Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func (pk *JSONPasswordKeeper) Del(username string) error {\n\tpk.mutex.Lock()\n\tdefer pk.mutex.Unlock()\n\tif _, exists := pk.userInfo[username]; exists {\n\t\tdelete(pk.userInfo, username)\n\t\treturn pk.flushToDisk()\n\t}\n\treturn ErrNoSuchUser\n}", "func (srv *Service) DeleteUser(id string) (*string, error) {\n\t//check if the email already 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 inserting a user inside the database\n\t_, err = srv.mongoRepository.DeleteUserByID(id)\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\tresponseDeployments, err := srv.mongoRepository.GetDeploymentsFromUser(id)\n\tif err != nil {\n\t\t//return the error sent by the repository\n\t\treturn nil, err\n\t}\n\n\t//delete user deployments\n\tfor _, element := range responseDeployments {\n\t\t_, err := srv.kubernetesRepository.DeleteNamespace(\"namespace-\" + element.UUID)\n\t\tif err != nil {\n\t\t\t//return the error sent by the repository\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = srv.mongoRepository.DeleteDeploymentByUUID(element.UUID)\n\t\tif err != nil {\n\t\t\t//return the error sent by the repository\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmessage := \"User deleted sucessfully\"\n\n\treturn &message, nil\n}", "func DeleteUser(c *gin.Context, client *statsd.Client) {\n\tlog.Info(\"deleting user\")\n\tvar user entity.User\n\tid := c.Params.ByName(\"id\")\n\terr := model.DeleteUser(&user, id, client)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"id\" + id: \"is deleted\"})\n\t}\n\tlog.Info(\"user deleted\")\n}", "func (uv *userValidator) Delete(id uint) error {\r\n\tvar user User\r\n\tuser.ID = id\r\n\terr := runUserValFns(&user, uv.idGreaterThan(0))\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\treturn uv.UserDB.Delete(id)\r\n}", "func UserDelete(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\tuserUUID := auth.GetUUIDByName(urlUser, refStr)\n\n\terr := auth.RemoveUser(userUUID, refStr)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write empty response if anything ok\n\trespondOK(w, output)\n\n}", "func (uv *userValidator) Delete(id uint) error {\n\tvar user User\n\tuser.ID = id\n\terr := runUserValFns(&user, uv.idGreaterThan(0))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (uv *userValidator) Delete(id uint) error {\n\tvar user User\n\tuser.ID = id\n\terr := runUserValFns(&user, uv.idGreaterThan(0))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (uv *userValidator) Delete(id uint) error {\n\tvar user User\n\tuser.ID = id\n\terr := runUserValFns(&user, uv.idGreaterThan(0))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func Delete(w http.ResponseWriter, r *http.Request) {\n\tuserID := context.Get(r, \"userID\").(int)\n\n\t// Excluindo usuário logado\n\terr := ServiceUser.Delete(userID)\n\n\tif err != nil {\n\t\tw.Write(util.MessageInfo(\"message\", err.Error()))\n\t\treturn\n\t}\n\n\tw.Write(util.MessageInfo(\"message\", \"Excluído com sucesso\"))\n}", "func (w *ServerInterfaceWrapper) DeleteUser(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"id\" -------------\n\tvar id int\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"id\", ctx.Param(\"id\"), &id)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter id: %s\", err))\n\t}\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.DeleteUser(ctx, id)\n\treturn err\n}", "func DeleteUser(c *gin.Context) {\n\tuserID := c.Param(\"userID\")\n\tuser := &userModel.User{ID: userID}\n\n\terr := dbConnect.Delete(user)\n\tif err != nil {\n\t\tlog.Printf(\"Error while deleting a single user, Reason: %v\\n\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"message\": \"Something went wrong\",\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": http.StatusOK,\n\t\t\"message\": \"User deleted successfully\",\n\t})\n\treturn\n}", "func deleteUserPolicy(neptuneName string) {\n\n\tsvc := iam.New(session.New(&aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"REGION\")),\n\t}))\n\n\tpolicyarn := getPolicyARN(neptuneName)\n\tdeparams := &iam.DetachUserPolicyInput{\n\t\tPolicyArn: aws.String(policyarn), // Required\n\t\tUserName: aws.String(neptuneName), // Required\n\t}\n\n\t_, err := svc.DetachUserPolicy(deparams)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tsvc = iam.New(session.New(&aws.Config{\n\t\tRegion: aws.String(os.Getenv(\"REGION\")),\n\t}))\n\n\tparams := &iam.DeletePolicyInput{\n\t\tPolicyArn: aws.String(policyarn), // Required\n\t}\n\t_, err = svc.DeletePolicy(params)\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n}", "func (db *DB) DeleteUser(id string) error {\n\tcursor := db.collections.users.FindOneAndDelete(\n\t\tcontext.Background(),\n\t\tbson.D{primitive.E{\n\t\t\tKey: \"_id\",\n\t\t\tValue: id,\n\t\t}},\n\t)\n\n\tif cursor.Err() != nil {\n\t\treturn cursor.Err()\n\t}\n\n\treturn nil\n}", "func (tc TeresaClient) DeleteUser(ID int64) error {\n\tparams := users.NewDeleteUserParams()\n\tparams.UserID = ID\n\t_, err := tc.teresa.Users.DeleteUser(params, tc.apiKeyAuthFunc)\n\treturn err\n}", "func (userRepo *PostUserRepository) DeleteUser(id int) error {\n\n\t_, err := userRepo.conn.Exec(\"DELETE FROM users WHERE id=$1\", id)\n\tif err != nil {\n\t\treturn errors.New(\"Delete has failed\")\n\t}\n\n\treturn nil\n}", "func (h *UserHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tidStr := vars[\"id\"]\n\tid, err := strconv.ParseUint(idStr, 10, 64)\n\tif err != nil {\n\t\tlog.Println(errors.Wrapf(err, \"error parse uint:%v\", idStr))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Printf(\"/users/%d DELETE handled\", id)\n\n\tif err := h.model.Delete(id); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}", "func (c *Client) Delete(id string) error {\n\terr := c.login()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar errbuf bytes.Buffer\n\tcmd := exec.Command(\"lpass\", \"rm\", id, \"--sync=now\")\n\tcmd.Stderr = &errbuf\n\terr = cmd.Run()\n\tif err != nil {\n\t\t// Make sure the secret is not removed manually.\n\t\tif strings.Contains(errbuf.String(), \"Could not find specified account\") {\n\t\t\treturn nil\n\t\t}\n\t\tvar err = errors.New(errbuf.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *UserAPI) DeleteUserByID(ctx *gin.Context) {\n\twithID(ctx, \"id\", func(id uint) {\n\t\tif user := a.DB.GetUserByID(id); user != nil {\n\t\t\ta.NotifyDeleted(id)\n\t\t\ta.DB.DeleteUserByID(id)\n\t\t} else {\n\t\t\tctx.AbortWithError(404, errors.New(\"user does not exist\"))\n\t\t}\n\t})\n}", "func DeleteAccount(id string, vrs int) error {\n\tuid, isUuid := checkUuid(id)\n\tif !isUuid {\n\t\tinvalidIdErr := errors.New(\"given id must be a valid uuid type\")\n\t\tlog.Print(invalidIdErr)\n\t\treturn invalidIdErr\n\t}\n\n\tgate := data.NewGateway()\n\terr := gate.Delete(uid, strconv.Itoa(vrs))\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k Keeper) DeleteUser(ctx sdk.Context, key string) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete([]byte(types.UserPrefix + key))\n}", "func (inst *UserN) Delete(ctx context.Context) error {\n\tif inst.userModel == nil {\n\t\treturn query.ErrModelNotSet\n\t}\n\n\t_, err := inst.userModel.DeleteById(ctx, inst.Id.Int64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *database) deleteUser(publicKey string) (err error) {\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tquery := \"DELETE FROM letters WHERE sender == ?;\"\n\tlogger.Log.Debug(query)\n\tstmt, err := tx.Prepare(query)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(publicKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deleteUser\")\n\t}\n\treturn\n}", "func DeleteUser(jxClient versioned.Interface, ns string, userName string) error {\n\tid := naming.ToValidName(userName)\n\tuserInterface := jxClient.JenkinsV1().Users(ns)\n\t_, err := userInterface.Get(id, metav1.GetOptions{})\n\tif err == nil {\n\t\terr = userInterface.Delete(id, nil)\n\t}\n\treturn err\n}", "func (uv *userValidator) Delete(id uint) error {\n\tif id == 0 {\n\t\treturn ErrIDInvalid\n\t}\n\treturn uv.UserDB.Delete(id)\n}", "func (client *Client) DeleteUser(userID string, userDomainName string) (string, error) {\n\tuserDomainData := UserDomainData{\n\t\tID: userID,\n\t\tDomainName: userDomainName,\n\t}\n\tuserDomainDataJSON, _ := json.Marshal(userDomainData)\n\n\tresRaw, err := client.RemoveClient(userDomainDataJSON)\n\treturn string(resRaw), err\n}", "func (u *UserTest) DeleteByID(id int) error {\n\treturn nil\n}", "func DeleteUser(w http.ResponseWriter, r *http.Request) {\n\tcookie, _ := cookies.Read(r)\n\tuserID, _ := strconv.ParseUint(cookie[\"id\"], 10, 64)\n\n\turl := fmt.Sprintf(\"%s/users/%d\", config.APIURL, userID)\n\n\tresponse, err := requests.RequestsWithAuthentication(r, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, response.StatusCode, nil)\n}", "func DeleteUser(c echo.Context) error {\n\tid, _ := strconv.Atoi(c.Param(\"id\"))\n\tdelete(users, id)\n\treturn c.NoContent(http.StatusNoContent)\n}" ]
[ "0.67293096", "0.6685717", "0.64978117", "0.6477398", "0.6426493", "0.6403434", "0.6390443", "0.63575166", "0.6320435", "0.63022155", "0.629935", "0.6193499", "0.61792743", "0.61733806", "0.6168578", "0.61629343", "0.61620194", "0.6154224", "0.6144365", "0.61240584", "0.6123414", "0.611248", "0.61116165", "0.6110961", "0.6108123", "0.6102574", "0.610189", "0.6100056", "0.6087539", "0.60850424", "0.6064073", "0.60337", "0.6028244", "0.60259056", "0.6024688", "0.6012025", "0.6004314", "0.59991044", "0.5990196", "0.5978654", "0.59780836", "0.5976744", "0.59705216", "0.5960302", "0.5959334", "0.59528583", "0.59448564", "0.593655", "0.5930772", "0.59039253", "0.59023404", "0.5901638", "0.5901638", "0.5895031", "0.588511", "0.588511", "0.58760005", "0.5872783", "0.5869298", "0.5868329", "0.58614075", "0.5847319", "0.583844", "0.58357966", "0.58297426", "0.5829525", "0.58292216", "0.5824126", "0.58222675", "0.5821053", "0.5817365", "0.58152616", "0.5805654", "0.5802764", "0.5802635", "0.58001965", "0.57903475", "0.5785853", "0.5785853", "0.5785853", "0.578176", "0.57795405", "0.5777904", "0.577366", "0.5769528", "0.57615465", "0.5759482", "0.57585406", "0.575749", "0.5749287", "0.57489806", "0.5746824", "0.57412684", "0.57404774", "0.5739983", "0.57390165", "0.5729042", "0.57254684", "0.5722069", "0.5717799" ]
0.63319606
8
NewServer creates, initiates, and returns a new server. This function should NOT block. Instead, it should spawn one or more goroutines (to handle things like accepting incoming client connections, triggering epoch events at fixed intervals, synchronizing events using a forselect loop like you saw in project 0, etc.) and immediately return. It should return a nonnil error if there was an error resolving or listening on the specified port number.
func NewServer(port int, params *Params) (Server, error) { str := lspnet.JoinHostPort("localhost", strconv.Itoa(port)) ln, err := lspnet.ResolveUDPAddr("udp", str) if err != nil { fmt.Println("resolving error") return nil, err } conn, err := lspnet.ListenUDP("udp", ln) if err != nil { fmt.Println("listening error") return nil, err } epoch_interval = params.EpochMillis epoch_limit = params.EpochLimit window_size = params.WindowSize maxBackOffInterval = params.MaxBackOffInterval server := &server{ // server listening port ln: conn, // all clients clients: make(map[int]*client_data), addr: make(chan *lspnet.UDPAddr), mes: make(chan Message, 1), // current connection id cur_conn_id: 1, close_client: make(chan int), // send to Write send: make(chan Message), // send to Read read: make(chan Message, 2500), send_error: make(chan bool), closing: false, closed: make(chan int), one_client_closed: make(chan int, 100), close_accept: make(chan int, 100), close_conn_success: make(chan bool), is_client_alive: make(chan int), client_dead: make(chan int, 100), close_all: make(chan int,), } go accept(server) go serve(server) return server, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(addr string, port int) *Server {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn &Server{\n\t\taddr: addr,\n\t\tport: port,\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t}\n}", "func NewServer(port int, params *Params) (Server, error) {\n\n\t// Start listening\n\taddr, err := lspnet.ResolveUDPAddr(\"udp\", fmt.Sprint(\"localhost:\", port))\n\tif err != nil {\n\t\tLOGE.Println(\"Error resolving address: \" + fmt.Sprint(\"localhost:\", port))\n\t\treturn nil, errors.New(\"Error resolving address: \" + fmt.Sprint(\"localhost:\", port))\n\t}\n\tconn, err := lspnet.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\tLOGE.Println(fmt.Sprint(\"Error listening: \", err))\n\t\treturn nil, errors.New(fmt.Sprint(\"Error listening: \", err))\n\t}\n\n\t// Package and return server\n\ts := &server{\n\t\tclients: make(map[int]*cli),\n\t\taddrs: make(map[string]int),\n\t\tconn: conn,\n\t\tsend: NewUnboundedChannel(),\n\t\treceive: make(chan *clientMessage, channelBufferSize),\n\t\tparams: params,\n\t\ttoRead: NewUnboundedChannel(),\n\t\tconnIdCount: 1,\n\t\treqSeqNum: make(chan int),\n\t\tresSeqNum: make(chan int),\n\t\tkill: make(chan int),\n\t\tkillClient: make(chan int),\n\t\tkillClientResult: make(chan int),\n\t\tshutdown: make(chan int),\n\t\tshutdownComplete: make(chan int),\n\t\tclosing: false,\n\t}\n\n\t// Start goroutines\n\tgo s.masterHandler()\n\tgo s.netHandler()\n\n\tLOGS.Println(\"Server started listening\")\n\n\treturn s, nil\n\n}", "func NewServer(port string, newClients chan<- *Client, clientInput chan<- *ClientInputMessage) *Server {\n\tid := NewID(\"server\")\n\tlog := NewLogger(id)\n\treturn &Server{id, newClients, clientInput, port, nil, log}\n}", "func New(port string) *Server {\n\treturn &Server{\n\t\tport: port,\n\t\tmanager: endly.New(),\n\t}\n}", "func NewServer(port int) *Server {\n\treturn &Server{port: port}\n}", "func NewServer(h Handler, port int) (s *Server, err error) {\n\ts = &Server{\n\t\thandler: h,\n\t}\n\n\ts.ln, err = net.Listen(\"tcp\", \":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn s, err\n}", "func NewServer(port uint16, cmd *exec.Cmd) (*DefaultServer, error) {\n\tif port < 1024 {\n\t\treturn nil, IllegalArgumentError(\"port\")\n\t}\n\n\tcmd.Env = append(os.Environ(), fmt.Sprintf(\"PORT=%d\", port))\n\n\treturn &DefaultServer{\n\t\tport: port,\n\t\tcmd: cmd,\n\t\tclient: &http.Client{},\n\t}, nil\n}", "func NewServer(host string, port, interval int) *Server {\n\treturn &Server{\n\t\t// it's possible to wrap TimeManager and ClientManager with interface,\n\t\t// so they could be easy replaceable, but it would be an overkill for this lab\n\t\tTimeManager: newTimeManager(interval),\n\t\tClientManager: newClientManager(),\n\t\t// It's possible to pass it via CLI and validate it,\n\t\t// but there was nothing about protocol type it in lab,\n\t\t// so i don't want to experiment\n\t\tprotocol: \"tcp\",\n\t\thost: host,\n\t\tport: port,\n\t}\n}", "func NewServer(ports []uint, hosts []string, pipelineFactory *PipelineFactory) *Server {\n\ts := new(Server)\n\ts.ports = ports\n\ts.hosts = hosts\n\ts.pipelineFactory = pipelineFactory\n\ts.eventHandlers = make([]ServerEventHandler, 0)\n\tcurrentServerState = make(chan server_state)\n\n\treturn s\n}", "func NewServer(name string, port int) Server {\n\ts := new(serv)\n\ts.name = name\n\ts.ip = Here()\n\ts.port = port\n\n\ts.running = false\n\n\ts.pks = make(chan network.Packet)\n\n\treturn s\n}", "func NewServer(config Config) (*Server, error) {\n\tserver := &Server{\n\t\tstartTime: time.Now(),\n\t\tConfig: config,\n\t\ttcpServers: []*healthApi.Server{},\n\t\tconnectivity: &healthReport{},\n\t}\n\n\tswaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !config.Passive {\n\t\tcl, err := ciliumPkg.NewClient(config.CiliumURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tserver.Client = cl\n\t\tserver.Server = *server.newServer(swaggerSpec, 0)\n\t}\n\tfor port := range PortToPaths {\n\t\tsrv := server.newServer(swaggerSpec, port)\n\t\tserver.tcpServers = append(server.tcpServers, srv)\n\t}\n\n\treturn server, nil\n}", "func NewServer(cfg *config.Config) (*Server, error) {\n\tvar rpt report.Reporter\n\tvar err error\n\tswitch cfg.Report {\n\tcase \"http\":\n\t\trpt, err = report.NewHttpReport(&cfg.Http)\n\tcase \"database\":\n\t\trpt, err = report.NewSqlReporter(&cfg.DB)\n\tdefault:\n\t\terr = errors.New(fmt.Sprintf(\"unspport %v\", cfg.Report))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Server{cfg.TCP.Ports, rpt}, nil\n}", "func NewServer(addr string) (*Server, error) {\n\ts := &Server{\n\t\trequests: make(chan *protocol.NetRequest, 8),\n\t\tresponses: make(chan *protocol.NetResponse, 8),\n\t\tAddr: addr,\n\t\trunning: true,\n\t\tgames: make(map[uint64]poker.GameLike, 0),\n\t}\n\n\tlis, err := net.Listen(\"tcp\", serverAddr())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen: %v\\n\", err)\n\t}\n\tgrpcServer := grpc.NewServer()\n\tpb.RegisterGameServerServer(grpcServer, s)\n\n\tlog.Printf(\"server listening at %v\\n\", lis.Addr())\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to serve: `%v`\\n\", err)\n\t}\n\n\treturn s, nil\n}", "func NewServer(port int, path string, plumber *miniplumber.Plumber) (*Server, error) {\n\ts := &Server{\n\t\tserialConns: make(map[string]net.Conn),\n\t\tudsConns: make(map[string]net.Listener),\n\t\tcommands: make(map[int]*Command),\n\t\tclients: make(map[string]*client),\n\t\tvms: make(map[string]VM),\n\t\tpath: path,\n\t\tlastBroadcast: time.Now(),\n\t\tresponses: make(chan *Client, 1024),\n\t\tUseVMs: true,\n\t\tplumber: plumber,\n\t}\n\n\tif err := os.MkdirAll(filepath.Join(s.path, RESPONSE_PATH), 0775); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := s.Listen(port); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo s.responseHandler()\n\tgo s.clientReaper()\n\n\tlog.Debug(\"registered new ron server: %v\", port)\n\n\treturn s, nil\n}", "func NewServer(port int, params *Params) (Server, error) {\n\ts := &server{\n\t\tnextConnectId: 1,\n\t\tclients: make(map[int]*abstractClient),\n\t\treadFromClientChan: make(chan *msgPackage),\n\t\twriteToClientChan: make(chan *Message),\n\t\treadRequest: &requestRead{\n\t\t\task: make(chan int),\n\t\t\tresponse: make(chan *Message),\n\t\t},\n\t\twriteRequest: &requestWrite{\n\t\t\task: make(chan []byte),\n\t\t\tconnId: make(chan int),\n\t\t\tresponse: make(chan error),\n\t\t},\n\t\treadList: list.New(),\n\t\twriteList: list.New(),\n\n\t\tflag: false,\n\n\t\t// variables for window size\n\t\twindowSize: params.WindowSize,\n\t\tmapNeedSend: list.New(),\n\n\t\t// variables for epoch\n\t\tepochChan: make(chan int),\n\t\tepochMillis: params.EpochMillis,\n\t\tepochLimit: params.EpochLimit,\n\n\t\t// close\n\t\tdeleteClient: make(chan int),\n\t\tcloseConnRequest: &requestCloseConn{\n\t\t\task: make(chan int),\n\t\t\tgetError: make(chan error),\n\t\t},\n\t\twaitToWriteFinish: false,\n\t\twriteFinished: make(chan int),\n\t\twaitToAckFinish: false,\n\t\tackFinished: make(chan int),\n\t\tcloseRead: make(chan int, 1),\n\t\tcloseEpoch: make(chan int, 1),\n\t\tcloseEvent: make(chan int, 1),\n\n\t\t// close conn\n\t\tcloseConn: make(chan int, 1),\n\t}\n\n\t// start server\n\taddr, err := lspnet.ResolveUDPAddr(\"udp\", \"localhost:\"+strconv.Itoa(port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := lspnet.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.conn = conn\n\tgo s.readMessage()\n\tgo s.handleMessage()\n\tgo s.epochFire()\n\n\tfmt.Println(\"new server\")\n\treturn s, nil\n}", "func NewServer(port string) Server {\n\trouter := newRouter()\n\n\treturn &server{\n\t\tServer: &http.Server{\n\t\t\tAddr: \":\" + port,\n\t\t\tHandler: router,\n\t\t},\n\t\trouter: router,\n\t}\n}", "func NewServer(hostPort string) *Server {\n\treturn &Server{\n\t\thostPort: hostPort,\n\t}\n}", "func NewServer() *Server {}", "func NewServer(config *Config, services ...service) *Server {\n\treturn &Server{\n\t\tconfig: config,\n\t\tshutdownTimeout: defaultShutdownTimeout,\n\t\tservices: services,\n\t}\n}", "func NewServer(listenAddr string, methods map[string]CallBackFunc, timeout time.Duration, logger log.Logger) (svr *Server, err error) {\n\n\tlogger.Debug(fmt.Sprintf(\"New server with listenaddr=%s, methods=%v, timeout=%d\", listenAddr, methods, timeout))\n\tserver := Server{\n\t\tlistenAddr: listenAddr,\n\t\tmethods: methods,\n\t\ttimeout: timeout,\n\t\tlogger: logger,\n\t\tconnList: list.New()}\n\n\terr = server.listen()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn &server, nil\n}", "func NewServer(host string, port int, packetQueue chan PacketQueue) (*Server, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%d\", host, port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Info(\"Starting server...\", addr.String())\n\n\treturn &Server{\n\t\tpacketQueue: packetQueue,\n\t\taddr: addr,\n\t\tsocket: nil,\n\t\tconnections: make(map[*Connection]struct{}),\n\t\tsignal: make(chan os.Signal, 1),\n\t\tmutex: new(sync.Mutex),\n\t}, nil\n}", "func NewServer(addr string,\n\thandler func(conn Conn, cmd Command),\n\taccept func(conn Conn) bool,\n\tclosed func(conn Conn, err error),\n) *Server {\n\treturn NewServerNetwork(\"tcp\", addr, handler, accept, closed)\n}", "func NewServer(addr string, n http.Handler) (Server, error) {\n\tconf := ServerConfig{\n\t\tTimeout: time.Minute,\n\t\tHandler: n,\n\t\tAddress: addr,\n\t}\n\n\treturn conf.Resolve()\n}", "func New() (*Server, error) {\n\treturn &Server{}, nil\n}", "func NewServer(config Config, shutdownChan chan bool) *server {\n\tif config.ReadTimeout == 0 {\n\t\tconfig.ReadTimeout = 10 * time.Second\n\t}\n\n\tif config.WriteTimeout == 0 {\n\t\tconfig.WriteTimeout = 10 * time.Second\n\t}\n\n\tconfig.nextCommandTimeout = 5 * time.Minute\n\n\treturn &server{\n\t\tconfig: config,\n\t\tshutdownChan: shutdownChan,\n\t}\n}", "func NewServer(addr string, handler http.Handler, readTimeout, writeTimeout, shutTimeout time.Duration) *Server {\n\tisGraceful := false\n\tif os.Getenv(GRACEFUL_ENVIRON_KEY) != \"\" {\n\t\tisGraceful = true\n\t}\n\n\tif readTimeout <= 0 {\n\t\treadTimeout = DEFAULT_READ_TIMEOUT\n\t}\n\n\tif writeTimeout <= 0 {\n\t\twriteTimeout = DEFAULT_WRITE_TIMEOUT\n\t}\n\n\tif shutTimeout <= 0 {\n\t\tshutTimeout = DEFAULT_SHUT_TIMEOUT\n\t}\n\n\treturn &Server{\n\t\thttpServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: handler,\n\n\t\t\tReadTimeout: readTimeout * time.Second,\n\t\t\tWriteTimeout: writeTimeout * time.Second,\n\t\t},\n\t\tisGraceful: isGraceful,\n\t\tshutTimeout: shutTimeout * time.Second,\n\t\tendRunning: make(chan bool, 1),\n\t\tisRestart: false,\n\t\tisHttps: false,\n\t}\n}", "func NewServer() *Server {\n\n\treturn &Server{\n\t\tConfig: Config{\n\t\t\tPort: \":8080\",\n\t\t},\n\t}\n}", "func NewServer(config *Config) Server {\n\treturn &server{\n\t\tport: config.Port,\n\t\trouter: NewRouter(config.Endpoints),\n\t}\n}", "func NewServer(rpc *cosmos.RPC, eventPublisher *publisher.EventPublisher, tokenToRunnerHash *sync.Map, logger tmlog.Logger) *Server {\n\treturn &Server{\n\t\trpc: rpc,\n\t\teventPublisher: eventPublisher,\n\t\ttokenToRunnerHash: tokenToRunnerHash,\n\t\texecInProgress: &sync.Map{},\n\t\tlogger: logger,\n\t}\n}", "func NewServer(port int, params *Params) (Server, error) {\n\taddr,err := lspnet.ResolveUDPAddr(\"udp\", \":\" + strconv.Itoa(port))\n\tfmt.Print(\"Server:\" + strconv.Itoa(port))\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\tconn,err := lspnet.ListenUDP(\"udp\", addr)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\tres := server{conn:conn,addr:addr,portPool:0,\n\t\t idToClient:make(map[int]*clientHandle),\n\t\t\t\t\t\t\t params:params,addrToId:make(map[string]int),\n\t\t\t\t\t\t\t\tprocessedRead:make(chan *processedReadMessage,3000)}\n\tgo poll(&res)\n\treturn &res, nil\n}", "func NewServer(options Options, observationContext *observation.Context) goroutine.BackgroundRoutine {\n\taddr := fmt.Sprintf(\":%d\", options.Port)\n\thandler := newHandlerWithMetrics(options, glock.NewRealClock(), observationContext)\n\thttpHandler := ot.Middleware(httpserver.NewHandler(handler.setupRoutes))\n\tserver := httpserver.NewFromAddr(addr, &http.Server{Handler: httpHandler})\n\tjanitor := goroutine.NewPeriodicGoroutine(context.Background(), options.CleanupInterval, &handlerWrapper{handler})\n\treturn goroutine.CombinedRoutine{server, janitor}\n}", "func NewServer(address string, port int) (server *TaggedServer) {\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", address, port))\n\tif err != nil {\n\t\t// handle error\n\t\tserver = nil\n\t} else {\n\t\tserver = &TaggedServer{\n\t\t\tlistener: ln,\n\t\t\tdone: false,\n\t\t\tmutex: &sync.Mutex{},\n\t\t}\n\t}\n\treturn server\n}", "func NewServer(port int, params *Params) (Server, error) {\n\taddr, err := lspnet.ResolveUDPAddr(\"udp\", \":\"+strconv.Itoa(port))\n\tif err != nil {\n\t\tfmt.Println(\"Error on ResolveUDPAddr\")\n\t\treturn nil, err\n\t}\n\tudpConn, err2 := lspnet.ListenUDP(\"udp\", addr)\n\tif err2 != nil {\n\t\tfmt.Println(\"Error in ListenUDP\")\n\t\treturn nil, err2\n\t}\n\n\ts := &server{\n\t\tudpConn: udpConn,\n\t\trequestQueue: make(chan *info),\n\t\tnextClientId: 1,\n\t\tparams: params,\n\t\treadResult: make(chan *Message),\n\t\treadRequest: make(chan int),\n\t\treadBlock: make(chan int),\n\t\treadClientLost: make(chan int),\n\t\tcloseRequest: make(chan int),\n\t\tcloseBlock: make(chan int),\n\t\tcloseClientConnectRequest: make(chan int),\n\t\tcloseAcptReadRoutine: make(chan int),\n\t\tcloseReadRoutine: make(chan int),\n\t\tcloseEpochFile: make(chan int),\n\t\twriteTaskQueue: make(chan *shortMessageType),\n\t\twriteResult: make(chan bool),\n\t\tclientMap: make(map[int]*clientTrackingMap),\n\t\treadyToWriteTask: make(chan *writeBackMessage),\n\t\treadStorage: list.New(),\n\t\twriteStorage: list.New(),\n\t\twriteTask: make(chan int),\n\t\tseq: 1,\n\t\tclientAddrSet: make(map[lspnet.UDPAddr]int),\n\t\tticker: time.NewTicker(time.Duration(params.EpochMillis) * time.Millisecond),\n\t\tepochRenew: make(chan int),\n\t\tclientCloseError: make(chan bool),\n\t\tisCalledClose: false,\n\t\tserverClosed: make(chan int),\n\t\tserverAlreadyClosed: false,\n\t\tlostClient: list.New(),\n\t}\n\t// accepting clients && read\n\tgo acceptAndRead(s)\n\n\t// Main server handling routine\n\tgo mainRoutine(s)\n\n\t// A routine for epoch ticker\n\tgo epochFire(s)\n\n\treturn s, nil\n}", "func NewServer(opts ...ServerOpt) *Server {\n\tret := &Server{}\n\tfor _, opt := range opts {\n\t\topt(ret)\n\t}\n\tif ret.socket == nil {\n\t\tsock, _ := makeSocket(\"\")\n\t\tret.socket = sock\n\t}\n\treturn ret\n}", "func NewServer(authFunc, cmdFunc func(io.ReadWriter, []byte) error) (*Server, error) {\n\tvar err error\n\ts := new(Server)\n\ts.ln, err = nettest.NewLocalListener(\"tcp\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.serve(authFunc, cmdFunc)\n\treturn s, nil\n}", "func NewServer() Server {\n\treturn Server{\n\t\tport: \"5000\",\n\t\tserver: gin.Default(),\n\t}\n}", "func NewServer(port string, logger *log.Logger, limits ...Limits) (*Server, error) {\n\ts := &Server{\n\t\tAddr: port,\n\t\tlog: logger,\n\t\tshuttingDown: false,\n\t}\n\t// limits are optional, if no limits were provided, use the default ones\n\tif len(limits) == 1 {\n\t\ts.Limits = limits[0]\n\t} else {\n\t\ts.Limits = DefaultLimits\n\t}\n\treturn s, nil\n}", "func NewServer(ctx context.Context, factory dependency.Factory) (*Server, error) {\n\tctx1, cancel := context.WithCancel(ctx)\n\n\ts := &Server{\n\t\tctx: ctx1,\n\t\tcancel: cancel,\n\t\tquerynode: qn.NewQueryNode(ctx, factory),\n\t\tgrpcErrChan: make(chan error),\n\t}\n\treturn s, nil\n}", "func NewServer(t *testing.T, dbc *sql.DB) (*server.Server, string) {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tjtest.RequireNil(t, err)\n\n\tgrpcServer := grpc.NewServer(\n\t\tgrpc.UnaryInterceptor(interceptors.UnaryServerInterceptor),\n\t\tgrpc.StreamInterceptor(interceptors.StreamServerInterceptor))\n\n\tsrv := server.New(dbc, dbc)\n\n\tpb.RegisterGokuServer(grpcServer, srv)\n\n\tgo func() {\n\t\terr := grpcServer.Serve(l)\n\t\tjtest.RequireNil(t, err)\n\t}()\n\n\treturn srv, l.Addr().String()\n}", "func NewServer(addr string, allowDebug bool) (*Server, error) {\n\t// basic server address validation\n\tif addr == \"\" {\n\t\treturn nil, errors.New(\"Invalid address\")\n\t}\n\n\treturn &Server{\n\t\tAddr: addr,\n\t\tClients: NewClientState(),\n\t\tLogger: debug.NewLogger(allowDebug),\n\t\tBroadcast: make(chan chat.ResponseStream, 1000),\n\t}, nil\n}", "func New(addr string) (*Server, error) {\n\ts := &Server{\n\t\taddr: addr,\n\t\tshutdownTimeout: time.Minute,\n\t\tSessions: make(chan *Session),\n\t}\n\ts.hs = &http.Server{Handler: s}\n\tln, err := net.Listen(\"tcp\", s.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.ln = ln\n\ts.ListeningAddr = fmt.Sprintf(\":%d\", s.ln.Addr().(*net.TCPAddr).Port)\n\treturn s, nil\n}", "func NewServer() *Server {\n\ts := &Server{quit: make(chan bool)}\n\treturn s\n}", "func NewServer(tcp_port string, udp_port string, address string, max_connections int, cas bool, flush bool,\n\t verbosity int, bytes_of_memory int64) *Server {\n\tserver := new(Server)\n\tserver.tcp_socket = nil\n\tserver.tcp_port = tcp_port\n\tserver.udp_port = udp_port\n\tserver.cas_disabled = cas\n\tserver.flush_disabled = flush\n\tserver.connection_limit = max_connections\n\tserver.listen_address = address\n\tserver.storage = cache.New(bytes_of_memory)\n\tserver.connections = make(map[string] net.Conn)\n\tserver.Stat = statistic.New(bytes_of_memory, tcp_port, udp_port, max_connections, verbosity, cas, flush)\n\tserver.Logger = NewServerLogger(verbosity)\n\treturn server\n}", "func NewServer(tb testing.TB, a server.Adapter, opts *server.Options) *Server {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\ttb.Helper()\n\t\ttb.Fatalf(\"net.Listen failed: %s\", err)\n\t}\n\treturn &Server{\n\t\tl: l,\n\t\ts: &server.Server{\n\t\t\tAddr: \"tcp://\" + l.Addr().String(),\n\t\t\tAdapter: a,\n\t\t\tOptions: opts,\n\t\t},\n\t}\n}", "func NewServer(config *Config, serverConfig *ServerConfig) *Server {\n\tformat := serverConfig.Format\n\tif format == nil {\n\t\tformat = config.DefaultFormat\n\t}\n\n\tserver := &Server{\n\t\tid: serverConfig.ID,\n\t\tlock: sync.Mutex{},\n\t\tstopper: gstop.New(),\n\t\tformat: format,\n\t\trouters: make(map[int64]*Router, defaultMapSize),\n\t\tworkers: make(map[string]*worker, defaultMapSize),\n\t}\n\n\tif existsServer, ok := serverDB[server.id]; ok {\n\t\t_ = existsServer.Stop()\n\n\t\tdelete(serverDB, server.id)\n\t}\n\n\tserverDB[server.id] = server\n\n\tserver.initial(config, serverConfig)\n\n\treturn server\n}", "func NewServer(ops ...Option) (*Server, error) {\n\tconf := toGRPCConfig(ops...)\n\tvar srv *grpc.Server\n\tif conf.tlsConfig != nil {\n\t\tsrv = grpc.NewServer(grpc.Creds(credentials.NewTLS(conf.tlsConfig)), grpc.MaxRecvMsgSize(math.MaxInt32), grpc.MaxSendMsgSize(math.MaxInt32))\n\t} else {\n\t\tsrv = grpc.NewServer(grpc.MaxRecvMsgSize(math.MaxInt32), grpc.MaxSendMsgSize(math.MaxInt32))\n\t}\n\n\trpc.RegisterGRpcServer(srv)\n\n\tls, err := net.Listen(\"tcp\", conf.addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"grpc: listen failed, addr = %s\", conf.addr)\n\t}\n\n\treturn &Server{\n\t\tserver: srv,\n\t\tlistener: ls,\n\t\trunning: utils.NewAtomicBool(false),\n\t\treadyCh: make(chan struct{}),\n\t\tstopCh: make(chan struct{}),\n\t}, nil\n}", "func NewServer(config *Config) *Server {\n\tif config == nil {\n\t\tconfig = &Config{}\n\t}\n\n\tvar port uint = 5000\n\tif config.Port != 0 {\n\t\tport = config.Port\n\t}\n\n\treturn &Server{\n\t\thost: fmt.Sprintf(\"0.0.0.0:%v\", port),\n\t\tdebug: config.Debug,\n\t\tipfsHost: config.IPFSHost,\n\t\tipfsGateway: ipfs.NormalizeGatewayURL(config.IPFSGateway),\n\t\tcidResolvers: config.CIDResolvers,\n\t\tcidStorePath: config.CIDStorePath,\n\t\ttlsCertPath: config.TLSCertPath,\n\t\ttlsKeyPath: config.TLSKeyPath,\n\t}\n}", "func NewServer(hostPort string) (*Server, error) {\n\tdb, err := newDatabase()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Server{\n\t\thostPort: hostPort,\n\t\tdatabase: db,\n\t}, nil\n}", "func NewServer(proto, addr string, job *engine.Job) (Server, error) {\n\t// Basic error and sanity checking\n\tswitch proto {\n\tcase \"tcp\":\n\t\treturn setupTcpHttp(addr, job)\n\tdefault:\n\t\treturn nil, errors.New(\"Invalid protocol format. Windows only supports tcp.\")\n\t}\n}", "func NewServer(c *support.ConfigT) *ServerT {\n\trenderer := multitemplate.NewRenderer()\n\t// Initialize the error templates.\n\trenderer.AddFromString(\"error/404\", html.ErrorTpl404())\n\trenderer.AddFromString(\"error/500\", html.ErrorTpl500())\n\trenderer.AddFromString(\"default/welcome\", html.WelcomeTpl())\n\n\tr := newRouter(c)\n\tr.HTMLRender = renderer\n\n\ts := &http.Server{\n\t\tAddr: c.HTTPHost + \":\" + c.HTTPPort,\n\t\tHandler: r,\n\t\tMaxHeaderBytes: c.HTTPMaxHeaderBytes,\n\t\tReadTimeout: c.HTTPReadTimeout,\n\t\tReadHeaderTimeout: c.HTTPReadHeaderTimeout,\n\t\tWriteTimeout: c.HTTPWriteTimeout,\n\t\tIdleTimeout: c.HTTPIdleTimeout,\n\t}\n\ts.ErrorLog = zap.NewStdLog(support.Logger.Desugar())\n\n\tif c.HTTPSSLEnabled == true {\n\t\ts.Addr = c.HTTPHost + \":\" + c.HTTPSSLPort\n\t}\n\n\treturn &ServerT{\n\t\tConfig: c,\n\t\tGRPC: nil, // to be implemented\n\t\tHTTP: s,\n\t\tHTMLRenderer: renderer,\n\t\tRouter: r,\n\t}\n}", "func NewServer(addr string) *Server {\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)\n\n\treturn &Server{\n\t\taddr: addr,\n\t\trouter: http.NewServeMux(),\n\t\tquit: quit,\n\t}\n}", "func NewServer(cfg *ServerConfig) *server {\n\treturn &server{\n\t\tPort: cfg.ServerPort,\n\t\tNodes: cfg.TotalNodes,\n\t\tEndPoint: getEndPoint(cfg.ServerPort),\n\t\tServerID: generateID(cfg.ServerPort),\n\t\tCurrentState: Follower,\n\t\tTerm: 0,\n\t\tVotedFor: NotVotedYet,\n\t\tPeers: cfg.PeerPorts,\n\t\tmutex: &sync.Mutex{},\n\t}\n}", "func New(\n\taddr string,\n\thandler Handler,\n\tlog *log.Logger,\n\tworkersCount uint8,\n) (srv *Server) {\n\tsrv = &Server{\n\t\taddr: addr,\n\t\thandler: handler,\n\t\tlog: log,\n\t\tClients: newClients(),\n\t\tchStop: make(chan bool, 1),\n\t\tchRequest: make(chan *tRequest, workersCount),\n\t}\n\n\treturn\n}", "func NewServer(logger *logrus.Logger, port int, handler http.Handler) *Server {\n\tserver := &http.Server{\n\t\tHandler: handler,\n\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\tReadTimeout: time.Second * 30,\n\t\tWriteTimeout: time.Second * 60,\n\t\tIdleTimeout: time.Second * 60,\n\t}\n\n\treturn &Server{\n\t\tport: port,\n\t\tlogger: logger,\n\t\tserver: server,\n\t}\n}", "func New(opt *Options) (server *Server, err error) {\n\tserver = &Server{\n\t\toptions: opt,\n\t\tServer: http.Server{\n\t\t\tAddr: fmt.Sprintf(\"0.0.0.0:%v\", opt.Config.Port),\n\t\t\tErrorLog: slog.New(log.New().Writer(), \"server\", 0),\n\t\t},\n\t}\n\n\tserver.Handler, err = server.createHandler()\n\treturn\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\tcodecs: make(map[string]Codec),\n\t\tservices: new(serviceMap),\n\t}\n}", "func NewServer() *Server {\n\treturn &Server{name: \"\", handlers: nil}\n}", "func NewServer() *Server {\n\tc := config.GetInstance()\n\n\treturn &Server {\n\t\tinstance: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", c.Server.Port),\n\t\t\tReadTimeout: time.Duration(c.Server.Timeouts.Read) * time.Second,\n\t\t\tWriteTimeout: time.Duration(c.Server.Timeouts.Write) * time.Second,\n\t\t},\n\t\tresources: &Resources{\n\t\t\tDB: db.NewFCDB(),\n\t\t},\n\t\trunning: false,\n\t}\n}", "func NewServer(name string, logger termlog.Logger) *Server {\n\tbroadcast := make(chan string, 50)\n\ts := &Server{\n\t\tname: name,\n\t\tbroadcast: broadcast,\n\t\tconnections: make(map[*websocket.Conn]bool),\n\t\tlogger: logger,\n\t}\n\tgo s.run(broadcast)\n\treturn s\n}", "func NewServer(addr string, port int, devMode bool, logger log.Logger, repo core.Repository) *Server {\n\ts := &Server{Logger: logger, Repo: repo}\n\n\tif !devMode {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\ts.Router = gin.New()\n\n\ts.Router.Use(\n\t\tmiddleware.GinReqLogger(logger, time.RFC3339, \"request served\", \"http-router-mux\"),\n\t)\n\tif !devMode {\n\t\ts.Router.Use(gin.Recovery())\n\t}\n\n\t// Create http.Server\n\ts.HTTPServer = http.Server{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", addr, port),\n\t\tHandler: s.Router,\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\ts.setupRoutes(devMode)\n\n\treturn s\n}", "func NewServer() *Server {\n\tserver := &Server{\n\t\tmessages: make(chan []byte, 1),\n\t\tclients: make(map[chan []byte]bool),\n\t\tregister: make(chan chan []byte),\n\t\tunregister: make(chan chan []byte),\n\t}\n\tgo server.listen()\n\treturn server\n}", "func newServer(config Config) *http.Server {\n\treturn &http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", config.Port),\n\t\tHandler: newRouter(config),\n\t}\n}", "func NewServer() *server {\n\treturn &server{}\n}", "func New(options ...OptionsFunc) (*Server, error) {\n\ts := &Server{\n\t\tauxAddr: \":9090\",\n\t\tstopChan: make(chan struct{}, 1),\n\t}\n\n\tfor _, f := range options {\n\t\tif err := f(s); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"options func failed\")\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n\treturn &Server{}\n}", "func NewServer() *Server {\n return &Server{\n Addr: DefaultAddr,\n }\n}", "func NewServer(config *Config) *Server {\n\tif config == nil {\n\t\tconfig = &Config{}\n\t}\n\n\tvar port uint = 5000\n\tif config.Port != 0 {\n\t\tport = config.Port\n\t}\n\n\treturn &Server{\n\t\thost: fmt.Sprintf(\"0.0.0.0:%v\", port),\n\t\tdebug: config.Debug,\n\t\tipfsGateway: ipfs.NormalizeGatewayURL(config.IPFSGateway),\n\t\ttlsCrtPath: config.TLSCrtPath,\n\t\ttlsKeyPath: config.TLSKeyPath,\n\t}\n}", "func NewServer() (server *Server, err error) {\n\tserver = &Server{\n\t\tserviceName: OwnService,\n\t\thandlers: make(map[string]*handlerEntry),\n\t\tstreamingHandlers: make(map[string]*handlerEntry),\n\t}\n\tlistenAddr := \":\" + core.InstanceListenPortFlag.Get()\n\tserver.listener, err = net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserver.grpcServer = grpc.NewServer()\n\tcore.RegisterLeverRPCServer(server.grpcServer, server)\n\treturn server, nil\n}", "func NewServer(port int) *Server {\n\tret := new(Server)\n\tret.Port = port\n\tret.Registry = new(Registry)\n\tret.Registry.mappings = make(map[string]*Client)\n\treturn ret\n}", "func TcpPort_NewServer(s TcpPort_Server, policy *server.Policy) *server.Server {\n\tc, _ := s.(server.Shutdowner)\n\treturn server.New(TcpPort_Methods(nil, s), s, c, policy)\n}", "func NewServer(config *ServerConfig) *Server {\n\tserver := &Server{\n\t\tdnsOrIpaddr: config.DNSOrIPAddr,\n\t\tport: config.Port,\n\t\tcompletedLongTTL: config.LongTrim,\n\t\tcompletedAckTrim: config.ShortTrim,\n\t\tdeadlineIO: config.DeadlineIO,\n\t\tkeepAlivePeriod: config.KeepAlivePeriod,\n\t\tdontStartTrimmers: config.dontStartTrimmers,\n\t\tlogger: config.Logger,\n\t\ttlsCertificate: config.TLSCertificate}\n\tif server.logger == nil {\n\t\tvar logBuf bytes.Buffer\n\t\tserver.logger = log.New(&logBuf, \"\", 0)\n\t}\n\tserver.svrMap = make(map[string]*methodArgs)\n\tserver.perClientInfo = make(map[uint64]*clientInfo)\n\tserver.completedTickerDone = make(chan bool)\n\tserver.connections = list.New()\n\n\treturn server\n}", "func NewServer() Server {\n\treturn &server{}\n}", "func NewServer(opts ...server.Option) server.Server {\n\treturn newServer(opts...)\n}", "func NewServer(debug bool, verbose bool) *Server {\n\tserver := &Server{\n\t\tserverCommon: serverCommon{\n\t\t\tdebug: debug,\n\t\t\tverbose: verbose,\n\t\t},\n\t\tlisteners: map[string]*Listener{},\n\t}\n\n\treturn server\n}", "func NewServer(ip string, port string) *Server {\n\treturn &Server{ip: ip, port: port, acceptedAddrs: make([]*net.UDPAddr, 0), ReadQueue: make(chan *gamedata.Packet, 10), AcceptQueue: make(chan *client.AcceptUDPPacket, 2)}\n}", "func New() *Server {\n\treturn &Server{}\n}", "func New() *Server {\n\treturn &Server{}\n}", "func CreateServer(port string, intake chan WriteTicket) error {\n\ts, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Server up on port %s\\n\", port)\n\tfor {\n\t\tconn, err := s.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error in connection: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(conn, intake)\n\t}\n}", "func NewServer(\n\tclient client.Client,\n\taddress string,\n\tcontextPool context.Pool,\n\topts *tchannel.ChannelOptions,\n) ns.NetworkService {\n\treturn &server{\n\t\taddress: address,\n\t\tclient: client,\n\t\tcontextPool: contextPool,\n\t\topts: opts,\n\t}\n}", "func NewServer(host string, port int, scheme string) Server {\n\treturn &BasicServer{\n\t\thost: host,\n\t\tport: uint16(port),\n\t\tscheme: scheme,\n\t}\n}", "func newServer(ctx common.Context, self *replica, listener net.Listener, workers int) (net.Server, error) {\n\tserver := &rpcServer{ctx: ctx, logger: ctx.Logger(), self: self}\n\treturn net.NewServer(ctx, listener, serverInitHandler(server), workers)\n}", "func NewServer(bind string, shutdownTimeout time.Duration, handler http.Handler) *Server {\n\treturn &Server{\n\t\tsvr: &http.Server{Addr: bind, Handler: handler},\n\t\tshutdownTimeout: shutdownTimeout,\n\t}\n}", "func NewServer(config *Config, opts []grpc.ServerOption) (*Server, error) {\n\tif config == nil {\n\t\treturn nil, errors.New(\"config not provided\")\n\t}\n\n\ts := grpc.NewServer(opts...)\n\treflection.Register(s)\n\n\tsrv := &Server{\n\t\ts: s,\n\t\tconfig: config,\n\t\tclients: map[string]*Client{},\n\t}\n\tvar err error\n\tif srv.config.Port < 0 {\n\t\tsrv.config.Port = 0\n\t}\n\tsrv.lis, err = net.Listen(\"tcp\", fmt.Sprintf(\":%d\", srv.config.Port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open listener port %d: %v\", srv.config.Port, err)\n\t}\n\tgnmipb.RegisterGNMIServer(srv.s, srv)\n\tlog.V(1).Infof(\"Created Server on %s\", srv.Address())\n\treturn srv, nil\n}", "func NewServer() *Server {\n\treturn new(Server)\n}", "func NewServer(\n\tlogger hclog.Logger,\n\thttp clients.HTTP) *Server {\n\treturn &Server{\n\t\tplugins: []ServerPlugin{},\n\t\tpluginInfos: []PluginInfo{},\n\t\tstarted: false,\n\t\tLogger: logger,\n\t\thttp: http,\n\t}\n}", "func NewServer(addr string) *Server {\n\treturn &Server{\n\t\taddr: addr,\n\t\thandlers: make(map[string]HandlerFunc),\n\t}\n}", "func NewServer(cfg *Config) *Server {\n\ts := NewUnstartedServer(cfg)\n\ts.Start()\n\treturn s\n}", "func NewServer(cfg *config.Config, driver IDriver) (*Server, error) {\n\ts := &Server{\n\t\tcfg: cfg,\n\t\tdriver: driver,\n\t\tqueryCtxs: make(map[string]QueryCtx),\n\t\tquitCh: make(chan struct{}, 1),\n\t}\n\tvar err error\n\tif s.cfg.Host != \"\" && s.cfg.Port != 0 {\n\t\taddr := fmt.Sprintf(\"%s:%d\", s.cfg.Host, s.cfg.Port)\n\t\tif s.listener, err = net.Listen(\"tcp\", addr); err == nil {\n\t\t\tlogutil.Logger(context.Background()).Info(\"server is running TCP listener\", zap.String(\"addr\", addr))\n\t\t}\n\t} else {\n\t\terr = errors.New(\"Server not configured to listen on either -socket or -host and -port\")\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\ts.rpcServer = NewRPCServer(s)\n\n\tif s.cfg.HBase.ThriftEnable {\n\t\tzDriver := driver.(*ZettaDriver)\n\t\ttServer, err := hthrift.NewTServer(s.cfg, session.CreateSessionFunc(zDriver.Store))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\ts.tServer = tServer\n\t}\n\n\t// Init rand seed for randomBuf()\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn s, nil\n}", "func NewServer(c Configuration, b *builder.Builder, stg astichat.Storage) *Server {\n\tastilog.Debug(\"Starting server\")\n\treturn &Server{\n\t\tchannelQuit: make(chan bool),\n\t\tserverHTTP: NewServerHTTP(c.Addr.HTTP, c.PathStatic, b, stg),\n\t\tserverUDP: NewServerUDP(stg),\n\t\tstartedAt: time.Now(),\n\t}\n}", "func NewServer(opts Opts) (net.Listener, *grpc.Server) {\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", opts.Host, opts.Port))\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on %s:%d: %v\", opts.Host, opts.Port, err)\n\t}\n\tlog.Notice(\"Listening on %s:%d\", opts.Host, opts.Port)\n\n\ts := grpc.NewServer(OptionalTLS(opts.KeyFile, opts.CertFile, opts.TLSMinVersion,\n\t\tgrpc.ChainUnaryInterceptor(append([]grpc.UnaryServerInterceptor{\n\t\t\tLogUnaryRequests,\n\t\t\tserverMetrics.UnaryServerInterceptor(),\n\t\t\tgrpc_recovery.UnaryServerInterceptor(),\n\t\t}, unaryAuthInterceptor(opts)...)...),\n\t\tgrpc.ChainStreamInterceptor(append([]grpc.StreamServerInterceptor{\n\t\t\tLogStreamRequests,\n\t\t\tserverMetrics.StreamServerInterceptor(),\n\t\t\tgrpc_recovery.StreamServerInterceptor(),\n\t\t}, streamAuthInterceptor(opts)...)...),\n\t\tgrpc.MaxRecvMsgSize(419430400), // 400MB\n\t\tgrpc.MaxSendMsgSize(419430400),\n\t)...)\n\n\tserverMetrics.InitializeMetrics(s)\n\treflection.Register(s)\n\tif !opts.NoHealth {\n\t\tgrpc_health_v1.RegisterHealthServer(s, health.NewServer())\n\t}\n\treturn lis, s\n}", "func NewServer(\n\tisTestMode bool,\n\tconf *configs.Config,\n\tport int,\n\tdbModeler dbmodel.DBModeler,\n\tmongoModeler mongomodel.MongoModeler) *Server {\n\n\tif port == 0 {\n\t\tport = conf.Server.Port\n\t}\n\n\tsrv := Server{\n\t\tisTestMode: isTestMode,\n\t\tconf: conf,\n\t\tport: port,\n\t\tdbModeler: dbModeler,\n\t\tmongoModeler: mongoModeler,\n\t\tgin: gin.New(),\n\t}\n\treturn &srv\n}", "func New(cfg config.ServerConfig, db database.Database) *Server {\n\treturn &Server{\n\t\trouter: gin.Default(),\n\t\tport: cfg.Port,\n\t\tdb: db,\n\t}\n}", "func NewServer() Server {\n\ts := server{}\n\treturn &s\n}", "func New(initCtx context.Context, c *configpb.ServerConf, l *logger.Logger) (*Server, error) {\n\tconn, err := Listen(&net.UDPAddr{Port: int(c.GetPort())}, l)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\t<-initCtx.Done()\n\t\tconn.Close()\n\t}()\n\n\ts := &Server{\n\t\tc: c,\n\t\tconn: conn,\n\t\tl: l,\n\t}\n\n\treturn s, s.initConnection()\n}", "func NewServer() *Server {\n\treturn &Server{\n\t\thandlers: make(map[string]JobHandler),\n\t}\n}" ]
[ "0.7516474", "0.7375979", "0.72823966", "0.7276561", "0.7263422", "0.7193755", "0.7175273", "0.7150717", "0.70504516", "0.7021117", "0.6984167", "0.69353646", "0.6934183", "0.69332665", "0.6932684", "0.6928796", "0.69018936", "0.68757033", "0.68631876", "0.68569875", "0.68318254", "0.68232244", "0.6795817", "0.6791467", "0.6790962", "0.6780685", "0.6770154", "0.67619985", "0.67445475", "0.6724924", "0.6721368", "0.6711894", "0.6710381", "0.6702375", "0.66829014", "0.667843", "0.6669969", "0.6669395", "0.6666859", "0.6657141", "0.6651332", "0.6647547", "0.66461396", "0.6627912", "0.6622569", "0.66185284", "0.6616152", "0.66107327", "0.66042995", "0.6603348", "0.65944946", "0.659403", "0.6593421", "0.658745", "0.65863127", "0.65851724", "0.657815", "0.65723974", "0.6570883", "0.65706813", "0.6568227", "0.6565208", "0.65571946", "0.65460515", "0.65452707", "0.65452707", "0.65452707", "0.65452707", "0.65452707", "0.65452707", "0.65409124", "0.65398544", "0.65262127", "0.65144116", "0.65104884", "0.6509658", "0.6507775", "0.65011144", "0.65006703", "0.64976716", "0.649408", "0.649408", "0.648506", "0.64818615", "0.64785343", "0.64697254", "0.6459217", "0.6458076", "0.6457406", "0.64564687", "0.64562786", "0.6451473", "0.6449487", "0.64455366", "0.64341545", "0.6411311", "0.64084935", "0.6406041", "0.64043343", "0.6403833" ]
0.6980947
11
TestAddPerson tests the functionality of AddPerson
func TestAddPerson(t *testing.T) { var ( err error user, testUser User addPerson = func(fname, lname, jobType, officeName, livingspaceName string) { if livingspaceName != "" { _, err = CreateRoom(con, livingspaceName, "livingspace") } if officeName != "" { _, err = CreateRoom(con, officeName, "office") } So(err, ShouldBeNil) user, err = AddPerson(con, fname, lname, jobType, officeName, livingspaceName) } ) Convey("Tests for AddPerson", t, func() { Convey("AddPerson should return a User with all correct values present and an error", func() { var runValuesTests = func(rm models.Room) { So(rm.Capacity, ShouldNotEqual, 0) So(rm.ID, ShouldNotBeBlank) So(rm.Name, ShouldNotBeBlank) So(rm.Type, ShouldNotBeBlank) } addPerson("Jade", "Flora", "fellow", "Narnia", "PHP") So(err, ShouldBeNil) So(user.FirstName, ShouldNotBeBlank) So(user.ID, ShouldNotBeBlank) So(user.LastName, ShouldNotBeBlank) So(user.Type, ShouldNotBeBlank) So(user.User, ShouldNotResemble, testUser.User) runValuesTests(user.LivingSpace) runValuesTests(user.Office) }) Convey("Print the successfully created User and Room ", func() { addPerson("Jackson", "Davids", "fellow", "", "Mogadishu") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func addPerson(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\tuser, err = controllers.AddPerson(con, args.Get(0), args.Get(1), args.Get(2), args.Get(3), args.Get(4))\n\t)\n\n\texitOnError(err)\n\n\tprintUserDetails(user)\n\n\treturn nil\n}", "func (pm *personManagement) AddPerson(params []string, stub shim.ChaincodeStubInterface) peer.Response {\n\tjsonObj := params[0]\n\tvar person Person\n\n\t// Read person info into struct\n\tjson.Unmarshal([]byte(jsonObj), &person)\n\n\tval, err := stub.GetState(person.ID)\n\tif err != nil {\n\t\tfmt.Printf(\"[ERROR] cannot get state, because of %s\\n\", err)\n\t\treturn shim.Error(fmt.Sprintf(\"%s\", err))\n\t}\n\n\tif val != nil {\n\t\terrMsg := fmt.Sprintf(\"[ERROR] person already exists, cannot create two accounts with same ID <%d>\", person.ID)\n\t\tfmt.Println(errMsg)\n\t\treturn shim.Error(errMsg)\n\t}\n\n\tfmt.Println(\"Adding new person\", person)\n\tif err = stub.PutState(person.ID, []byte(jsonObj)); err != nil {\n\t\terrMsg := fmt.Sprintf(\"[ERROR] cannot store person record with id <%d>, due to %s\", person.ID, err)\n\t\tfmt.Println(errMsg)\n\t\treturn shim.Error(errMsg)\n\t}\n\treturn shim.Success(nil)\n}", "func AddPerson(name string, age, phone int) {\n\n\tsession := getSession()\n\tdefer session.Close()\n\n\tconnect := session.DB(\"people\").C(\"Peoples\")\n\n\terr := connect.Insert(&Person{name, age, phone})\n\n\t// TODO: Do you really think a panic is appropriate here, if am running this\n\t// on production server, my whole app will die because on db query failed,\n\t// those that make sense to you? O_O\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"New person(s) added..\")\n}", "func addPerson(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tvar person models.Person\r\n\t_ = json.NewDecoder(r.Body).Decode(&person)\r\n\tperson.UUID = primitive.NewObjectID()\r\n\r\n\tcollection := models.ConnectDB()\r\n\tnewPerson, err := collection.InsertOne(context.TODO(), person)\r\n\tif err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\tjson.NewEncoder(w).Encode(newPerson.InsertedID.(primitive.ObjectID))\r\n}", "func (s *SwapService) AddPerson(person string) error {\n\t_, err := s.db.Exec(insertPeopleQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *MockUserRepository) Add(nationality string, birth int, gender string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", nationality, birth, gender)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestAdd(t *testing.T) {\n\tfmt.Println(Add(1,2))\n}", "func TestAdd(t *testing.T) {\n\t_plague := New()\n\t_plague.Add(Item{})\n\tif len(_plague.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func TestAdd(t *testing.T) {\n\n\tresult := Add(1, 2)\n\tif result != 3 {\n\t\tt.Error(\"Existing 1 + 2 to equal 3\")\n\t}\n}", "func TestAdd(t *testing.T) {\n\t_ph := New()\n\t_ph.Add(Item{})\n\tif len(_ph.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func TestAddUser(t *testing.T) {\n\taddUserWithArgs(t, []string{\n\t\t\"--user\", \"someuser\",\n\t})\n}", "func TestStore(t *testing.T) {\r\n\tsetup()\r\n\tp := Person{\r\n\t\tFirstname: firstname,\r\n\t\tLastname: lastname,\r\n\t}\r\n\tresult, err := p.Store(client)\r\n\t_id = result.InsertedID.(primitive.ObjectID)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tif p.Firstname != firstname {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n\tt.Log(\"Person was successfully stored : \"+p.Firstname+\" \"+p.Lastname+\" inserted id: \", _id)\r\n\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed store test %s\", err)\r\n\t}\r\n\r\n}", "func (r *InMemoryPersonRepository) AddPerson(p domain.Person) error {\n\t_, ok := r.personList[p.GetName()]\n\tif ok {\n\t\treturn fmt.Errorf(\"Cannot add person '%s', it already exists\", p.GetName())\n\t}\n\n\tr.personList[p.GetName()] = p\n\treturn nil\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) error {\n\tperson := Person{ID: strconv.Itoa(len(people) + 1)}\n\n\tif err := json.NewDecoder(r.Body).Decode(&person); err != nil {\n\t\treturn err\n\t}\n\tdefer r.Body.Close()\n\n\tpeople = append(people, &person)\n\n\treturn writeJSON(w, http.StatusOK, \"success\")\n}", "func HandleAddPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Body Read Error : %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar person db.Person\n\terr = json.Unmarshal(reqBody, &person)\n\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Request Body parse error : %v\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\tfmt.Println(\"new person\", person)\n\t_, err = Db.Exec(\"INSERT INTO people(name,city,contactNo,photoUrl) values(?,?,?,?)\", person.Name, person.City, person.ContactNo, person.PhotoUrl)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar newPerson db.Person\n\tres, err := Db.Query(\"SELECT * FROM RD.people order by id Desc limit 1\")\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer res.Close()\n\tfor res.Next() {\n\t\terr = res.Scan(&newPerson.Id, &newPerson.Name, &newPerson.City, &newPerson.ContactNo, &newPerson.PhotoUrl)\n\t\tif err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(newPerson)\n}", "func (g *GaeAccessManager) AddPerson(site, firstName, lastName, email, roles string, password *string, ip string, requestor Session) (string, error) {\n\tif requestor != nil && !requestor.HasRole(\"s1\") {\n\t\treturn \"\", errors.New(\"Permission denied.\")\n\t}\n\n\tfirstName = strings.TrimSpace(firstName)\n\tlastName = strings.TrimSpace(lastName)\n\temail = strings.ToLower(strings.TrimSpace(email))\n\n\tcheck, err := g.GetPersonByEmail(site, email, requestor)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif check != nil {\n\t\treturn \"\", errors.New(\"A user account already exists with this email address.\")\n\t}\n\n\t// Password is hashed, this doesnt make sense\n\t/*\n\t\tif password != nil {\n\t\t\tpasswordCheck := PasswordStrength(*password)\n\t\t\tif len(passwordCheck) > 0 {\n\t\t\t\treturn \"\", errors.New(\"Password is insecure. \" + passwordCheck[0])\n\t\t\t}\n\t}*/\n\n\tsyslog := NewGaeSyslogBundle(site, g.client, g.ctx)\n\tdefer syslog.Put()\n\n\tuuid, err := uuid.NewUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnow := time.Now()\n\tsi := &GaePerson{\n\t\tuuid: uuid.String(),\n\t\tsite: site,\n\t\tfirstName: firstName,\n\t\tlastName: lastName,\n\t\temail: email,\n\t\troles: roles,\n\t\tpassword: password,\n\t\tnameKey: strings.ToLower(firstName + \"|\" + lastName),\n\t\tcreated: &now,\n\t}\n\n\tif requestor == nil {\n\t\trequestor = &GaeSession{\n\t\t\tsite: site,\n\t\t\tpersonUUID: si.uuid,\n\t\t\tfirstName: firstName,\n\t\t\tlastName: lastName,\n\t\t\temail: email,\n\t\t\troles: roles,\n\t\t}\n\t}\n\n\tbulk := &GaeEntityAuditLogCollection{}\n\tbulk.SetEntityUuidPersonUuid(uuid.String(), requestor.PersonUuid(), requestor.DisplayName())\n\n\tif firstName != \"\" {\n\t\tbulk.AddItem(\"FirstName\", \"\", firstName)\n\t}\n\tif lastName != \"\" {\n\t\tbulk.AddItem(\"LastName\", \"\", lastName)\n\t}\n\tif email != \"\" {\n\t\tbulk.AddItem(\"Email\", \"\", email)\n\t}\n\tif roles != \"\" {\n\t\tbulk.AddItem(\"Roles\", \"\", roles)\n\t}\n\tif err = g.AddEntityChangeLog(bulk, requestor); err != nil {\n\t\tg.Error(requestor, `datastore`, \"AddPerson() failed persisting changelog. Error: %v\", err)\n\t\treturn \"\", err\n\t}\n\n\tk := datastore.NameKey(\"Person\", uuid.String(), nil)\n\tk.Namespace = site\n\tif _, err := g.client.Put(g.ctx, k, si); err != nil {\n\t\tsyslog.Add(`datastore`, ip, `error`, ``, fmt.Sprintf(\"AddPerson() Person storage failed. Error: %v\", err))\n\t\treturn \"\", err\n\t}\n\tsyslog.Add(`auth`, ip, `notice`, uuid.String(), fmt.Sprintf(\"New user account created '%s','%s','%s'\", firstName, lastName, email))\n\n\treturn uuid.String(), nil\n}", "func (s *Server) HandleAddPerson(c *gin.Context) {\n\tqueryTeamID := c.Param(\"team-id\")\n\n\tteamID, err := strconv.ParseInt(queryTeamID, 10, 64)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\texists, err := s.teamExists(c.Request.Context(), teamID)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tif !exists {\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"error\": \"Team not found.\"})\n\t\treturn\n\t}\n\n\tbinding := struct {\n\t\tFirstName string `json:\"first_name\" binding:\"required\"`\n\t\tLastName string `json:\"last_name\" binding:\"required\"`\n\t\tEmail string `json:\"email\" binding:\"required\"`\n\t}{}\n\terr = c.BindJSON(&binding)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\targs := db.CreatePersonParams{\n\t\tFirstName: binding.FirstName,\n\t\tLastName: binding.LastName,\n\t\tEmail: binding.Email,\n\t\tTeamID: teamID,\n\t}\n\n\tperson, err := s.peopleService.AddPerson(c.Request.Context(), args)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, gin.H{\"data\": person})\n}", "func TestToManyAdd(t *testing.T) {}", "func TestToManyAdd(t *testing.T) {}", "func TestToManyAdd(t *testing.T) {}", "func createPerson(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tnewID := ps.ByName(\"id\")\n\tvar newPerson person\n\t_ = json.NewDecoder(r.Body).Decode(&newPerson)\n\tnewPerson.ID = string(newID)\n\tpeople = append(people, newPerson)\n\tjson.NewEncoder(w).Encode(people)\n}", "func Test_AddContact(t *testing.T) {\n\t// SETUP:\n\t// A standard Env. defer is used to ensure the env is cleaned up after the test.\n\tenv := test.SetupEnv(t)\n\tdefer env.Close()\n\n\t// TEST: Adding a contact via the API.\n\tcontact, err := env.Client.AddContact(service.AddContactRequest{\n\t\tEmail: \"[email protected]\",\n\t\tName: \"Alice Zulu\",\n\t})\n\n\t// VERIFY: Response contains the contact\n\trequire.NoError(t, err, \"Unable to get contact via API\")\n\trequire.NotEmpty(t, contact, \"Contact not found\")\n\tassert.True(t, contact.Id > 0, \"Contact ID is missing\")\n\tassert.Equal(t, contact.Email, \"[email protected]\")\n\tassert.Equal(t, contact.Name, \"Alice Zulu\")\n\n\t// VERIFY: Contact is added to the database properly.\n\tdbContact := env.ReadContactWithEmail(\"[email protected]\")\n\trequire.NotEmpty(t, dbContact, \"Contact not found\")\n\tassert.Equal(t, dbContact.Email, \"[email protected]\")\n\tassert.Equal(t, dbContact.Name, \"Alice Zulu\")\n}", "func TestAdd(t *testing.T) {\n\tbody, err := json.Marshal(&fakeRequests)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tres, err := http.Post(url+\"add\", contentType, bytes.NewBuffer(body))\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\tt.Fatal(fmt.Errorf(\"Wrong status code = %v\", res.StatusCode))\n\t}\n}", "func CreatePerson(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t// params := mux.Vars(req)\n\tvar person models.Person\n\n\t// The user ID will be generated by the mongodb\n\t// id,_ := strconv.Atoi(params[\"id\"])\n\t// person.ID = id\n\terr := json.NewDecoder(req.Body).Decode(&person)\n\tif err != nil {\n\t\tfmt.Println(\"Oops\", err)\n\t}\n\t\n\tcollection := client.Database(\"thepolyglotdeveloper\").Collection(\"people\")\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\tresult, _ := collection.InsertOne(ctx, person)\n\n\t// we don`t need this since we are dealing with a database\n\t//models.People = append(models.People, person) \n\tjson.NewEncoder(w).Encode(result)\t\n}", "func TestIntCreatePersonAndUpdate(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreatePersonAndUpdate\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t// Create a person in the DB.\n\tp := personModel.MakeInitialisedPerson(0, expectedSurname1, expectedForename1)\n\tperson, err := dao.Create(p)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\t// Update the person in the DB.\n\tperson.SetForename(expectedForename2)\n\tperson.SetSurname(expectedSurname2)\n\trows, err := dao.Update(person)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected 1 row to be updated, actually %d rows\", rows)\n\t}\n\n\t// fetch the updated record back and check it.\n\tpersonfetched, err := dao.FindByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif personfetched.Forename() != expectedForename2 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename2, personfetched.Forename())\n\t}\n\tif person.Surname() != expectedSurname2 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname2, personfetched.Surname())\n\t}\n\n\tclearDown(dao, t)\n}", "func (_m *MockService) AddUser(ctx context.Context, name string) (string, error) {\n\tret := _m.ctrl.Call(_m, \"AddUser\", ctx, name)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewPersonAddOK() *PersonAddOK {\n\treturn &PersonAddOK{}\n}", "func TestAddClinic(t *testing.T) {\n\temail := \"[email protected]\"\n\tpassword := \"112233\"\n\tname := \"a nice place\"\n\taddress1 := \"2323 hesting road, singapore\"\n\n\tjwt := login(t, email, password)\n\taddClinic(t, jwt, name, address1)\n}", "func TestContactAddCreateUser(t *testing.T) {\n\tdb := database.Connect()\n\tu := models.User{\n\t\tEmail: \"[email protected]\",\n\t}\n\tu.Create(db)\n\tut, _ := u.AddToken(db)\n\n\ttype Data struct {\n\t\tName string\n\t\tEmail string\n\t}\n\td := Data{Name: \"test\", Email: \"[email protected]\"}\n\tj, _ := json.Marshal(d)\n\tb := bytes.NewBuffer(j)\n\n\tr, err := http.NewRequest(\"POST\", \"/\", b)\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tr.Header.Add(\"X-Access-Token\", ut.Token)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error\", err)\n\t}\n\n\tw := httptest.NewRecorder()\n\tc := SetupWebContext()\n\tContactAdd(c, w, r)\n\tif w.Code != http.StatusAccepted {\n\t\tt.Errorf(\"%v expected, got %v instead\", http.StatusAccepted, w.Code)\n\t}\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tvar person model.Person\n\t/*\n\t\tTo print the response to string\n\t*/\n\tbodyBytes, _ := ioutil.ReadAll(r.Body)\n\tbodyString := string(bodyBytes)\n\tfmt.Println(bodyString)\n\n\t/*\n\t\tParse JSON object without struct\n\t*/\n\tm := map[string]interface{}{}\n\terr := json.Unmarshal(bodyBytes, &m)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(m)\n\tfmt.Println(m[\"firstname\"])\n\n\tjson.Unmarshal(bodyBytes, &person) // parse JSON to person struct object\n\tfmt.Println(person.Firstname)\n\tpeople = append(people, person)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tjson.NewEncoder(w).Encode(people)\n}", "func TestAdd(t *testing.T) {\n\tfeed := New()\n\tfeed.Add(Item{})\n\n\tif len(feed.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tparams := mux.Vars(r)\n\tvar person Person\n\t_ = json.NewDecoder(r.Body).Decode(&person)\n\tperson.ID = params[\"id\"]\n\tpeople = append(people, person)\n\tjson.NewEncoder(w).Encode(people)\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar personInterface interface{}\n\tif err := json.Unmarshal(body, &personInterface); err != nil {\n\t\tutils.SendJSONResponse(w, 422, \"Not Processing\", nil)\n\t}\n\n\tperson := personInterface.(map[string]interface{})\n\n\tsession := utils.GetMongoSession()\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tupdateInfo, errDB := session.DB(\"test_db\").C(\"persons\").Upsert(\n\t\tbson.M{\"email\": person[\"email\"]},\n\t\tbson.M{\"$set\": person},\n\t)\n\n\tif errDB != nil {\n\t\tpanic(errDB)\n\t}\n\n\tutils.SendJSONResponse(w, 0, \"Success\", updateInfo)\n}", "func createPerson(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"CREATE HIT\")\n\tstmt, err := db.Prepare(\"INSERT INTO Persons(pAge, pName) VALUES (?,?)\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar per Person\n\tjson.Unmarshal(body, &per)\n\tage := per.Age\n\tname := per.Name\n\t_, err = stmt.Exec(age, name)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Fprintf(w, \"New person was created\")\n}", "func CreatePerson(writer http.ResponseWriter, requets *http.Request, ps httprouter.Params) {\n\tvar person Person\n\t_ = json.NewDecoder(requets.Body).Decode(&person)\n\tpeople = append(people, person)\n\tjson.NewEncoder(writer).Encode(people)\n}", "func (m *CarCheckInOutMutation) AddPerson(i int) {\n\tif m.addperson != nil {\n\t\t*m.addperson += i\n\t} else {\n\t\tm.addperson = &i\n\t}\n}", "func TestTableAdd(t *testing.T) {\n\n\t//iterate over test array\n\tfor _, test := range testingArray {\n\n\t\t//call Add and get the result\n\t\tresult := Add(test.x, test.y)\n\n\t\t//compare the result to expected. return error if failed\n\t\tif result != test.expected {\n\t\t\tt.Error(\"Testing failed\")\n\t\t}\n\t}\n\n}", "func (service *AuthRepository) PersonRegister(person *models.Person, auth *models.Auth, client *models.Client) (*models.Client, error) {\n\tuserExist, err := checkUserExistOrNot(auth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif userExist {\n\t\treturn nil, errors.New(\"user with the requested email exist\")\n\t}\n\t//insert auth\n\t_, err = helpers.Mongo().InsertOne(models.AuthCollection, auth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//insert person\n\t_, err = helpers.Mongo().InsertOne(models.PersonCollection, person)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = service.InsertClient(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"[email protected]\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func (idb *InDB) CreatePerson(c *gin.Context) {\n\tvar (\n\t\tperson structs.Person\n\n\t\tresult gin.H\n\t)\n\tfirstName := c.PostForm(\"first_name\")\n\tlastName := c.PostForm(\"last_name\")\n\tphone := c.PostForm(\"phone_number\")\n\timei := c.PostForm(\"imei\")\n\tmodelName := c.PostForm(\"model_name\")\n\tmodelNumber := c.PostForm(\"model_number\")\n\tsoftwareVer := c.PostForm(\"software_ver\")\n\tapiKey := authGenerator(imei)\n\n\tperson.First_Name = firstName\n\tperson.Last_Name = lastName\n\tperson.Phone_Number = phone\n\tperson.Model_Number = modelNumber\n\tperson.Model_Name = modelName\n\tperson.Software_Ver = softwareVer\n\tperson.API = apiKey\n\tperson.Imei = imei\n\n\tidb.DB.Create(&person)\n\n\tresult = gin.H{\n\t\t\"result\": person,\n\t}\n\n\tc.JSON(http.StatusOK, result)\n}", "func (_m *MockService) AddTournament(ctx context.Context, name string, deposit float64) (string, error) {\n\tret := _m.ctrl.Call(_m, \"AddTournament\", ctx, name, deposit)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func insertPerson(persona person) {\n\n\tdb, err := getDB()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t_, err = db.Exec(\"INSERT INTO Personas (Persona, Apellido, Email) VALUES (?, ?, ?)\", persona.Nombre, persona.Apellido, persona.Email)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer db.Close()\n}", "func (p *Person) InsertPerson() (bool, error) {\n\tobject := orm.NewOrm()\n\tstatu, err := object.Insert(p)\n\tif err != nil {\n\t\tlog.Error(statu, err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (a *Person) Add() {\r\n\ta.Account++\r\n}", "func AddPerson(pic_path string ,y *youtu.Youtu,groupIDs []string) {\n\tpic_datas:=getPicData(pic_path)\n\ti:=1\n\tfor _,pic_data:=range pic_datas {\n\t\tpersonName:=pic_data.name\n\t\tpic_names:=pic_data.pics\n\n\t\tpersonID:=\"test\"+strconv.Itoa(i)\n\t\ti++\n\t\tpicPath:=pic_path+\"/\"+personName+\"/\"+pic_names[0]\n\t\tprintln(picPath)\n\t\timage,err:=ioutil.ReadFile(picPath)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"ReadFile() failed: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\ttag:=\"test\"\n\t\trsp, err :=y.NewPerson(personID, personName ,groupIDs, image , tag)\n\t\tif err != nil && rsp.ErrorMsg != \"ERROR_PERSON_EXISTED\" {\n\t\t\tprintln(\"NewPerson failed: \", err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"rsp: %#v\\n\", rsp)\n\t\tn:=0\n\t\tfor _,pics:=range pic_names {\n\t\t\tif n>10 {break} //<=10 pics\n\t\t\tn++\n\t\t\t// fmt.Printf(\"pics: %#v\\n\", pics)\n\t\t\tpicPath=pic_path+\"/\"+personName+\"/\"+pics\n\t\t\tprintln(picPath)\n\t\t\tbimage,err:=ioutil.ReadFile(picPath)\n\t\t\tbimages:=[][]byte{bimage}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"ReadFile() failed: %s\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tafrsp, err := y.AddFace(personID, bimages, tag)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"AddFace() failed: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"rsp: %#v\\n\", afrsp)\n\n\t\t}\n\n\t}\n\n\n}", "func createPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar person Person\n\t_ = json.NewDecoder(r.Body).Decode(&person)\n\tpeople = append(people, person)\n\tjson.NewEncoder(w).Encode(person)\n\n}", "func (m *CarCheckInOutMutation) AddedPerson() (r int, exists bool) {\n\tv := m.addperson\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *MockLDAPClient) Add(arg0 *ldap.AddRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *MockService) AddUserToTournamentList(ctx context.Context, tournamentID string, userID string) error {\n\tret := _m.ctrl.Call(_m, \"AddUserToTournamentList\", ctx, tournamentID, userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestToManyAdd(t *testing.T) {\n\tt.Run(\"PersonToThings\", testPersonToManyAddOpThings)\n\tt.Run(\"ThingToPersons\", testThingToManyAddOpPersons)\n}", "func TestCreate(t *testing.T) {\n\n}", "func AddPeople(w http.ResponseWriter, r *http.Request) {\n\tmyDb, err := db.StartDB(\"mydb.db\")\n\tif err != nil {\n\t\tfmt.Printf(\"Fail in open database: %v\\n\", err)\n\t\treturn\n\t}\n\n\t// Verify token\n\ttoken := r.Header.Get(\"AuthToken\")\n\tif (!myDb.IsLogIn([]byte(token))) {\n\t\tfmt.Printf(\"Unauthorized: %v\\n\", err)\n\t\t// 401: Unauthorized\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Add a people\n\tvars := mux.Vars(r)\n\tpeopleId, err := strconv.Atoi(vars[\"peopleId\"])\n\n\tbody, err := ioutil.ReadAll(r.Body)\n if err != nil {\n\t\tfmt.Printf(\"Read body error: %v\\n\", err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}\n\t\n\tif err := myDb.AddObj(\"people\", []byte(strconv.Itoa(peopleId)),[]byte(body)); err != nil {\n\t\tfmt.Printf(\"Read body error: %v\\n\", err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}\n\t\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n}", "func TestAdd(t *testing.T) {\n\toperand, a, expected := 42, 3, 45\n\tresult := Add(a, operand)\n\tif result != expected {\n\t\tt.Errorf(\"Add result incorrect. Operand: %d, A: %d, Expected: %d, Received: %d\", operand, a, expected, result)\n\t}\n}", "func TestAdd(t *testing.T) {\n\tscheme, err := contrail.SchemeBuilder.Build()\n\tassert.NoError(t, err)\n\tassert.NoError(t, core.SchemeBuilder.AddToScheme(scheme))\n\tassert.NoError(t, apps.SchemeBuilder.AddToScheme(scheme))\n\taddCases := map[string]struct {\n\t\tmanager *mockManager\n\t\treconciler *mockReconciler\n\t}{\n\t\t\"add process suceeds\": {\n\t\t\tmanager: &mockManager{\n\t\t\t\tscheme: scheme,\n\t\t\t},\n\t\t\treconciler: &mockReconciler{},\n\t\t},\n\t}\n\tfor name, addCase := range addCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\terr := add(addCase.manager, addCase.reconciler)\n\t\t\tassert.NoError(t, err)\n\t\t})\n\t}\n}", "func (m *MockUsecases) Add(n string, u interface{}) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", n, u)\n}", "func (p *PeopleService) AddPeople(people model.People) error{\n\tfmt.Println(strconv.Itoa(people.Age))\n\tif people.Age<0 {\n\t\treturn &exception.PeopleError{Msg:\"Un Valid age\"}\n\t}\n\tp.peoplePersistence.AddPeople(people)\n\treturn nil\n}", "func ExampleNewPerson() {\n\tperson := NewPerson(\"bob\")\n\t_ = person\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tperson := r.Context().Value(security.KeyUser{}).(data.Person)\n\n\t//create the user\n\tcreatedPerson := data.DB.Create(&person)\n\terr := createdPerson.Error\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(&person)\n}", "func (s *ObjectsIntegrationSuite) TestTA_PublishAddLookup10_1_Test(cc *C) {\n\tdoPublishAddLookup(1, 10, 10, cc)\n}", "func TestAddApp(t *testing.T) {\n\n\tvar err error\n\n\t// Use the configuration manager to get Algolia's keys to mock the app interactor\n\tconfigInteractor := interfaces.ConfigurationManager{}\n\tconfigInteractor.ConfigurationInteractor = infrastructure.NewViperConfig()\n\n\t// Instanciate the App interactor\n\tappInteractor := usecases.NewAppInteractor(\n\t\tinterfaces.NewAlgoliaRepository(\n\t\t\tconfigInteractor.GetConfigString(\"algolia.applicationID\", \"NOT_SET\"),\n\t\t\tconfigInteractor.GetConfigString(\"algolia.apiKey\", \"NOT_SET\"),\n\t\t\tconfigInteractor.GetConfigString(\"algolia.indexes.apps\", \"NOT_SET\"),\n\t\t),\n\t)\n\n\t// Single addition\n\t// Create a random app\n\ttestApp := domain.NewApp(\n\t\t\"Unit testing app interactor\",\n\t\t\"static.whatthetvshow.com:9000/media/snapshots/c4c3021b168ba93572d402e313f0f884_medium.png\",\n\t\t\"http://whatthetvshow.com/fe/snapshots/2205\",\n\t\t\"Quiz unit tests Benjamin\",\n\t\t223,\n\t)\n\t// Try to persist it\n\tres, err := appInteractor.Create(testApp)\n\n\t// Testing returns\n\tif err != nil {\n\t\t// Error raised during the creation\n\t\tt.Error(\"The app was not properly added : \", err)\n\t\treturn\n\t}\n\tif res == \"\" {\n\t\t// No object created\n\t\tt.Error(\"The app was not properly added : no identifier returned\")\n\t\treturn\n\t}\n\n\t_, _ = appInteractor.Delete(res)\n\n\tt.Log(\"TestAddApp: Test Clear\")\n\treturn\n}", "func TestIntCreatePersonStoreFetchBackAndCheckContents(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreatePersonAndCheckContents\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\tp := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\n\t// Store the person in the DB\n\tperson, err := dao.Create(p)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"created person %s\\n\", person.String())\n\n\tretrievedPerson, err := dao.FindByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"retrieved person %s\\n\", retrievedPerson.String())\n\n\tif retrievedPerson.ID() != person.ID() {\n\t\tt.Errorf(\"expected ID to be %d actually %d\", person.ID(),\n\t\t\tretrievedPerson.ID())\n\t}\n\tif retrievedPerson.Forename() != expectedForename1 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\", expectedForename1,\n\t\t\tretrievedPerson.Forename())\n\t}\n\tif retrievedPerson.Surname() != expectedSurname1 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\", expectedSurname1,\n\t\t\tretrievedPerson.Surname())\n\t}\n\n\t// Delete person and check response\n\tid := person.ID()\n\trows, err := dao.DeleteByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected delete to return 1, actual %d\", rows)\n\t}\n\tlog.Printf(\"deleted person with ID %d\\n\", id)\n\tclearDown(dao, t)\n}", "func (m *MockPersister) AddUser(username, email, password string, isSysAdmin, overwrite bool) error {\n\tret := m.ctrl.Call(m, \"AddUser\", username, email, password, isSysAdmin, overwrite)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (s *ObjectsIntegrationSuite) TestTA_PublishAddLookup10_4_Test(cc *C) {\n\tdoPublishAddLookup(4, 10, 10, cc)\n}", "func TestInsertNewUserService (t *testing.T){\n\terr := PostNewUserService(user_01)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_02)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_03)\n\tassert.Equal(t, 200, err.HTTPStatus)\n\terr = PostNewUserService(user_04)\n\tassert.Equal(t, 200, err.HTTPStatus)\n}", "func (m *MockTenantServiceLBMappingPortDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAddNetwork(t *testing.T) {\n\t// initialize rsrcMgr since we use it for resource allocation\n\trsrcMgr.Init(nil)\n\n\t// Initialize the ctrler\n\tInit()\n\n\t// Create network\n\tnetwork, err := NewNetwork(\"default\")\n\tif err != nil {\n\t\tt.Errorf(\"Error creating network default. Err: %v\", err)\n\t\treturn\n\t}\n\n\tlog.Infof(\"Successfully Created network: %+v\", network)\n\n\t// Create new endpoint\n\tep, err := network.NewEndPoint(\"alta1234.0\")\n\tif err != nil {\n\t\tt.Errorf(\"Error creating network endpoint. Err: %v\", err)\n\t\treturn\n\t}\n\n\tlog.Infof(\"Successfully Created endpoint: %+v\", ep)\n}", "func TestAddPeer(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tg := newTestingGateway(t)\n\tdefer g.Close()\n\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\tg.addPeer(&peer{\n\t\tPeer: modules.Peer{\n\t\t\tNetAddress: \"foo.com:123\",\n\t\t},\n\t\tsess: newClientStream(new(dummyConn), build.Version),\n\t})\n\tif len(g.peers) != 1 {\n\t\tt.Fatal(\"gateway did not add peer\")\n\t}\n}", "func (m *MockTaskDao) AddTask(task *task.OwlTask) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddTask\", task)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTenantServiceRelationDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantServicesPortDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockManager) Add(arg0 ids.ID, arg1 Set) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockTenantServiceDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (db *database) CreatePerson(\n\tctx context.Context,\n\tp app.Person,\n) (int, error) {\n\n\tvar id int\n\terr := db.GetContext(ctx, &id, `\n\t\tINSERT INTO person (\n\t\t\tfirst_name,\n\t\t\tlast_name,\n\t\t\temail,\n\t\t\trole_id,\n\t\t\tpass_hash\n\t\t) VALUES ($1, $2, $3, $4, $5)\n\t\tRETURNING person_id\n\t`, p.FirstName, p.LastName, p.Email, p.Role, p.Password)\n\n\treturn id, errors.Wrap(err, \"failed to insert person\")\n}", "func TestFindAPersonExists(t *testing.T){\n\tt.Parallel()\n\n\tr, _ := http.NewRequest(\"GET\", \"/api/person\", nil)\n\tid := \"60d555b6ba8b0ead3bb0596d\"\n\t//Hack to try to fake gorilla/mux vars\n\tvars := map[string]string{\n\t\t\"id\": id,\n\t}\n\tr = mux.SetURLVars(r, vars)\n\n\trr := httptest.NewRecorder()\n\thandler := http.HandlerFunc(controller.FindAPerson)\n\thandler.ServeHTTP(rr, r)\n\t// check httpStatus\n\tif status := rr.Code; status != http.StatusOK {\n\t\tt.Errorf(\"handler returned wrong status code: got %v want %v\",\n\t\t\tstatus, http.StatusOK)\n\t}\n\tdocId, errCheckId := primitive.ObjectIDFromHex(id)\n\n\tif errCheckId != nil{\n\t\tt.Error(\"handler returned wrong \")\n\t}\n\texpected := model.Person{\n\t\tID: docId,\n\t\tName: \"quang\",\n\t}\n\tresponseData := model.Person{}\n\n\t//parse repsonse body to struct Error\n\tif err := json.NewDecoder(rr.Body).Decode(&responseData); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t//compare expected and reponse data\n\tif expected.ID != responseData.ID || expected.Name != responseData.Name{\n\t\tt.Errorf(\"handler returned unexpected status: got %v want %v\",\n\t\t\tresponseData, expected)\n\t}\n}", "func CreatePerson(c *gin.Context) {\n // Validate input\n var input CreatePersonInput\n if err := c.ShouldBindJSON(&input); err != nil {\n c.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n return\n }\n\n // Create person\n person := models.Person{CreatedBy: input.CreatedBy, FirstName: input.FirstName, LastName: input.LastName, Email: input.Email, Phone: input.Phone, Birthday: input.Birthday, Title: input.Title, Department: input.Department}\n models.DB.Create(&person)\n\n c.JSON(http.StatusOK, gin.H{\"data\": person})\n}", "func (m *MockTenantDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func CreatePerson() *Person {\n\tvar newPerson Person\n\tnewPerson.Name = \"mario\"\n\tnewPerson.Address = \"rome\"\n\tnewPerson.Phone = 349121454\n\treturn &newPerson\n}", "func (m *MockContext) AddTasks(request *persistence.AddTasksRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddTasks\", request)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRegionUserInfoDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockUserRepositoryMockRecorder) Add(nationality, birth, gender interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockUserRepository)(nil).Add), nationality, birth, gender)\n}", "func TestAdd(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Common name is required to add a peer to the cache\n\terr = cache.Add(&peers.PeerInfo{})\n\trequire.EqualError(t, err, \"common name is required for all peers\")\n\n\t// Generate a random key for some of our fixtures.\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\trequire.NoError(t, err)\n\n\t// Test adding peers concurrently; the leonardo peer should be updated with\n\t// consecutive updates to\n\tt.Run(\"addTests\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tinfo *peers.PeerInfo\n\t\t}{\n\t\t\t{\"add-id-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tID: \"19d84515-007a-48cc-9efd-b153a263e77c\",\n\t\t\t}},\n\t\t\t{\"add-registered-directory-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tRegisteredDirectory: \"testdirectory.org\",\n\t\t\t}},\n\t\t\t{\"add-endpoint-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tEndpoint: \"leonardo.trisatest.net:443\",\n\t\t\t}},\n\t\t\t{\"add-signing-key-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tSigningKey: &privateKey.PublicKey,\n\t\t\t}},\n\t\t\t{\"add-new-peer\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"donatello.trisatest.net\",\n\t\t\t\tID: \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\",\n\t\t\t\tRegisteredDirectory: \"testdirectory.org\",\n\t\t\t\tEndpoint: \"donatello.trisatest.net:443\",\n\t\t\t}},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttt := tt\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\trequire.NoError(t, cache.Add(tt.info))\n\t\t\t})\n\t\t}\n\t})\n\n\t// Verify the final state of the cache\n\tleonardo, err := cache.Get(\"leonardo.trisatest.net\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"leonardo.trisatest.net\", leonardo.Info().CommonName)\n\trequire.Equal(t, \"19d84515-007a-48cc-9efd-b153a263e77c\", leonardo.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", leonardo.Info().RegisteredDirectory)\n\trequire.Equal(t, \"leonardo.trisatest.net:443\", leonardo.Info().Endpoint)\n\trequire.Equal(t, &privateKey.PublicKey, leonardo.Info().SigningKey)\n\n\tdonatello, err := cache.Get(\"donatello.trisatest.net\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"donatello.trisatest.net\", donatello.Info().CommonName)\n\trequire.Equal(t, \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\", donatello.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", donatello.Info().RegisteredDirectory)\n\trequire.Equal(t, \"donatello.trisatest.net:443\", donatello.Info().Endpoint)\n}", "func (m *MockIRepository) Add(id aggregates.Id, tag string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", id, tag)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRepository) AddProfile(arg0 *models.AuthUser) (uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddProfile\", arg0)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockService) Add(arg0 interface{}) error {\n\tret := m.ctrl.Call(m, \"Add\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockEndpointsDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockBulkProcessor) Add(arg0 elasticsearch.BulkRequest) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", arg0)\n}", "func (s *ObjectsIntegrationSuite) TestTA_PublishAddLookup10_3_Test(cc *C) {\n\tdoPublishAddLookup(3, 10, 10, cc)\n}", "func TestIntCreateTwoPeopleAndDeleteOneByIDStr(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreateTwoPeopleAndDeleteOneByIDStr\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t// Create two people\n\tp1 := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\tperson1, err := dao.Create(p1)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tp2 := personModel.MakeInitialisedPerson(0, expectedForename2, expectedSurname2)\n\tperson2, err := dao.Create(p2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tvar IDStr = fmt.Sprintf(\"%d\", person1.ID())\n\trows, err := dao.DeleteByIDStr(IDStr)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected one record to be deleted, actually %d\", rows)\n\t}\n\n\t// We should have one record in the DB and it should match person2\n\tpeople, err := dao.FindAll()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif len(people) != 1 {\n\t\tt.Errorf(\"expected one record, actual %d\", len(people))\n\t}\n\n\tfor _, person := range people {\n\t\tif person.ID() != person2.ID() {\n\t\t\tt.Errorf(\"expected id to be %d actually %d\",\n\t\t\t\tperson2.ID(), person.ID())\n\t\t}\n\t\tif person.Forename() != expectedForename2 {\n\t\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\t\texpectedForename2, person.Forename())\n\t\t}\n\t\tif person.Surname() != expectedSurname2 {\n\t\t\tt.Errorf(\"TestCreateTwoPeopleAndDeleteOneByIDStr(): expected surname to be %s actually %s\",\n\t\t\t\texpectedSurname2, person.Surname())\n\t\t}\n\t}\n\n\tclearDown(dao, t)\n}", "func (m *MockRouterTx) Add(method, path string, handler interface{}, options ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{method, path, handler}\n\tfor _, a := range options {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Add\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAdd(t *testing.T) {\n\tnums := []int{2, 7, 11, 15}\n\tt.Log(myTwoSum(nums, 22))\n}", "func (m *MockAppDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockHTTPRuleDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockRegionAPIClassDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantServicePluginRelationDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAdd(t *testing.T) {\n\tConvey(\"Unmarshaling fails.\\n\", t, func() {\n\t\tbadJSON := \"badJSON\"\n\n\t\t// Function under test.\n\t\terr := Add(badJSON)\n\n\t\tSo(err, ShouldNotBeNil)\n\t\tSo(err.Error(), ShouldEqual,\n\t\t\t`error unmarshaling action JSON [badJSON]: invalid character 'b' looking for beginning of value`)\n\t\tSo(len(actions), ShouldEqual, 0)\n\t})\n\n\tConvey(\"Adding one action succeeds.\\n\", t, func() {\n\t\t// Function under test.\n\t\terr := Add(action1)\n\n\t\tSo(err, ShouldBeNil)\n\t\tSo(len(actions), ShouldEqual, 1)\n\t})\n\n\tConvey(\"Adding multiple actions in parallel succeeds.\\n\", t, func() {\n\t\t// Kick off one client.\n\t\tc1 := make(chan error)\n\t\tvar err1 error\n\t\tgo func() {\n\t\t\t// Notify the caller when we're done, no matter how we end up.\n\t\t\tdefer func() {c1 <- err1}()\n\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t// Function under test.\n\t\t\t\terr1 = Add(action2)\n\t\t\t\tif err1 != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Kick off another client.\n\t\tc2 := make(chan error)\n\t\tvar err2 error\n\t\tgo func() {\n\t\t\t// Notify the caller when we're done, no matter how we end up.\n\t\t\tdefer func() {c2 <- err2}()\n\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t// Function under test.\n\t\t\t\terr2 = Add(action3)\n\t\t\t\tif err2 != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Wait for both clients to finish.\n\t\t<- c1\n\t\t<- c2\n\n\t\tSo(err1, ShouldBeNil)\n\t\tSo(err2, ShouldBeNil)\n\t\tSo(len(actions), ShouldEqual, 21) // 1 added in the previous test case.\n\t})\n\n\t// Clean up from these tests.\n\tactions = nil\n}", "func (m *MockApplicationDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func CreatePerson(db *sql.DB) {}", "func (cc *Chaincode) addChargedPerson(stub shim.ChaincodeStubInterface, params []string) sc.Response {\n\t// Check Access\n\tcreatorOrg, creatorCertIssuer, err := getTxCreatorInfo(stub)\n\tif !authenticatePolice(creatorOrg, creatorCertIssuer) {\n\t\treturn shim.Error(\"{\\\"Error\\\":\\\"Access Denied!\\\",\\\"Payload\\\":{\\\"MSP\\\":\\\"\" + creatorOrg + \"\\\",\\\"CA\\\":\\\"\" + creatorCertIssuer + \"\\\"}}\")\n\t}\n\n\t// Check if sufficient Params passed\n\tif len(params) < 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting (2+)!\")\n\t}\n\n\t// Check if Params are non-empty\n\tfor a := 0; a < len(params); a++ {\n\t\tif len(params[a]) <= 0 {\n\t\t\treturn shim.Error(\"Argument must be a non-empty string\")\n\t\t}\n\t}\n\n\t// Copy the Values from params[]\n\tID := params[0]\n\tCitizenID := params[1]\n\tvar SectionOfLaws []string\n\tfor a := 2; a < len(params); a++ {\n\t\tSectionOfLaws = append(SectionOfLaws, params[a])\n\t}\n\n\tNewChargedPerson := chargedPersons{CitizenID, SectionOfLaws}\n\n\t// Check if ChargeSheet exists with Key => ID\n\tchargeSheetAsBytes, err := stub.GetState(ID)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get ChargeSheet Details!\")\n\t} else if chargeSheetAsBytes == nil {\n\t\treturn shim.Error(\"Error: ChargeSheet Does NOT Exist!\")\n\t}\n\n\t// Create Update struct var\n\tchargeSheetToUpdate := chargeSheet{}\n\terr = json.Unmarshal(chargeSheetAsBytes, &chargeSheetToUpdate) //unmarshal it aka JSON.parse()\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t// Check if Judgement is Complete or NOT\n\tif chargeSheetToUpdate.Complete {\n\t\treturn shim.Error(\"Error: ChargeSheet is Complete & Locked!\")\n\t}\n\n\t// Update ChargeSheet.ChargedPersons to append => NewChargedPerson\n\tchargeSheetToUpdate.ChargedPersons = append(chargeSheetToUpdate.ChargedPersons, NewChargedPerson)\n\n\t// Convert to JSON bytes\n\tchargeSheetJSONasBytes, err := json.Marshal(chargeSheetToUpdate)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t// Put State of newly generated ChargeSheet with Key => ID\n\terr = stub.PutState(ID, chargeSheetJSONasBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t// Returned on successful execution of the function\n\treturn shim.Success(chargeSheetJSONasBytes)\n}", "func (m *MockTCPRuleDao) AddModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"AddModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAdditionalObjects(t *testing.T) {\n\tnewIntegrationTest(\"additionalobjects.example.com\", \"additionalobjects\").\n\t\twithAddons(dnsControllerAddon, awsEBSCSIAddon, leaderElectionAddon).\n\t\trunTestTerraformAWS(t)\n}" ]
[ "0.67847574", "0.6713656", "0.6553853", "0.6529472", "0.6448036", "0.6440355", "0.63886786", "0.6289509", "0.6272711", "0.62223697", "0.6211273", "0.62010425", "0.6156485", "0.61512357", "0.61320937", "0.60857344", "0.6051155", "0.60508364", "0.60508364", "0.60508364", "0.6009794", "0.59894246", "0.59517187", "0.5924164", "0.5912675", "0.59010166", "0.5894157", "0.5893929", "0.5861799", "0.5859247", "0.5854939", "0.5840385", "0.58197546", "0.580936", "0.5800814", "0.5797706", "0.5793665", "0.57855225", "0.57836974", "0.5771837", "0.57329166", "0.57186306", "0.5717472", "0.5713295", "0.57035494", "0.57024246", "0.57023245", "0.56678617", "0.5657942", "0.5649818", "0.5633881", "0.560728", "0.55940723", "0.5590933", "0.55788344", "0.55600435", "0.5559286", "0.5547673", "0.5543235", "0.55410874", "0.5535304", "0.5524476", "0.5508319", "0.545608", "0.54457325", "0.543717", "0.5433508", "0.54187566", "0.54160184", "0.54099303", "0.5404839", "0.53863615", "0.53789663", "0.5375255", "0.5343441", "0.5339987", "0.5318035", "0.5313786", "0.5311023", "0.5305837", "0.529419", "0.5285688", "0.528304", "0.52790666", "0.52789974", "0.5275851", "0.52745163", "0.52711844", "0.5271103", "0.5269999", "0.5257266", "0.5249008", "0.52473503", "0.5244412", "0.52440745", "0.52412283", "0.5236105", "0.5232967", "0.52308685", "0.522955" ]
0.7523569
0
TestCreateRoom tests the functionality of CreateRoom
func TestCreateRoom(t *testing.T) { var ( err error room Room createRoom = func(name, roomType string) { room, err = CreateRoom(con, name, roomType) } ) Convey("Tests for CreateRoom ", t, func() { Convey("CreateRoom should return Room with all the correct values present and an error", func() { createRoom("Valhalla", "office") So(err, ShouldBeNil) So(room.Capacity, ShouldEqual, 6) So(room.ID, ShouldNotBeBlank) So(room.Name, ShouldNotBeBlank) So(room.Occupants, ShouldBeEmpty) So(room.Type, ShouldNotBeBlank) }) Convey("Print the successfully created Room and User", func() { createRoom("Golang", "livingspace") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestGetRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = GetRoom(con, rmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoom \", t, func() {\n\t\tConvey(\"GetRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Joshua\", \"Mwaniki\", \"staff\", \"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Valhalla\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Joshua\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Mwaniki\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"staff\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"James\", \"Kaberia\", \"staff\", \"Pretoria\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestAddRoom(t *testing.T) {\n\t// first create a new controller\n\tapi := NewRoomApiController()\n\troomrouter := NewRouter(api)\n\ttestserver := httptest.NewServer(roomrouter)\n\tdefer testserver.Close()\n\n\t// api configuration\n\tapiConfig := roomapi.NewConfiguration()\n\tapiConfig.HTTPClient = testserver.Client()\n\ttesturl, err := url.Parse(testserver.URL)\n\tif err != nil {\n\t\tt.Errorf(\"error parsing url from test server: %s\", err)\n\t\treturn\n\t}\n\tapiConfig.Host = testurl.Host\n\n\t// create first client\n\tapic := roomapi.NewAPIClient(apiConfig)\n\tbackground := context.Background()\n\tretRoom, _, err := apic.RoomApi.AddRoom(background)\n\tif err != nil {\n\t\tt.Errorf(\"error adding room: %s\", err)\n\t\treturn\n\t}\n\tt.Logf(\"room id: %d, room id str: %s\\n\", retRoom.Id, retRoom.Code)\n}", "func roomToTestRoom(room *level.RoomData, inputLevel level.Level) Room {\n\treturn Room{\n\t\tType: \"room\",\n\t\tOrigin: Point{\n\t\t\troom.TopLeft.Row,\n\t\t\troom.TopLeft.Col,\n\t\t},\n\t\tBounds: Bounds{\n\t\t\tRows: room.Size.Row,\n\t\t\tColumns: room.Size.Col,\n\t\t},\n\t\tLayout: TilesToArray(inputLevel.GetTiles(room.TopLeft, room.Size)),\n\t}\n}", "func CreateRoom(w http.ResponseWriter, request *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tswitch request.Method {\n\tcase \"POST\":\n\t\tdata := request.URL.Query()\n\t\tif !createRoomValidator(w, data) {\n\t\t\treturn\n\t\t}\n\t\tvar room roomJSON\n\t\tmaxUsers, _ := strconv.Atoi(data[\"users\"][0])\n\t\ti := 0\n\t\tfor {\n\t\t\ti++\n\t\t\troomID := rand.Intn(99) + 1\n\t\t\tif ok, _ := getRoomByID(roomID, &Rooms); !ok {\n\t\t\t\troom.ID = roomID\n\t\t\t\troom.MaxUsers = maxUsers\n\t\t\t\troom.State = \"joining\"\n\t\t\t\troom.Daytime = \"day\"\n\t\t\t\troom.Mafia = make([]int, 0)\n\t\t\t\troom.Peaceful = make([]int, 0)\n\t\t\t\troom.Alive = make([]int, 0)\n\t\t\t\troom.Killed = make([]int, 0)\n\t\t\t\troom.Jailed = make([]int, 0)\n\t\t\t\tRooms = append(Rooms, room)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i >= 100 {\n\t\t\t\thttp.Error(w, \"503 Game is not available\", http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tresp, err := json.Marshal(&room)\n\t\tif err == nil {\n\t\t\tw.Write(resp)\n\t\t}\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(405)\n\t\tfmt.Fprintf(w, \"Only POST method is allowed\")\n\t}\n}", "func createRoom(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.CreateRoom(con, args.Get(0), args.Get(1))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func (lobby *Lobby) createRoom(rs *models.RoomSettings) (room *Room, err error) {\n\n\tid := utils.RandomString(16) // вынести в кофиг\n\troom, err = NewRoom(lobby.config().Field, lobby,\n\t\t&models.Game{Settings: rs}, id)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = lobby.addRoom(room); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func TestGetRoomDetails(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tusers []models.User\n\t\trm models.Room\n\t\troom Room\n\n\t\tgetRoomDetails = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\t_, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\trm, users, err = getRoomDetails(con, rmName, rmType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for getRoomDetails \", t, func() {\n\t\tConvey(\"getRoomDetaiils should return the room, a slice of user and an error \", func() {\n\t\t\tgetRoomDetails(\"Daniel\", \"Ikigai\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(rm.Capacity, ShouldEqual, 6)\n\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\tSo(rm.Name, ShouldEqual, \"Tsavoo\")\n\t\t\tSo(rm.Type, ShouldEqual, \"office\")\n\n\t\t\tSo(users[0].FirstName, ShouldEqual, \"Daniel\")\n\t\t\tSo(users[0].ID, ShouldNotBeBlank)\n\t\t\tSo(users[0].LastName, ShouldEqual, \"Ikigai\")\n\t\t\tSo(users[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tgetRoomDetails(\"Christine\", \"J\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func NewTestRoom(name string) *Room {\n\treturn NewRoom(nil, name, name, \"\")\n}", "func createRoom(gm *gomatrix.Client, roomAliasName string) (roomID string, err error) {\n req := &gomatrix.ReqCreateRoom{\n RoomAliasName: roomAliasName,\n Preset: \"public_chat\",\n }\n\n // Create the room\n resp, err := gm.CreateRoom(req)\n if err != nil {\n return\n }\n\n roomID = resp.RoomID\n return\n}", "func (g *Game) CreateRoom(room_name string) {\n\tif in_room {\n\t\tfmt.Println(\"Already in a room\")\n\t} else {\n\t\tgame_color = 1\n\t\tgame_team = 1\n\t\tmessenger.Msnger.Send_game_server(fmt.Sprintf(\"%v:%v:%v\", room_name, my_name, messenger.Msnger.Address), mylib.CREATE_ROOM)\n\t\tmsg := messenger.Msnger.Receive_game_server()\n\t\tif msg.Type == mylib.ACK {\n\t\t\tfmt.Printf(\"Creating room: %v\\n\", room_name)\n\t\t\trooms[room_name] = fmt.Sprintf(\"%v:%v\", my_name, messenger.Msnger.Address)\n\t\t\tmessenger.Msnger.Send_message(fmt.Sprintf(\"%v:%v:%v\", room_name, my_name, messenger.Msnger.Address), mylib.CREATE_ROOM)\n\t\t\tin_room = true\n\t\t\tmy_room = room_name\n\t\t} else {\n\t\t\tfmt.Println(\"Error: Room name already taken\")\n\t\t}\n\t}\n}", "func (s *Server) createRoom(c *client.Client, args []string) {\n\t// validate arg input\n\tif len(args) < 2 {\n\t\tc.Msg(\"please use /createRoom <text>\")\n\t\treturn\n\t}\n\t// check for existing room\n\t_, ok := s.rooms[args[1]]\n\tif !ok {\n\t\ts.rooms[args[1]] = &client.Room{\n\t\t\tName: args[1],\n\t\t\tMembers: make(map[net.Addr]*client.Client),\n\t\t}\n\t} else {\n\t\tc.Msg(fmt.Sprintf(\"%s already exists. Try /join %s to jump in!\", args[1], args[1]))\n\t}\n\n}", "func (v *Room) Create(tx *db.Tx, vdb *db.Room, payload model.CreateRoomRequest) (err error) {\n\tif pdebug.Enabled {\n\t\tg := pdebug.Marker(\"service.Room.Create\").BindError(&err)\n\t\tdefer g.End()\n\t}\n\n\tif err := v.populateRowForCreate(vdb, payload); err != nil {\n\t\treturn err\n\t}\n\n\tif err := vdb.Create(tx); err != nil {\n\t\treturn err\n\t}\n\n\tif err := payload.L10N.CreateLocalizedStrings(tx, \"Room\", vdb.EID); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CreateRoom(name string) error {\n\ttx := DB.Create(&Room{Name: name})\n\treturn tx.Error\n}", "func TestGetRoomAllocations(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\t\trooms []Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\trooms, err = GetRoomAllocations(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoomAllocations \", t, func() {\n\t\tConvey(\"GetRoomAllocations should return a slice of Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Garbrielle\", \"Wanjigi\", \"fellow\", \"Timbuktu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, room = range rooms {\n\n\t\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Name, ShouldEqual, \"Timbuktu\")\n\t\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Garbrielle\")\n\t\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Wanjigi\")\n\t\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"Ashley\", \"Wanjigi\", \"fellow\", \"Golang\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (a *API) Create(ctx context.Context, param *protos.NewRoomParam) (*protos.Room, error) {\n\t// check if user presents\n\troom := &RoomModel{}\n\terr := a.DB.Where(&RoomModel{ID: param.Id}).\n\t\tFirst(room).Error\n\tif err != nil {\n\t\tif err != gorm.ErrRecordNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(room.ID) > 0 {\n\t\treturn nil, fmt.Errorf(RoomAlreadyExistError)\n\t}\n\t// get all users\n\tusers := []*UserModel{}\n\terr = a.DB.Where(\"id IN (?)\", param.UserIDs).\n\t\tFind(&users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// save room instance\n\troom = &RoomModel{\n\t\tID: param.Id,\n\t\tName: param.Name,\n\t\tPhoto: param.Photo,\n\t\tDescription: param.Description,\n\t}\n\terr = a.DB.Create(room).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// add member to it\n\terr = a.DB.Model(room).\n\t\tAssociation(\"Members\").\n\t\tAppend(users).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// publish new room created events\n\tpayload, err := a.GetRoomInstancePayload(room)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.Events <- &RoomEvent{\n\t\tTime: time.Now(),\n\t\tEvent: RoomCreated,\n\t\tPayload: payload,\n\t}\n\treturn RoomModelToProto(room), nil\n}", "func FakeRoom() *RoomModel {\n\treturn &RoomModel{\n\t\tID: faker.RandomString(5),\n\t\tName: faker.Commerce().ProductName(),\n\t\tPhoto: faker.Avatar().String(),\n\t\tDescription: faker.Lorem().Sentence(5),\n\t}\n}", "func (c *Client) CreateRoom(ctx context.Context, req *CreateRoomRequest) (*CreateRoomResponse, error) {\n\tresp := &CreateRoomResponse{}\n\treturn resp, c.request(ctx, \"POST\", \"rooms\", req, resp)\n}", "func (m *MockIRoomService) SCreateRoom(arg0 models.RoomModel) (models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SCreateRoom\", arg0)\n\tret0, _ := ret[0].(models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *RoomService) Create(ctx context.Context, data url.Values) (*Room, error) {\n\troom := new(Room)\n\terr := r.client.CreateResource(ctx, roomPathPart, data, room)\n\treturn room, err\n}", "func CreateRoom(info chan<- ServerMessage) {\n\tstatus := \"\"\n\n\tconn, err := net.Dial(connType, host+\":\"+port)\n\tif err != nil {\n\t\tinfo <- ServerMessage{nil, false, \"\", \"error when connecting\"}\n\t\treturn\n\t}\n\tfmt.Fprintf(conn, \"wait\\n\")\n\tvar token string\n\tfmt.Fscan(conn, &token)\n\tinfo <- ServerMessage{conn, false, token, \"\"}\n\n\tvar msg string\n\tfmt.Fscan(conn, &msg)\n\tvar isSecond bool\n\tif msg == \"second\" {\n\t\tisSecond = true\n\t} else if msg == \"first\" {\n\t\tisSecond = false\n\t}\n\n\tinfo <- ServerMessage{conn, isSecond, \"\", status}\n}", "func NewRoom(name string, u user.Service, logger logger.Service, server *Server) *Room {\n\tlogger.Info(\"cmp\", \"Room\", \"method\", \"NewRoom\", \"msg\", fmt.Sprintf(\"new Room %s Created\", name))\n\t// clientService := client.NewService()\n\treturn &Room{\n\t\tName: name,\n\t\tuserService: u,\n\t\tAddClientChan: make(chan *websocket.Conn, 100),\n\t\tEventDespatcher: NewEventDispatcher(),\n\t\tClients: make(map[string]*Client),\n\t\tlogger: logger,\n\t\tserver: server,\n\t}\n}", "func TestAddPerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser, testUser User\n\n\t\taddPerson = func(fname, lname, jobType, officeName, livingspaceName string) {\n\t\t\tif livingspaceName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, livingspaceName, \"livingspace\")\n\t\t\t}\n\n\t\t\tif officeName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, officeName, \"office\")\n\t\t\t}\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, jobType, officeName, livingspaceName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for AddPerson\", t, func() {\n\t\tConvey(\"AddPerson should return a User with all correct values present and an error\", func() {\n\t\t\tvar runValuesTests = func(rm models.Room) {\n\t\t\t\tSo(rm.Capacity, ShouldNotEqual, 0)\n\t\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Name, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Type, ShouldNotBeBlank)\n\t\t\t}\n\n\t\t\taddPerson(\"Jade\", \"Flora\", \"fellow\", \"Narnia\", \"PHP\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user.FirstName, ShouldNotBeBlank)\n\t\t\tSo(user.ID, ShouldNotBeBlank)\n\t\t\tSo(user.LastName, ShouldNotBeBlank)\n\t\t\tSo(user.Type, ShouldNotBeBlank)\n\t\t\tSo(user.User, ShouldNotResemble, testUser.User)\n\n\t\t\trunValuesTests(user.LivingSpace)\n\t\t\trunValuesTests(user.Office)\n\t\t})\n\n\t\tConvey(\"Print the successfully created User and Room \", func() {\n\t\t\taddPerson(\"Jackson\", \"Davids\", \"fellow\", \"\", \"Mogadishu\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func AddRoom(c echo.Context) error {\n\treq := new(addRoomReq)\n\tif err := c.Bind(req); err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRAR001\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusBadRequest, ErrorResponse{\n\t\t\tCode: \"CSRAR001\",\n\t\t\tMessage: \"Wrong parameters\",\n\t\t})\n\t}\n\n\tif err := utils.MissingFields(c, reflect.ValueOf(req).Elem(), []string{\"Name\"}); err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRAR002\"}).Warnf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusBadRequest, ErrorResponse{\n\t\t\tCode: \"CSRAR002\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tuser := c.Get(\"user\").(User)\n\n\trow, err := DB.Query(\"INSERT INTO rooms (id, name, home_id, creator_id) VALUES (generate_ulid(), $1, $2, $3) RETURNING id;\", req.Name, c.Param(\"homeId\"), user.ID)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRAR003\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusBadRequest, ErrorResponse{\n\t\t\tCode: \"CSRAR003\",\n\t\t\tMessage: \"Room can't be created\",\n\t\t})\n\t}\n\tvar roomID string\n\trow.Next()\n\terr = row.Scan(&roomID)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRAR004\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusBadRequest, ErrorResponse{\n\t\t\tCode: \"CSRAR004\",\n\t\t\tMessage: \"Room can't be created\",\n\t\t})\n\t}\n\n\tnewPermission := Permission{\n\t\tUserID: user.ID,\n\t\tType: \"room\",\n\t\tTypeID: roomID,\n\t\tRead: true,\n\t\tWrite: true,\n\t\tManage: true,\n\t\tAdmin: true,\n\t}\n\t_, err = DB.NamedExec(\"INSERT INTO permissions (id, user_id, type, type_id, read, write, manage, admin) VALUES (generate_ulid(), :user_id, :type, :type_id, :read, :write, :manage, :admin)\", newPermission)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRAR005\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRAR005\",\n\t\t\tMessage: \"Room can't be created\",\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusCreated, MessageResponse{\n\t\tMessage: roomID,\n\t})\n}", "func (bpdb *BitpartmentDB) CreateRoomsTable() error {\n\treturn bpdb.createSomeTable(&Room{}, \"ROOM\")\n}", "func newRoom(id string, name string) *Room {\n\tr := &Room{\n\t\tid: id,\n\t\tname: name,\n\t\tmembers: make(map[string]*Member),\n\t}\n\treturn r\n}", "func TestCreate(t *testing.T) {\n\n}", "func CreateRoom(name string) *Room {\n\troom := &Room{\n\t\tname: name,\n\t\tMsgch: make(chan string),\n\t\tRWMutex: new(sync.RWMutex),\n\t\tclients: make(map[string]chan<- string),\n\t\tQuit: make(chan struct{}),\n\t}\n\troom.Run()\n\treturn room\n}", "func NewRoom(t *testing.T, creator *User, modifiers ...roomModifier) *Room {\n\tt.Helper()\n\tcounter := atomic.AddInt64(&roomIDCounter, 1)\n\n\t// set defaults then let roomModifiers override\n\tr := &Room{\n\t\tID: fmt.Sprintf(\"!%d:localhost\", counter),\n\t\tcreator: creator,\n\t\tauthEvents: gomatrixserverlib.NewAuthEvents(nil),\n\t\tpreset: PresetPublicChat,\n\t\tVersion: gomatrixserverlib.RoomVersionV9,\n\t}\n\tfor _, m := range modifiers {\n\t\tm(t, r)\n\t}\n\tr.insertCreateEvents(t)\n\treturn r\n}", "func createRoom(name string) *chatRoom {\n\t// Initialize chat room struct\n\tc := &chatRoom{\n\t\tname: name,\n\t\tmessages: make(chan string),\n\t\tmembers: make(map[string]*client, 0),\n\t\thistory: []string{},\n\t}\n\tlog.Printf(\"creating room %v\", c.name)\n\n\t//spin off new routine to listen for messages\n\tgo func(c *chatRoom) {\n\t\tfor {\n\t\t\tout := <-c.messages\n\t\t\tfor _, v := range c.members {\n\t\t\t\tv.Message <- out\n\t\t\t\tlog.Printf(\"createroom: broadcasting msg in room: %v to member: %v\", c.name, v.Name)\n\t\t\t}\n\t\t}\n\t}(c)\n\n\treturn c\n}", "func NewRoom() *room {\n\treturn &room{}\n}", "func (aec *AddEntryCmd) RequiresRoom() {}", "func (l *Leaf) CreateRooms() {\n\tif l.Left != nil || l.Right != nil {\n\t\t// if split, go into children leafs\n\t\tif l.Left != nil {\n\t\t\tl.Left.CreateRooms()\n\t\t}\n\t\tif l.Right != nil {\n\t\t\tl.Right.CreateRooms()\n\t\t}\n\t\tif l.Left != nil && l.Right != nil {\n\t\t\tl.CreateHall(l.Left.GetRoom(), l.Right.GetRoom())\n\t\t}\n\t} else {\n\t\t// ready to make a room\n\t\tx := l.Bounds.Min.X\n\t\ty := l.Bounds.Min.Y\n\t\twidth := l.Bounds.Dx()\n\t\theight := l.Bounds.Dy()\n\t\troomSize := image.Pt(randNum(3, width-2), randNum(3, height-2))\n\n\t\t// place the room within the Leaf, but don't put it right\n\t\t// against the side of the Leaf (that would merge rooms together)\n\t\troomPos := image.Pt(randNum(1, width-roomSize.X-1), randNum(1, height-roomSize.Y-1))\n\n\t\tx0 := x + roomPos.X\n\t\ty0 := y + roomPos.Y\n\t\tx1 := x0 + roomSize.X\n\t\ty1 := y0 + roomSize.Y\n\t\tl.Room = image.Rect(x0, y0, x1, y1)\n\t}\n}", "func (c *Mock) Room() interfaces.Room {\n\treturn c.FakeRoom()\n}", "func CreateTestGame() (game models.Game) {\n\tplayerTeam1 := CreateTestPlayer()\n\tplayerTeam2 := CreateTestPlayer()\n\n\tgame = models.Game{HomeTeam: playerTeam1.Team, AwayTeam: playerTeam2.Team}\n\tgame.Create()\n\n\treturn game\n}", "func CreateRoom() *Room {\n\n\t// increment the room identifier\n\tatomic.AddInt64(&lastRoomID, 1)\n\troomID := atomic.LoadInt64(&lastRoomID)\n\n\tnewRoom := &Room{\n\t\tID: roomID,\n\t\t// CurrGame: game,\n\t\tcheckin: make(chan *Client),\n\t\tcheckout: make(chan *Client),\n\t\tpublish: make(chan interface{}),\n\t\tclients: make(map[*Client]bool),\n\t}\n\n\t// add room to the list of active rooms\n\thotel[newRoom.ID] = newRoom\n\n\tgame := &Game{\n\t\tRoom: newRoom,\n\t\tBroadcast: newRoom.publish,\n\t}\n\n\tnewRoom.CurrGame = game\n\n\t// start the room in a routine\n\tgo newRoom.run()\n\n\treturn newRoom\n}", "func NewRoom(name string, private bool) *Room {\n\treturn &Room{\n\t\tID: uuid.New(),\n\t\tName: name,\n\t\tclients: make(map[*Client]bool),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tbroadcast: make(chan *Message),\n\t\tPrivate: private,\n\t}\n}", "func NewRoom() *Room {\n\treturn &Room{\n\t\tgroup: pitaya.NewGroup(\"room\"),\n\t\tstats: &stats{},\n\t}\n}", "func createRoomWithData(id string, roomType RoomType, data map[string]interface{}) {\n\tdat, err := ioutil.ReadFile(\"config/rooms/\" + string(roomType) + \".json\")\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar roomData map[string]interface{}\n\tjson.Unmarshal(dat, &roomData)\n\tdata[\"background\"] = roomData[\"background\"]\n\n\tif val, ok := roomData[\"corners\"]; ok {\n\t\tdata[\"corners\"] = val\n\t}\n\n\tif sponsorID, ok := data[\"id\"].(string); ok {\n\t\tdata[\"background\"] = strings.ReplaceAll(data[\"background\"].(string), \"<id>\", sponsorID)\n\n\t\tif val, ok := roomData[\"sponsor\"].(bool); ok && val {\n\t\t\tdata[\"sponsorId\"] = sponsorID\n\t\t}\n\t}\n\n\tinstance.HSet(\"room:\"+id, data)\n\n\telements := roomData[\"elements\"].([]interface{})\n\n\t// If this is the nightclub, add floor tiles\n\tif id == \"nightclub\" {\n\t\ttileStartX := 0.374\n\t\ttileStartY := 0.552\n\t\ttileSeparator := 0.0305\n\t\tnumTilesX := 7\n\t\tnumTilesY := 4\n\n\t\tnewTiles := make([]interface{}, numTilesX*numTilesY)\n\n\t\tfor i := 0; i < numTilesY; i++ {\n\t\t\tfor j := 0; j < numTilesX; j++ {\n\t\t\t\tnewTiles[i*numTilesX+j] = map[string]interface{}{\n\t\t\t\t\t\"x\": tileStartX + float64(i+j)*tileSeparator,\n\t\t\t\t\t\"y\": tileStartY + float64((numTilesY-i)+j)*tileSeparator,\n\t\t\t\t\t\"tile\": true,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\telements = append(newTiles, elements...)\n\t}\n\n\tfor _, val := range elements {\n\t\telementID := uuid.New().String()\n\t\telementData := val.(map[string]interface{})\n\n\t\tif _, ok := elementData[\"tile\"]; ok {\n\t\t\t// If this is a nightclub floor tile, autofill some attributes\n\t\t\tdelete(elementData, \"tile\")\n\t\t\telementData[\"width\"] = 0.052\n\t\t\telementData[\"path\"] = \"tiles/blue1.svg\"\n\t\t\telementData[\"changingImagePath\"] = true\n\t\t\telementData[\"changingPaths\"] = \"tiles/blue1.svg,tiles/blue2.svg,tiles/blue3.svg,tiles/blue4.svg,tiles/green1.svg,tiles/green2.svg,tiles/pink1.svg,tiles/pink2.svg,tiles/pink3.svg,tiles/pink4.svg,tiles/yellow1.svg\"\n\t\t\telementData[\"changingInterval\"] = 2000\n\t\t\telementData[\"changingRandomly\"] = true\n\t\t}\n\n\t\tif _, ok := elementData[\"campfire\"]; ok {\n\t\t\t// If this is a campfire, animate it\n\t\t\tdelete(elementData, \"campfire\")\n\t\t\telementData[\"width\"] = 0.0253\n\t\t\telementData[\"path\"] = \"campfire/campfire1.svg\"\n\t\t\telementData[\"changingImagePath\"] = true\n\t\t\telementData[\"changingPaths\"] = \"campfire/campfire1.svg,campfire/campfire2.svg,campfire/campfire3.svg,campfire/campfire4.svg,campfire/campfire5.svg\"\n\t\t\telementData[\"changingInterval\"] = 250\n\t\t\telementData[\"changingRandomly\"] = false\n\t\t}\n\n\t\tif _, ok := elementData[\"fountain\"]; ok {\n\t\t\t// If this is a fountain, animate it\n\t\t\tdelete(elementData, \"fountain\")\n\t\t\telementData[\"path\"] = \"fountain1.svg\"\n\t\t\telementData[\"changingImagePath\"] = true\n\t\t\telementData[\"changingPaths\"] = \"fountain1.svg,fountain2.svg,fountain3.svg\"\n\t\t\telementData[\"changingInterval\"] = 1000\n\t\t\telementData[\"changingRandomly\"] = false\n\t\t}\n\n\t\tif _, ok := elementData[\"toggleable\"]; ok {\n\t\t\tswitch elementData[\"path\"] {\n\t\t\tcase \"street_lamp.svg\":\n\t\t\t\telementData[\"path\"] = \"street_lamp.svg,street_lamp_off.svg\"\n\t\t\tcase \"bar_closed.svg\":\n\t\t\t\telementData[\"path\"] = \"bar_closed.svg,bar_open.svg\"\n\t\t\tcase \"flashlight_off.svg\":\n\t\t\t\telementData[\"path\"] = \"flashlight_off.svg,flashlight_on.svg\"\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\telementData[\"state\"] = 0\n\t\t}\n\n\t\tif id, ok := data[\"id\"].(string); ok {\n\t\t\telementData[\"path\"] = strings.ReplaceAll(elementData[\"path\"].(string), \"<id>\", id)\n\t\t}\n\n\t\tinstance.HSet(\"element:\"+elementID, elementData)\n\t\tinstance.RPush(\"room:\"+id+\":elements\", elementID)\n\t}\n\n\tfor _, val := range roomData[\"hallways\"].([]interface{}) {\n\t\thallwayData := val.(map[string]interface{})\n\n\t\tif roomType == Bronze || roomType == Silver || roomType == Gold || roomType == Plat {\n\t\t\thallwayData[\"toX\"] = data[\"toX\"].(float64)\n\t\t\thallwayData[\"toY\"] = data[\"toY\"].(float64)\n\n\t\t\tif val, ok := data[\"to\"].(string); ok {\n\t\t\t\thallwayData[\"to\"] = val\n\t\t\t}\n\t\t}\n\n\t\thallwayID := uuid.New().String()\n\t\tinstance.HSet(\"hallway:\"+hallwayID, val)\n\t\tinstance.SAdd(\"room:\"+id+\":hallways\", hallwayID)\n\t}\n\n\tinstance.SAdd(\"rooms\", id)\n}", "func TestNewBooking(t *testing.T) {\n\ttestRouter := SetupRouter()\n\tvar jsonStr = []byte(`{\"userid\":1,\"pickuplat\":11.0797,\"pickuplong\":76.9997,\"destinationlat\":11.0797,\"destinationlong\":76.9997\n\t}`)\n\treq, err := http.NewRequest(\"POST\", \"/newBooking\", bytes.NewBuffer(jsonStr))\n\treq.SetBasicAuth(\"admin\", \"admin123\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\ttestRouter.ServeHTTP(resp, req)\n\tassert.Equal(t, resp.Code, 200)\n}", "func (c *client) create() {\n\troomName, err := readInput(c.Conn, \"Please enter room name: \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Cannot make a room that already exists.\n\tif _, ok := roomList[roomName];ok {\n\t\twriteFormattedMsg(c.Conn,\"A room already exists with that name, try again later\")\n\t} else if roomName != \"\" {\n\t\tcr := createRoom(roomName)\n\t\tcr.members[c.Conn.RemoteAddr().String()] = c\n\n\t\t// leave current room to join newly create room\n\t\tif c.Room != \"\" {\n\t\t\troomList[c.Room].announce(c.Name + \" has left..\")\n\t\t\tc.leave()\n\t\t\t}\n\n\t\t// set clients room to new room\n\t\tc.Room = cr.name\n\n\t\t// add new room to map\n\t\troomList[cr.name] = cr\n\t\tcr.announce(c.Name + \" has joined!\")\n\t\twriteFormattedMsg(c.Conn, \"* room \"+cr.name+\" has been created *\")\n\t\twriteFormattedMsg(c.Conn, \"============ \" + cr.name + \" ============\")\n\n\t\t} else {\n\t\t\twriteFormattedMsg(c.Conn, \"* error: could not create room \\\"\"+roomName+\"\\\" *\")\n\t\t\t}\n\n}", "func NewRoom() *Room {\n\tid := xid.New().String()\n\tsecret, err := GenerateRandomString(64)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\troom := &Room{\n\t\tID: id,\n\t\tconnections: make(map[string]*Connection),\n\t\tSecret: secret,\n\t}\n\treturn room\n}", "func GenerateRoom(xxStart, yyStart, xxCount, yyCount int, dirHoriz bool) {\n\tgenerateRoom(xxStart, yyStart, xxCount, yyCount, dirHoriz)\n}", "func (rl *roomList) create(name string) *Room {\n\trl.Lock()\n\tdefer rl.Unlock()\n\tr := NewRoom(name)\n\trl.list[name] = r\n\treturn r\n}", "func NewRoom(name string) *Room {\r\n\treturn &Room{\r\n\t\tName: name,\r\n\t\tBroadcast: make(chan []byte),\r\n\t\tRegister: make(chan *Client),\r\n\t\tUnregister: make(chan *Client),\r\n\t\tClients: make(map[*Client]bool),\r\n\t}\r\n}", "func (c *RoomClient) Create() *RoomCreate {\n\tmutation := newRoomMutation(c.config, OpCreate)\n\treturn &RoomCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (c *RoomClient) Create() *RoomCreate {\n\tmutation := newRoomMutation(c.config, OpCreate)\n\treturn &RoomCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (s *SFU) CreateRoom(id string) *Room {\n\troom := NewRoom(id)\n\troom.OnClose(func() {\n\t\ts.roomLock.Lock()\n\t\tdelete(s.rooms, id)\n\t\ts.roomLock.Unlock()\n\t})\n\n\ts.roomLock.Lock()\n\ts.rooms[id] = room\n\ts.roomLock.Unlock()\n\treturn room\n}", "func newRoom(id proto.SID) *room {\n\tr := &room{\n\t\tid: id,\n\t\tpeers: make(map[proto.UID]*Peer),\n\t}\n\treturn r\n}", "func TestReallocatePerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, oldRmName, newRmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, oldRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom, err = CreateRoom(con, newRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = ReallocatePerson(con, fname, lname, newRmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for ReallocatePerson \", t, func() {\n\t\tConvey(\"ReallocatePerson should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"James\", \"Bond\", \"fellow\", \"Valhalla\", \"Mogadishu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Mogadishu\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"James\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Bond\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"TheSecret\", \"Coder\", \"fellow\", \"Narnia\", \"Shell\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\t// So(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (s *Server) MustJoinRoom(t *testing.T, deployment *docker.Deployment, remoteServer gomatrixserverlib.ServerName, roomID string, userID string) *ServerRoom {\n\tt.Helper()\n\tfedClient := s.FederationClient(deployment)\n\tmakeJoinResp, err := fedClient.MakeJoin(context.Background(), remoteServer, roomID, userID, SupportedRoomVersions())\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: make_join failed: %v\", err)\n\t}\n\troomVer := makeJoinResp.RoomVersion\n\tjoinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), gomatrixserverlib.ServerName(s.ServerName), s.KeyID, s.Priv, roomVer)\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: failed to sign event: %v\", err)\n\t}\n\tsendJoinResp, err := fedClient.SendJoin(context.Background(), gomatrixserverlib.ServerName(remoteServer), joinEvent, roomVer)\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: send_join failed: %v\", err)\n\t}\n\n\troom := newRoom(roomVer, roomID)\n\tfor _, ev := range sendJoinResp.StateEvents {\n\t\troom.replaceCurrentState(ev)\n\t}\n\troom.AddEvent(joinEvent)\n\ts.rooms[roomID] = room\n\n\tt.Logf(\"Server.MustJoinRoom joined room ID %s\", roomID)\n\n\treturn room\n}", "func (c *Mock) SetRoom(r interfaces.Room) {\n\tc.FakeSetRoom(r)\n}", "func NewRoom(name, creator string) *Room {\n\tadmins := make([]string, 1)\n\tadmins[0] = creator\n\treturn &Room{\n\t\tName: name,\n\t\tCreator: creator,\n\t\tAdmins: admins,\n\t\tBanned: make([]string, 0),\n\t\tOnline: make([]string, 0),\n\n\t\tgame: nil,\n\t\tpreviousGame: nil,\n\t}\n}", "func NewRoom(p Player) *Room {\n\treturn &Room{\n\t\tID: uuid.New(),\n\t\tplayers: []Player{p},\n\t\tStatus: Waiting,\n\t\tended: false,\n\t\tlastActivity: time.Now(),\n\t\tadmin: p,\n\t\tin: make(chan DirectionUpdate),\n\t\tout: make(chan Update),\n\t}\n}", "func NewRoom() *room {\n\treturn &room{\n\t\tstate: roomState{\n\t\t\tBannedUsers: make(map[string]struct{}),\n\t\t},\n\t}\n}", "func PostRoom(c *gin.Context) {\n\tsession := sessions.Default(c)\n\troomName := c.PostForm(\"name\")\n\tif !m.CreateRoom(roomName) {\n\t\tsession.AddFlash(\"The room already exists. Please try with a different name.\", \"CreateRoom\")\n\t}\n\tsession.Save()\n\tc.Redirect(http.StatusSeeOther, \"/dashboard\")\n}", "func NewRoom(zone *Zone, id string, name string, description string) *Room {\n\treturn &Room{\n\t\tId: id,\n\t\tName: name,\n\t\tDescription: description,\n\t\tZone: zone,\n\t\tplayerList: player.NewList(),\n\t\tinventory: NewRoomInventory(),\n\t\tmobs: NewRoomMobs(),\n\t\tdirections: make(map[direction.Direction]*Room),\n\t\tflags: make(map[string]bool),\n\t}\n}", "func (bpdb *BitpartmentDB) InsertRoom(room *Room) (interface{}, error) {\n\treturn bpdb.insert(room, \"ROOM\")\n}", "func (lobby *Lobby) CreateAndAddToRoom(rs *models.RoomSettings, conn *Connection) (room *Room, err error) {\n\tdefer utils.CatchPanic(\"lobby_room.go CreateAndAddToRoom()\")\n\tif lobby.done() || conn.done() {\n\t\treturn\n\t}\n\n\tlobby.wGroup.Add(1)\n\tdefer lobby.wGroup.Done()\n\n\tconn.wGroup.Add(1)\n\tdefer conn.wGroup.Done()\n\n\tif room, err = lobby.createRoom(rs); err == nil {\n\t\tutils.Debug(false, \"We create your own room, cool!\", conn.ID())\n\t\troom.addConnection(conn, true, false)\n\t} else {\n\t\tutils.Debug(true, \"cant create. Why?\", conn.ID(), err.Error())\n\t}\n\treturn\n}", "func NewRoom(pub Publisher) *Room {\n\treturn &Room{pub: pub}\n}", "func (r *chatRoomRepo) Create(ctx context.Context, room *models.ChatRoom) (*models.ChatRoom, error) {\n\tstmt, err := r.db.PrepareContext(ctx, queryChatRoomCreate)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"chatRoomRepo.Create:: error creating prepared stmt - %v\", err)\n\t}\n\n\tdefer func(stmt *sql.Stmt) {\n\t\t_ = stmt.Close()\n\t}(stmt)\n\n\tresult, err := stmt.ExecContext(ctx, room.UUID, room.Name, room.UsersCount, room.IsPrivate, room.UserID,\n\t\troom.CreatedAt, room.UpdatedAt)\n\n\tif err != nil {\n\t\tif mysqlErr, ok := err.(*mysql.MySQLError); ok {\n\t\t\tif mysqlErr.Number == models.MySQLDuplicateEntryNumber {\n\t\t\t\treturn nil, models.ErrDuplicateRecord\n\t\t\t}\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"chatRoomRepo.Create:: error inserting record - %v\", err)\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"chatRoomRepo.Create:: error getting id - %v\", err)\n\t}\n\n\troom.ID = uint64(id)\n\treturn room, nil\n}", "func NewRoom(name string) *Room {\n\treturn &Room{\n\t\tname: name,\n\t\tclients: make(map[*Client]bool),\n\t\tregister: make(chan *Client, 100),\n\t\tunregister: make(chan *Client, 100),\n\t\tbroadcast: make(chan *Message, 1000),\n\t}\n}", "func newRoom() *room {\n\treturn &room{\n\t\tfoward: make(chan []byte),\n\t\tjoin: make(chan *client),\n\t\tleave: make(chan *client),\n\t\tclients: make(map[*client]bool),\n\t\t//default trace sets as Off\n\t\ttracer: trace.Off(),\n\t}\n}", "func NewRoom(name, logFilePath string) (*Room, error) {\n\n\tp, err := expandPath(logFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error while getting log file path: %w\", err)\n\t}\n\n\tlogFileName := path.Join(p, strings.ReplaceAll(name, \" \", \"_\")+\".dat\")\n\tlog.Printf(\"Log file location: %s\\n\", logFileName)\n\n\tlogFile, err := os.OpenFile(logFileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening/creating log file: %v\", err)\n\t}\n\n\treturn &Room{name: name, logFile: logFile}, nil\n}", "func (s *Server) MustMakeRoom(t *testing.T, roomVer gomatrixserverlib.RoomVersion, events []b.Event) *ServerRoom {\n\troomID := fmt.Sprintf(\"!%d:%s\", len(s.rooms), s.ServerName)\n\troom := &ServerRoom{\n\t\tRoomID: roomID,\n\t\tVersion: roomVer,\n\t\tState: make(map[string]*gomatrixserverlib.Event),\n\t}\n\t// sign all these events\n\tfor _, ev := range events {\n\t\tsignedEvent := s.MustCreateEvent(t, room, ev)\n\t\troom.AddEvent(signedEvent)\n\t}\n\ts.rooms[roomID] = room\n\treturn room\n}", "func New(entities []interface{}, dba orm.ORM, version orm.VersionNumber,\n\tmigrations []orm.Migration, identityCalculator orm.IdentityHashCalculator) (room *Room, errors []error) {\n\n\tif len(entities) < 1 {\n\t\terrors = append(errors, fmt.Errorf(\"No entities provided for the database\"))\n\t}\n\tif dba == nil {\n\t\terrors = append(errors, fmt.Errorf(\"Need an ORM to work with\"))\n\t}\n\tif version < 1 {\n\t\terrors = append(errors, fmt.Errorf(\"Only non zero versions allowed\"))\n\t}\n\tif identityCalculator == nil {\n\t\terrors = append(errors, fmt.Errorf(\"Need an identity calculator\"))\n\t}\n\n\tif len(errors) < 1 {\n\t\troom = &Room{\n\t\t\tentities: entities,\n\t\t\tversion: version,\n\t\t\tmigrations: migrations,\n\t\t\tdba: dba,\n\t\t\tidentityCalculator: identityCalculator,\n\t\t}\n\t}\n\n\treturn\n}", "func TestEmployeeManagerMapCreate(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\texpectedResponse := `{\"Jonas\":{\"Sophie\":{\"Nick\":{\"Barbara\":{},\"Peter\":{}}}}}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (c *RoomdetailClient) Create() *RoomdetailCreate {\n\tmutation := newRoomdetailMutation(c.config, OpCreate)\n\treturn &RoomdetailCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (s *Server) MustMakeRoom(t *testing.T, roomVer gomatrixserverlib.RoomVersion, events []b.Event) *ServerRoom {\n\troomID := fmt.Sprintf(\"!%d:%s\", len(s.rooms), s.ServerName)\n\troom := newRoom(roomVer, roomID)\n\n\t// sign all these events\n\tfor _, ev := range events {\n\t\tsignedEvent := s.MustCreateEvent(t, room, ev)\n\t\troom.AddEvent(signedEvent)\n\t}\n\ts.rooms[roomID] = room\n\treturn room\n}", "func (c *Client) CreateRoom(ctx context.Context, params *CreateRoomInput, optFns ...func(*Options)) (*CreateRoomOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateRoomInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateRoom\", params, optFns, c.addOperationCreateRoomMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateRoomOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (d *Dispatcher) RegisterRoom(ctx context.Context, room *entity.Room) error {\n\td.rms.CreateRoom(room)\n\treturn nil\n}", "func TestCreateUser(t *testing.T) {\n user := User{\n Name: \"Mohammd Osama\",\n Password: \"helloworld\",\n Email: \"[email protected]\",\n }\n if user.ID == 0 {\n t.Errorf(\"Expected ID > 0, Received %d\", user.ID)\n }\n}", "func GenerateRoomPath(form url.Values) string {\n\n\tvar route string\n\tvar roomID string\n\n\txr := form[\"room\"]\n\tif len(xr) > 0 {\n\t\troomID = xr[0]\n\t}\n\n\tif len(roomID) > 0 {\n\n\t\troute = fmt.Sprintf(\"/room/%v\", roomID)\n\n\t} else {\n\n\t\tnewRoom := CreateRoom()\n\t\troute = fmt.Sprintf(\"/room/%v\", newRoom.ID)\n\t}\n\n\treturn route\n}", "func CreateMeeting(meetingRoom *dataStructs.MeetingRoom) (string, error) {\n\tif meetingRoom.Name_ == \"\" {\n\t\treturn \"\", errors.New(\"meeting name cannot be empty\")\n\t}\n\n\tif meetingRoom.MeetingID_ == \"\" {\n\t\treturn \"\", errors.New(\"meeting ID cannot be empty\")\n\t}\n\n\tif meetingRoom.AttendeePW_ == \"\" {\n\t\treturn \"\", errors.New(\"attendee PW cannot be empty\")\n\t}\n\n\tif meetingRoom.ModeratorPW_ == \"\" {\n\t\treturn \"\", errors.New(\"moderator PW cannot be empty\")\n\t}\n\n\tname := \"name=\" + url.QueryEscape(meetingRoom.Name_)\n\tmeetingID := \"&meetingID=\" + url.QueryEscape(meetingRoom.MeetingID_)\n\tattendeePW := \"&attendeePW=\" + url.QueryEscape(meetingRoom.AttendeePW_)\n\tmoderatorPW := \"&moderatorPW=\" + url.QueryEscape(meetingRoom.ModeratorPW_)\n\twelcome := \"&welcome=\" + url.QueryEscape(meetingRoom.Welcome)\n\tdialNumber := \"&dialNumber=\" + url.QueryEscape(meetingRoom.DialNumber)\n\tlogoutURL := \"&logoutURL=\" + url.QueryEscape(meetingRoom.LogoutURL)\n\trecord := \"&record=\" + url.QueryEscape(meetingRoom.Record)\n\tduration := \"&duration=\" + url.QueryEscape(strconv.Itoa(meetingRoom.Duration))\n\tallowStartStopRecording := \"&allowStartStopRecording=\" +\n\t\turl.QueryEscape(strconv.FormatBool(meetingRoom.AllowStartStopRecording))\n\tmoderatorOnlyMessage := \"&moderatorOnlyMessage=\" +\n\t\turl.QueryEscape(meetingRoom.ModeratorOnlyMessage)\n\tmetaBBBRecordingReadyURL := \"&meta_bbb-recording-ready-url=\" +\n\t\turl.QueryEscape(meetingRoom.Meta_bbb_recording_ready_url)\n\tmetaChannelId := \"&meta_channelid=\" +\n\t\turl.QueryEscape(meetingRoom.Meta_channelid)\n\tmetaEndCallbackURL := \"&meta_endCallbackUrl=\" +\n\t\turl.QueryEscape(meetingRoom.Meta_endcallbackurl)\n\tvoiceBridge := \"&voiceBridge=\" + url.QueryEscape(meetingRoom.VoiceBridge)\n\n\tmetaBBBOrigin := \"&meta_bbb-origin=\" + url.QueryEscape(meetingRoom.Meta_bbb_origin) +\n\t\t\"&meta_bbb-origin-version=\" + url.QueryEscape(meetingRoom.Meta_bbb_origin_version) +\n\t\t\"&meta_bbb-origin-server-name=\" + url.QueryEscape(meetingRoom.Meta_bbb_origin_server_name)\n\n\tmetaDC := \"&meta_dc-creator=\" + url.QueryEscape(meetingRoom.Meta_dc_creator)\n\n\tcreateParam := name + meetingID + attendeePW + moderatorPW + welcome + dialNumber +\n\t\tvoiceBridge + logoutURL + record + duration + moderatorOnlyMessage + metaBBBRecordingReadyURL +\n\t\tmetaChannelId + metaEndCallbackURL + allowStartStopRecording + metaBBBOrigin + metaDC\n\n\tchecksum := helpers.GetChecksum(\"create\" + createParam + secret)\n\n\tresponse, err := helpers.HttpGet(BaseUrl + \"create?\" + createParam + \"&checksum=\" + checksum)\n\n\tif err != nil {\n\t\tmattermost.API.LogError(\"ERROR: HTTP ERROR: \" + response)\n\t\treturn \"\", errors.New(response)\n\t}\n\n\tif err := helpers.ReadXML(response, &meetingRoom.CreateMeetingResponse); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif SUCCESS_STATUS_CODE == meetingRoom.CreateMeetingResponse.Returncode {\n\t\tmattermost.API.LogInfo(\"SUCCESS CREATE MEETINGROOM. MEETING ID: \" +\n\t\t\tmeetingRoom.CreateMeetingResponse.MeetingID)\n\t\treturn meetingRoom.CreateMeetingResponse.MeetingID, nil\n\t}\n\n\tmattermost.API.LogError(\"CREATE MEETINGROOM FAILD: \" + response)\n\treturn \"\", errors.New(response)\n}", "func NewRoom(id string, rds *redis.Client) *Room {\n\treturn &Room{\n\t\tid: id,\n\t\tclients: make(map[*Client]bool),\n\t\tregister: make(chan *Client),\n\t\tunregister: make(chan *Client),\n\t\tbroadcast: make(chan *model.WebsocketMessage),\n\t\tredis: rds,\n\t}\n}", "func newRoom(id int) *room {\n\treturn &room{\n\t\tID: id,\n\t\tclients: make(map[*client]bool),\n\t\tmessages: make(chan string), //initialize channel, or...deadlock\n\t\tjoining: make(chan *client), //initialize channel, or...deadlock\n\t\tleaving: make(chan *client), //initialize channel, or...deadlock\n\t}\n}", "func (rf *RoomFinder) RegisterRoom( r *Room ) {\n\tif rf.regRoomIds == nil {\n\t\trf.regRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.sdRoomIds == nil {\n\t\trf.sdRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.ldRoomIds == nil {\n\t\trf.ldRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.elRoomIds == nil {\n\t\trf.elRoomIds = make( map[ int32 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.regRoomIds[ r.regionId ] == nil {\n\t\trf.regRoomIds[ r.regionId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.regRoomIds[ r.regionId ].Add( r.id )\n\tif rf.sdRoomIds[ r.shortDescId ] == nil {\n\t\trf.sdRoomIds[ r.shortDescId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.sdRoomIds[ r.shortDescId ].Add( r.id )\n\tif rf.ldRoomIds[ r.longDescId ] == nil {\n\t\trf.ldRoomIds[ r.longDescId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.ldRoomIds[ r.longDescId ].Add( r.id )\n\tes := make( []string, len(r.exits) )\n\ti := 0\n\tfor k, _ := range r.exits {\n\t\tes[i] = k\n\t\ti++\n\t}\n\th := hashExits( es )\n\tif rf.elRoomIds[ h ] == nil {\n\t\trf.elRoomIds[ h ] = tools.NewSI64Set( 1 )\n\t}\n\trf.elRoomIds[ h ].Add( r.id )\n\treturn\n}", "func NewRoom(name string) *Room {\n\troom := new(Room)\n\troom.Name = name\n\troom.clients = make(map[string]Client)\n\troom.queue = make(chan string)\n\n\tgo room.Broadcast()\n\n\treturn room\n}", "func (mr *MockIRoomServiceMockRecorder) SCreateRoom(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"SCreateRoom\", reflect.TypeOf((*MockIRoomService)(nil).SCreateRoom), arg0)\n}", "func getRoomMock(cfg roomMockConfig) roomMock {\n\tvar conf config.WorkerConfig\n\tif _, err := config.LoadConfig(&conf, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tconf.Worker.Library.BasePath = cfg.gamesPath\n\n\tfixEmulators(&conf, cfg.autoGlContext)\n\tl := logger.NewConsole(conf.Worker.Debug, \"w\", false)\n\tif cfg.noLog {\n\t\tlogger.SetGlobalLevel(logger.Disabled)\n\t}\n\n\t// sync cores\n\tif err := remotehttp.CheckCores(conf.Emulator, l); err != nil {\n\t\tl.Error().Err(err).Msg(\"cores sync error\")\n\t}\n\tconf.Encoder.Video.Codec = string(cfg.vCodec)\n\n\troom := NewRoom(cfg.roomName, cfg.game, nil, conf, l)\n\n\tif !cfg.dontStartEmulator {\n\t\troom.StartEmulator()\n\t}\n\n\t// loop-wait the room initialization\n\tvar init sync.WaitGroup\n\tinit.Add(1)\n\twasted := 0\n\tgo func() {\n\t\tsleepDeltaMs := 10\n\t\tfor room.emulator == nil {\n\t\t\ttime.Sleep(time.Duration(sleepDeltaMs) * time.Millisecond)\n\t\t\twasted++\n\t\t\tif wasted > 1000 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tinit.Done()\n\t}()\n\tinit.Wait()\n\treturn roomMock{Room: room, startEmulator: !cfg.dontStartEmulator}\n}", "func newRoom(id proto.RID) *room {\n\tr := &room{\n\t\tid: id,\n\t\tpeers: make(map[proto.UID]*peer),\n\t}\n\n\troomLock.Lock()\n\tdefer roomLock.Unlock()\n\trooms[id] = r\n\n\treturn r\n}", "func (o *CreateRoomParams) WithTimeout(timeout time.Duration) *CreateRoomParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func DeleteRoom(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\tvar permission Permission\n\terr := DB.Get(&permission, \"SELECT * FROM permissions WHERE user_id=$1 AND type=$2 AND type_id=$3\", user.ID, \"room\", c.Param(\"roomId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRDR001\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusNotFound, ErrorResponse{\n\t\t\tCode: \"CSRDR001\",\n\t\t\tMessage: \"Room not found\",\n\t\t})\n\t}\n\n\tif permission.Admin == false {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRDR002\"}).Warnf(\"Unauthorized\")\n\t\treturn c.JSON(http.StatusUnauthorized, ErrorResponse{\n\t\t\tCode: \"CSRDR002\",\n\t\t\tMessage: \"Unauthorized modifications\",\n\t\t})\n\t}\n\n\t_, err = DB.Exec(\"DELETE FROM rooms WHERE id=$1\", c.Param(\"roomId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRDR003\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRDR003\",\n\t\t\tMessage: \"Room can't be deleted\",\n\t\t})\n\t}\n\t_, err = DB.Exec(\"DELETE FROM permissions WHERE type=$1 AND type_id=$2\", \"room\", c.Param(\"roomId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRDR004\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRDR004\",\n\t\t\tMessage: \"Room can't be deleted\",\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusOK, MessageResponse{\n\t\tMessage: \"Room deleted\",\n\t})\n}", "func TestCreate(t *testing.T) {\n\tassert := assert.New(t)\n\tacctDefEntry := new(AccountDefEntry)\n\tacctDefEBuilder := &AccountDefEntryBuilder{\n\t\taccountDefEntry: acctDefEntry,\n\t}\n\tacctDE := acctDefEBuilder.Create()\n\tassert.Equal(acctDefEntry, acctDE)\n}", "func NewRoomRepository(db database.Database, log bool) (Repository, error) {\n\tif err := db.CreateSchema([]interface{}{\n\t\t(*model.Room)(nil),\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif log {\n\t\tdb.Conn().AddQueryHook(dbLogger{})\n\t}\n\n\treturn &roomRepository{\n\t\tdb: db,\n\t}, nil\n}", "func CreateTestGameForHomeTeam(homeTeam models.Team) (game models.Game) {\n\taway_team := CreateTestTeam()\n\tgame = models.Game{HomeTeam: homeTeam, AwayTeam: away_team}\n\tgame.Create()\n\n\treturn game\n}", "func createLobby(maxRounds int, startingTeam int, team1Name string, team2Name string) Lobby {\n\n\t// Firstly generate uuids\n\tlobbyUUID := generateUUID()\n\tteam1UIDGenerated := generateUUID()\n\tteam2UIDGenerated := generateUUID()\n\n\tlobby := Lobby{\n\t\tLobbyUID: lobbyUUID,\n\t\tTeam1UID: team1UIDGenerated,\n\t\tTeam1Name: team1Name,\n\t\tTeam2Name: team2Name,\n\t\tTeam2UID: team2UIDGenerated,\n\t\tTeam1link: fmt.Sprintf(`/pv/%v/%v`, lobbyUUID, team1UIDGenerated),\n\t\tTeam2link: fmt.Sprintf(`/pv/%v/%v`, lobbyUUID, team2UIDGenerated),\n\t\tMaxRounds: maxRounds,\n\t\tEnabled: false,\n\t\tStartingTeam: startingTeam,\n\t}\n\n\t// By default whenever a new lobby is generated then a game on nagrand is added.\n\t// With the exception of there being a potential different map for single play.\n\tif maxRounds != 1 {\n\t\tlobby.createDefaultGame(startingTeam)\n\t}\n\n\tif maxRounds == 1 {\n\t\tlobby.createGame(startingTeam, 1)\n\t}\n\n\treturn lobby\n\n}", "func AddNewRoom(storage storage.Storage) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar newRoom *models.Room\n\t\tvar newRoomData *models.NewRoomData\n\t\tvar createdBy int\n\t\tvar err error\n\n\t\tif createdBy, err = strconv.Atoi(c.Request.Header.Get(\"created-by\")); err != nil || createdBy == 0 {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": \"created-by missing\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif err = c.ShouldBindJSON(&newRoomData); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"newRoomData: %+v\\n\", newRoomData)\n\n\t\tif newRoom, err = models.NewRoom(newRoomData, createdBy); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// TODO: Check if RoomType exists or not\n\t\tif err = storage.AddNewRoom(newRoom); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tc.Status(http.StatusNoContent)\n\t}\n}", "func NewRoom() *Room {\n\treturn &Room{\n\t\tforward: make(chan *Message),\n\t\tjoin: make(chan *Client),\n\t\tleave: make(chan *Client),\n\t\tclients: make(map[*Client]bool),\n\t}\n}", "func (s *RoomsNightService) Room(ctx context.Context, id int) (*NightRoomResponsePayload, *Response, error) {\n\treq, err := s.NewRequest(id)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpayload := &NightRoomResponsePayload{}\n\tresp, err := s.client.Do(ctx, req, payload)\n\n\treturn payload, resp, nil\n}", "func CreateRoomRoutes(roomDBFacade db.RoomReaderWriterUpdaterDeleter) []Route {\n\tmyRoomAPI := roomAPI{\n\t\troomReader: roomDBFacade,\n\t\troomWriter: roomDBFacade,\n\t\troomUpdater: roomDBFacade,\n\t\troomDeleter: roomDBFacade,\n\t}\n\n\troutes := []Route{\n\t\tNewRoute(\"/api/v1/rooms\", myRoomAPI.getAllRooms, \"GET\"),\n\t\tNewRoute(\"/api/v1/room\", myRoomAPI.getARoom, \"GET\"),\n\t\tNewRoute(\"/api/v1/room\", myRoomAPI.writeARoom, \"POST\"),\n\t\tNewRoute(\"/api/v1/room\", myRoomAPI.updateARoom, \"PUT\"),\n\t\tNewRoute(\"/api/v1/room\", myRoomAPI.deleteARoom, \"DELETE\"),\n\t}\n\n\treturn routes\n}", "func (m *MockRoute) Create(route api.Route) (api.Route, error) {\n\tret := m.ctrl.Call(m, \"Create\", route)\n\tret0, _ := ret[0].(api.Route)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *PlacesRequestBuilder) Room()(*ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.RoomRequestBuilder) {\n return ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.NewRoomRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func AddRoom(xxStart, yyStart, xxCount, yyCount int) {\n\taddRoom(xxStart, yyStart, xxCount, yyCount)\n}", "func (rc *RoominfoCreate) Save(ctx context.Context) (*Roominfo, error) {\n\tif _, ok := rc.mutation.RoomID(); !ok {\n\t\treturn nil, &ValidationError{Name: \"RoomID\", err: errors.New(\"ent: missing required field \\\"RoomID\\\"\")}\n\t}\n\tif _, ok := rc.mutation.RoomNo(); !ok {\n\t\treturn nil, &ValidationError{Name: \"RoomNo\", err: errors.New(\"ent: missing required field \\\"RoomNo\\\"\")}\n\t}\n\tif v, ok := rc.mutation.RoomNo(); ok {\n\t\tif err := roominfo.RoomNoValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"RoomNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"RoomNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := rc.mutation.RoomType(); !ok {\n\t\treturn nil, &ValidationError{Name: \"RoomType\", err: errors.New(\"ent: missing required field \\\"RoomType\\\"\")}\n\t}\n\tif v, ok := rc.mutation.RoomType(); ok {\n\t\tif err := roominfo.RoomTypeValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"RoomType\", err: fmt.Errorf(\"ent: validator failed for field \\\"RoomType\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := rc.mutation.RoomTime(); !ok {\n\t\treturn nil, &ValidationError{Name: \"RoomTime\", err: errors.New(\"ent: missing required field \\\"RoomTime\\\"\")}\n\t}\n\tif v, ok := rc.mutation.RoomTime(); ok {\n\t\tif err := roominfo.RoomTimeValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"RoomTime\", err: fmt.Errorf(\"ent: validator failed for field \\\"RoomTime\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := rc.mutation.RoomStatus(); !ok {\n\t\treturn nil, &ValidationError{Name: \"RoomStatus\", err: errors.New(\"ent: missing required field \\\"RoomStatus\\\"\")}\n\t}\n\tif v, ok := rc.mutation.RoomStatus(); ok {\n\t\tif err := roominfo.RoomStatusValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"RoomStatus\", err: fmt.Errorf(\"ent: validator failed for field \\\"RoomStatus\\\": %w\", err)}\n\t\t}\n\t}\n\tvar (\n\t\terr error\n\t\tnode *Roominfo\n\t)\n\tif len(rc.hooks) == 0 {\n\t\tnode, err = rc.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*RoominfoMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\trc.mutation = mutation\n\t\t\tnode, err = rc.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(rc.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = rc.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, rc.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func NewRoomFromJson(id string, j []byte) (*Room, error) {\n\tm := make(map[string]interface{})\n\terr := json.Unmarshal(j, &m)\n\n\tif err == nil {\n\t\tr := RoomFromMap(m)\n\t\tr.UId = id\n\t\treturn r, nil\n\t}\n\treturn nil, err\n}", "func CreateTestPlayerForTeam(team models.Team) {\n\tplayer := models.Player{Name: rand.String(10), Active: true, JerseyNumber: 23, Team: team}\n\tplayer.Create()\n\treturn\n}", "func New() *Room {\n\tid := xid.New().String()\n\tsecret, err := util.GenerateRandomString(64)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\troom := &Room{\n\t\tID: id,\n\t\tconnections: make(map[string]*connection.Connection),\n\t\tSecret: secret,\n\t}\n\treturn room\n}", "func NewRoomDAO(db *DBAccess) *RoomDAO {\n\treturn &RoomDAO{\n\t\tdb: db,\n\t\tcollection: \"rooms\",\n\t}\n}", "func TestCreateSuccess(t *testing.T) {\n\tisTesting = true\n\tvar request = Request{\n\t\tPath: \"/api/devices\",\n\t\tHTTPMethod: \"POST\",\n\t\tBody: `{\n\t\t\t\"id\": \"valid-id\",\n\t\t\t\"deviceModel\": \"valid-device-model\",\n\t\t\t\"model\": \"valid-model\",\n\t\t\t\"name\": \"valid-name\",\n\t\t\t\"serial\": \"valid-serial\"\n\t\t}`,\n\t}\n\tvar response, _ = Handler(request)\n\tif response.StatusCode != 201 {\n\t\tt.Errorf(\"response status code has to be 201\")\n\t}\n}", "func TestCreateMovieOK(t *testing.T) {\n\t// Prepare\n\tmovie := models.Movie{\n\t\tName: \"godfather\",\n\t}\n\tmovies = []models.Movie{}\n\n\t// Command\n\tmovie, err := CreateMovie(movie)\n\n\t// Assert\n\tassert.NoError(t, err)\n\tassert.Equal(t, movie.Name, movies[0].Name, \"the movie is not stored properly to db\")\n}" ]
[ "0.7288036", "0.7206583", "0.70437026", "0.6869155", "0.6868737", "0.6844833", "0.6795024", "0.66933244", "0.6667715", "0.66677004", "0.6508968", "0.6444158", "0.63904876", "0.6388529", "0.63182753", "0.6289313", "0.6278355", "0.6267864", "0.6233683", "0.62095946", "0.62056357", "0.61774844", "0.6121763", "0.6092586", "0.6026229", "0.595033", "0.5949439", "0.59425884", "0.58967584", "0.5877939", "0.5854049", "0.58298033", "0.5781912", "0.5776935", "0.57604045", "0.57504845", "0.57403296", "0.57259613", "0.5679482", "0.56647825", "0.5639849", "0.56371033", "0.5633803", "0.5629512", "0.5628082", "0.5628082", "0.5622116", "0.562136", "0.5604589", "0.55820173", "0.557212", "0.5563546", "0.55527425", "0.5535649", "0.5533087", "0.5522524", "0.54909813", "0.54838437", "0.5481929", "0.5476664", "0.5465076", "0.5457434", "0.54534537", "0.53824604", "0.5370789", "0.5370787", "0.535302", "0.5348252", "0.5347663", "0.53361607", "0.5322266", "0.5310153", "0.5308163", "0.5308118", "0.5303339", "0.52800703", "0.5279233", "0.5268052", "0.5257052", "0.5248349", "0.52317595", "0.52190083", "0.5215105", "0.5214706", "0.52029186", "0.519793", "0.5191469", "0.51790863", "0.51689005", "0.51622367", "0.5151602", "0.5146242", "0.5144628", "0.51441234", "0.5140382", "0.5137426", "0.5132766", "0.5132351", "0.5118194", "0.5113833" ]
0.81604636
0
TestGetRoom tests the functionality of GetRoom
func TestGetRoom(t *testing.T) { var ( err error user User room Room fetchRoom = func(fname, lname, userType, rmName, rmType string) { room, err = CreateRoom(con, rmName, rmType) So(err, ShouldBeNil) So(room.ID, ShouldNotBeBlank) user, err = AddPerson(con, fname, lname, userType, room.Name, "") So(err, ShouldBeNil) So(user, ShouldNotResemble, (User{})) room = Room{} room, err = GetRoom(con, rmName) } ) Convey("Tests for GetRoom ", t, func() { Convey("GetRoom should return Room with all the correct values present and an error", func() { fetchRoom("Joshua", "Mwaniki", "staff", "Valhalla", "office") So(err, ShouldBeNil) So(room.Capacity, ShouldEqual, 6) So(room.ID, ShouldNotBeBlank) So(room.Name, ShouldEqual, "Valhalla") So(room.Occupants, ShouldNotBeEmpty) So(room.Type, ShouldNotBeBlank) So(room.Occupants[0].FirstName, ShouldEqual, "Joshua") So(room.Occupants[0].ID, ShouldNotBeBlank) So(room.Occupants[0].LastName, ShouldEqual, "Mwaniki") So(room.Occupants[0].Type, ShouldEqual, "staff") }) Convey("Print the successfully created Room and User", func() { fetchRoom("James", "Kaberia", "staff", "Pretoria", "office") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestGetRoomDetails(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tusers []models.User\n\t\trm models.Room\n\t\troom Room\n\n\t\tgetRoomDetails = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\t_, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\trm, users, err = getRoomDetails(con, rmName, rmType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for getRoomDetails \", t, func() {\n\t\tConvey(\"getRoomDetaiils should return the room, a slice of user and an error \", func() {\n\t\t\tgetRoomDetails(\"Daniel\", \"Ikigai\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(rm.Capacity, ShouldEqual, 6)\n\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\tSo(rm.Name, ShouldEqual, \"Tsavoo\")\n\t\t\tSo(rm.Type, ShouldEqual, \"office\")\n\n\t\t\tSo(users[0].FirstName, ShouldEqual, \"Daniel\")\n\t\t\tSo(users[0].ID, ShouldNotBeBlank)\n\t\t\tSo(users[0].LastName, ShouldEqual, \"Ikigai\")\n\t\t\tSo(users[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tgetRoomDetails(\"Christine\", \"J\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (c *Client) GetRoom(ctx context.Context, name string) (*GetRoomResponse, error) {\n\tresp := &GetRoomResponse{}\n\treturn resp, c.request(ctx, \"GET\", \"rooms/\"+name, nil, resp)\n}", "func TestGetRoomAllocations(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\t\trooms []Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\trooms, err = GetRoomAllocations(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoomAllocations \", t, func() {\n\t\tConvey(\"GetRoomAllocations should return a slice of Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Garbrielle\", \"Wanjigi\", \"fellow\", \"Timbuktu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, room = range rooms {\n\n\t\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Name, ShouldEqual, \"Timbuktu\")\n\t\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Garbrielle\")\n\t\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Wanjigi\")\n\t\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"Ashley\", \"Wanjigi\", \"fellow\", \"Golang\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func GetRoom(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tcUser := m.CurrentUser(session.Get(\"uid\").(int))\n\tdomain := m.GetDomain()\n\troomID, _ := strconv.Atoi(c.Param(\"roomID\"))\n\troom := m.GetRoom(roomID)\n\twToken := m.GetWatsonToken()\n\tjoinedFlg := cUser.IsJoin(roomID)\n\n\t// Flash Message\n\tvar joinRoomMessage interface{}\n\tif f := session.Flashes(\"JoinRoom\"); len(f) != 0 {\n\t\tjoinRoomMessage = f[0]\n\t}\n\tc.HTML(http.StatusOK, \"room.tmpl\", gin.H{\n\t\t\"CurrentUser\": cUser,\n\t\t\"Domain\": domain,\n\t\t\"Room\": room,\n\t\t\"WatsonToken\": wToken,\n\t\t\"JoinedFlg\": joinedFlg,\n\t\t\"JoinRoomMessage\": joinRoomMessage,\n\t})\n}", "func roomToTestRoom(room *level.RoomData, inputLevel level.Level) Room {\n\treturn Room{\n\t\tType: \"room\",\n\t\tOrigin: Point{\n\t\t\troom.TopLeft.Row,\n\t\t\troom.TopLeft.Col,\n\t\t},\n\t\tBounds: Bounds{\n\t\t\tRows: room.Size.Row,\n\t\t\tColumns: room.Size.Col,\n\t\t},\n\t\tLayout: TilesToArray(inputLevel.GetTiles(room.TopLeft, room.Size)),\n\t}\n}", "func (c *Mock) Room() interfaces.Room {\n\treturn c.FakeRoom()\n}", "func TestCreateRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\troom Room\n\n\t\tcreateRoom = func(name, roomType string) {\n\t\t\troom, err = CreateRoom(con, name, roomType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for CreateRoom \", t, func() {\n\t\tConvey(\"CreateRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tcreateRoom(\"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants, ShouldBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tcreateRoom(\"Golang\", \"livingspace\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func GetRoom(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\tvar permission permissionRoom\n\terr := DB.QueryRowx(`\n\t\tSELECT permissions.*, users.*,\n\t\trooms.id as r_id,\trooms.name AS r_name, rooms.home_id AS r_homeid, rooms.created_at AS r_createdat, rooms.updated_at AS r_updatedat FROM permissions\n\t\tJOIN rooms ON permissions.type_id = rooms.id\n\t\tJOIN users ON rooms.creator_id = users.id\n\t\tWHERE permissions.type=$1 AND permissions.type_id=$2 AND permissions.user_id=$3\n\t`, \"room\", c.Param(\"roomId\"), user.ID).StructScan(&permission)\n\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGR001\"}).Errorf(\"QueryRowx: Select error\")\n\t\treturn c.JSON(http.StatusNotFound, ErrorResponse{\n\t\t\tCode: \"CSRGR001\",\n\t\t\tMessage: \"Room can't be found\",\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusOK, roomRes{\n\t\tID: permission.RoomID,\n\t\tName: permission.RoomName,\n\t\tHomeID: permission.RoomHomeID,\n\t\tCreatedAt: permission.RoomCreatedAt,\n\t\tUpdatedAt: permission.RoomUpdatedAt,\n\t\tCreator: permission.User,\n\t\tRead: permission.Permission.Read,\n\t\tWrite: permission.Permission.Write,\n\t\tManage: permission.Permission.Manage,\n\t\tAdmin: permission.Permission.Admin,\n\t})\n}", "func TestAddRoom(t *testing.T) {\n\t// first create a new controller\n\tapi := NewRoomApiController()\n\troomrouter := NewRouter(api)\n\ttestserver := httptest.NewServer(roomrouter)\n\tdefer testserver.Close()\n\n\t// api configuration\n\tapiConfig := roomapi.NewConfiguration()\n\tapiConfig.HTTPClient = testserver.Client()\n\ttesturl, err := url.Parse(testserver.URL)\n\tif err != nil {\n\t\tt.Errorf(\"error parsing url from test server: %s\", err)\n\t\treturn\n\t}\n\tapiConfig.Host = testurl.Host\n\n\t// create first client\n\tapic := roomapi.NewAPIClient(apiConfig)\n\tbackground := context.Background()\n\tretRoom, _, err := apic.RoomApi.AddRoom(background)\n\tif err != nil {\n\t\tt.Errorf(\"error adding room: %s\", err)\n\t\treturn\n\t}\n\tt.Logf(\"room id: %d, room id str: %s\\n\", retRoom.Id, retRoom.Code)\n}", "func (cl *RestClient) Get(room string) {\n\tresp, err := restGet(room, cl.client, cl.ip, cl.port)\n\tif err != nil {\n\t\tcl.test.Errorf(\"Error with restGet: %v\", err)\n\t}\n\tif resp.StatusCode == 404 { //room not found\n\t\tcl.messages = append(cl.messages, \"Room not Found\")\n\t\tcl.res.RestGet(room)\n\t\treturn\n\t}\n\tif resp.StatusCode != 200 {\n\t\tcl.test.Errorf(\"Rest Get got %v want 200\", resp.StatusCode)\n\t}\n\tdec := json.NewDecoder(resp.Body)\n\tvar messages []string\n\terr = dec.Decode(&messages)\n\tif err != nil {\n\t\tcl.test.Errorf(\"Error decoding in Rest Get: %v\", err)\n\t}\n\tresp.Body.Close()\n\tfor _, mg := range messages {\n\t\tcl.messages = append(cl.messages, mg)\n\t}\n\tcl.res.RestGet(room)\n}", "func GetRoom(id int64) (*Room, bool) {\n\n\troom, ok := hotel[id]\n\treturn room, ok\n}", "func (r Virtual_Guest) GetServerRoom() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getServerRoom\", nil, &r.Options, &resp)\n\treturn\n}", "func (r *RoomService) Get(ctx context.Context, sidOrUniqueName string) (*Room, error) {\n\troom := new(Room)\n\terr := r.client.GetResource(ctx, roomPathPart, sidOrUniqueName, room)\n\treturn room, err\n}", "func getRooms(api *slack.Client) map[string]string {\n\trooms := make(map[string]string)\n\t// get public channels\n\tchannels, _ := api.GetChannels(true)\n\tfor _, channel := range channels {\n\t\trooms[channel.Name] = channel.ID\n\t}\n\t// get private channels\n\tgroups, _ := api.GetGroups(true)\n\tfor _, group := range groups {\n\t\trooms[group.Name] = group.ID\n\t}\n\treturn rooms\n}", "func (d *Dispatcher) GetRoom(ctx context.Context, roomUID string) *entity.Room {\n\troom := d.rms.GetRoom(roomUID)\n\tif room == nil {\n\t\treturn nil\n\t}\n\treturn room\n}", "func getRoom(id proto.RID) *room {\n\troomLock.RLock()\n\tdefer roomLock.RUnlock()\n\tr := rooms[id]\n\treturn r\n}", "func (a *RoomHandler) GetRoomList(c echo.Context) error {\n\tsortParam := c.QueryParam(\"sort_by\")\n\torderParam := c.QueryParam(\"order_by\")\n\n\tsortField := formSortField(sortParam)\n\tif sortField == usecase.ErrField {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"sort_by field must be price or date_added\"}, \" \")\n\t}\n\n\tsortOrder := formSortOrder(orderParam)\n\tif sortOrder == usecase.ErrOrder {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"order_by field must be asc or desc\"}, \" \")\n\t}\n\n\trooms, err := a.RoomUsecase.GetList(sortField, sortOrder)\n\tif err != nil {\n\t\treturn c.JSONPretty(getStatusCode(err), ResponseError{Message: err.Error()}, \" \")\n\t}\n\n\treturn c.JSONPretty(http.StatusOK, rooms, \" \")\n}", "func (c *RoomClient) Get(ctx context.Context, id int) (*Room, error) {\n\treturn c.Query().Where(room.ID(id)).Only(ctx)\n}", "func (c *RoomClient) Get(ctx context.Context, id int) (*Room, error) {\n\treturn c.Query().Where(room.ID(id)).Only(ctx)\n}", "func GetRooms(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\trows, err := DB.Queryx(`\n\t\tSELECT permissions.*, users.*,\n\t\trooms.id as r_id,\trooms.name AS r_name, rooms.home_id AS r_homeid, rooms.created_at AS r_createdat, rooms.updated_at AS r_updatedat FROM permissions\n\t\tJOIN rooms ON permissions.type_id = rooms.id\n\t\tJOIN users ON rooms.creator_id = users.id\n\t\tWHERE permissions.type=$1 AND permissions.user_id=$2 AND rooms.home_id=$3 AND (permissions.read=true OR permissions.admin=true)\n\t`, \"room\", user.ID, c.Param(\"homeId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS001\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRGRS001\",\n\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t})\n\t}\n\tdefer rows.Close()\n\n\trooms := []roomRes{}\n\tfor rows.Next() {\n\t\tvar permission permissionRoom\n\t\terr := rows.StructScan(&permission)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS002\"}).Errorf(\"%s\", err.Error())\n\t\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\t\tCode: \"CSRGRS002\",\n\t\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t\t})\n\t\t}\n\n\t\trooms = append(rooms, roomRes{\n\t\t\tID: permission.RoomID,\n\t\t\tName: permission.RoomName,\n\t\t\tHomeID: permission.RoomHomeID,\n\t\t\tCreatedAt: permission.RoomCreatedAt,\n\t\t\tUpdatedAt: permission.RoomUpdatedAt,\n\t\t\tCreator: permission.User,\n\t\t\tRead: permission.Permission.Read,\n\t\t\tWrite: permission.Permission.Write,\n\t\t\tManage: permission.Permission.Manage,\n\t\t\tAdmin: permission.Permission.Admin,\n\t\t})\n\t}\n\n\ttotalRooms := strconv.Itoa(len(rooms))\n\tc.Response().Header().Set(\"Content-Range\", \"0-\"+totalRooms+\"/\"+totalRooms)\n\treturn c.JSON(http.StatusOK, rooms)\n}", "func (s *rpcServer) GetRoomInfo(ctx context.Context, in *pb.GetRoomInfoData) (*pb.GetRoomInfoRes, error) {\n\tlogPrefix := \"rpcServer GetRoomInfo\"\n\tlogger := s.nex.GetLogger()\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlogger.LogFile(nxLog.LevelPanic, fmt.Sprintf(\"%s panic:%v\\n\", logPrefix, r))\n\t\t}\n\t}()\n\n\trm := s.nex.GetRoomManager()\n\tr, ok := rm.GetRoom(int(in.RoomID))\n\tif !ok {\n\t\tlogger.LogFile(nxLog.LevelError, fmt.Sprintf(\"%s roomID not found :%d\", logPrefix, int(in.RoomID)))\n\t\treturn nil, errors.New(\"rpcServer GetRoomInfo roomID not found\")\n\t}\n\n\tbrData := s.roomCtrl.GetBootRoundBetMinBetMax(r)\n\tif brData.Err != nil {\n\t\t//error\n\t\treturn nil, brData.Err\n\t}\n\n\t//Get typeData by room type\n\treturn &pb.GetRoomInfoRes{\n\t\tBoot: int64(brData.Boot),\n\t\tRound: brData.Round,\n\t\tRoomID: int64(r.ID()),\n\t\tRoomName: r.Name(),\n\t\tBankerPlayerMin: int64(brData.BetMin),\n\t\tBankerPlayerPairMax: int64(brData.BetMax),\n\t\tTieMin: int64(brData.BetMin),\n\t\tTieMax: int64(brData.BetMax),\n\t\tBankerPlayerPairMin: int64(brData.BetMin),\n\t\tBankerPlayerMax: int64(brData.BetMax),\n\t\tOnline: 999,\n\t\tBetCountDown: 20,\n\t}, nil\n}", "func (s *RoomsNightService) Room(ctx context.Context, id int) (*NightRoomResponsePayload, *Response, error) {\n\treq, err := s.NewRequest(id)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpayload := &NightRoomResponsePayload{}\n\tresp, err := s.client.Do(ctx, req, payload)\n\n\treturn payload, resp, nil\n}", "func printRoom(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.GetRoom(con, args.Get(0))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func getRoomMock(cfg roomMockConfig) roomMock {\n\tvar conf config.WorkerConfig\n\tif _, err := config.LoadConfig(&conf, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tconf.Worker.Library.BasePath = cfg.gamesPath\n\n\tfixEmulators(&conf, cfg.autoGlContext)\n\tl := logger.NewConsole(conf.Worker.Debug, \"w\", false)\n\tif cfg.noLog {\n\t\tlogger.SetGlobalLevel(logger.Disabled)\n\t}\n\n\t// sync cores\n\tif err := remotehttp.CheckCores(conf.Emulator, l); err != nil {\n\t\tl.Error().Err(err).Msg(\"cores sync error\")\n\t}\n\tconf.Encoder.Video.Codec = string(cfg.vCodec)\n\n\troom := NewRoom(cfg.roomName, cfg.game, nil, conf, l)\n\n\tif !cfg.dontStartEmulator {\n\t\troom.StartEmulator()\n\t}\n\n\t// loop-wait the room initialization\n\tvar init sync.WaitGroup\n\tinit.Add(1)\n\twasted := 0\n\tgo func() {\n\t\tsleepDeltaMs := 10\n\t\tfor room.emulator == nil {\n\t\t\ttime.Sleep(time.Duration(sleepDeltaMs) * time.Millisecond)\n\t\t\twasted++\n\t\t\tif wasted > 1000 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tinit.Done()\n\t}()\n\tinit.Wait()\n\treturn roomMock{Room: room, startEmulator: !cfg.dontStartEmulator}\n}", "func (c *RoomdetailClient) Get(ctx context.Context, id int) (*Roomdetail, error) {\n\treturn c.Query().Where(roomdetail.ID(id)).Only(ctx)\n}", "func NewTestRoom(name string) *Room {\n\treturn NewRoom(nil, name, name, \"\")\n}", "func TestGetPartnersWorking(t *testing.T) {\n\tclearTable()\n\tinsertGame()\n\tapitest.New().\n\t\tDebug().\n\t\tHandler(newApp().Router).\n\t\tGet(\"/api/assoc_partners\").\n\t\tExpect(t).\n\t\tStatus(http.StatusOK).\n\t\tEnd()\n}", "func GetRoomsCondition(query map[string]string) (result Rooms, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(Rooms))\n\tqs = RebuildConditions(qs, query)\n\tvar room []Rooms\n\tvar roomId int64\n\tif roomId, err = qs.All(&room); err == nil && roomId > 0 {\n\t\tresult = room[0]\n\t\treturn result, nil\n\t}\n\treturn result, err\n}", "func FakeRoom() *RoomModel {\n\treturn &RoomModel{\n\t\tID: faker.RandomString(5),\n\t\tName: faker.Commerce().ProductName(),\n\t\tPhoto: faker.Avatar().String(),\n\t\tDescription: faker.Lorem().Sentence(5),\n\t}\n}", "func (m *MockBooking) GetByRoomId(arg0 int) ([]*model.Booking, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByRoomId\", arg0)\n\tret0, _ := ret[0].([]*model.Booking)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client *Client) Room() *Room {\n\treturn client.room\n}", "func (m *PlacesRequestBuilder) Room()(*ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.RoomRequestBuilder) {\n return ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.NewRoomRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GoogleChatManager) Room() string {\n\treturn m.room\n}", "func (server *ChatServer) GetRoom(name string) *Room {\n\tserver.lock.Lock()\n\tdefer server.lock.Unlock()\n\tif _, ok := server.Rooms[name]; !ok {\n\t\troom := &Room{\n\t\t\tServer: server,\n\t\t\tName: name,\n\t\t\tlock: new(sync.RWMutex),\n\t\t\tClients: make(map[string]*Client),\n\t\t\tIn: make(chan *Message),\n\t\t}\n\t\tgo room.Listen()\n\t\tserver.Rooms[name] = room\n\t}\n\treturn server.Rooms[name]\n}", "func (m *MockIRoomService) SGetAllRoom() ([]models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SGetAllRoom\")\n\tret0, _ := ret[0].([]models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *postgresDBRepo) GetRoomById(id int) (models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar room models.Room\n\tquery := `select id, room_name, created_at, updated_at from rooms where id = $1`\n\n\trow := m.DB.QueryRowContext(ctx, query, id)\n\terr := row.Scan(&room.ID, &room.RoomName, &room.CreatedAt, &room.UpdatedAt)\n\tif err != nil {\n\t\treturn room, err\n\t}\n\n\treturn room, nil\n}", "func (aec *AddEntryCmd) RequiresRoom() {}", "func GetRoomByRoomID(storage storage.Storage) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar room *models.Room\n\t\tvar roomID string\n\t\tvar err error\n\n\t\tif roomID = c.Param(\"roomid\"); roomID == \"\" {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": \"roomid required\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif room, err = storage.GetRoomByRoomID(roomID); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, room)\n\t}\n}", "func Room() parameter.Parameter {\n\treturn parameter.Single(CUTYPE, \"ROOM\")\n}", "func (inst *Instance) GetPlayerRoom(id int32) (room.Room, error) {\n\tfor _, v := range inst.rooms {\n\t\tif v.Present(id) {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Player does not belong to a room\")\n}", "func GetRoomsByBuilding(building string) ([]accessors.Room, error) {\n\n\tlog.Printf(\"dbo.GetRoomsByBuilding called\")\n\n\tlog.Printf(\"getting all rooms from %v ...\", building)\n\turl := os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\") + \"/buildings/\" + building + \"/rooms\"\n\tvar rooms []accessors.Room\n\terr := GetData(url, &rooms)\n\treturn rooms, err\n}", "func (c *PatientroomClient) Get(ctx context.Context, id int) (*Patientroom, error) {\n\treturn c.Query().Where(patientroom.ID(id)).Only(ctx)\n}", "func GetRoomDataById(id int) (ResultRoomData, bool) {\n\to := orm.NewOrm()\n\tqb, _ := orm.NewQueryBuilder(\"mysql\")\n\n\tsql := qb.Select(\"rooms.*\").From(\"rooms\").\n\t\tWhere(\"room_id = \" + fmt.Sprint(id)).\n\t\tAnd(\"deleted_at = \" + strconv.Itoa(conf.NOT_DELETED))\n\n\tvar tmpRooms []ResultRoomData\n\tnum, tmpErr := o.Raw(sql.String()).QueryRows(&tmpRooms)\n\tif num > 0 && tmpErr == nil {\n\t\treturn tmpRooms[0], false\n\t}\n\treturn ResultRoomData{}, true\n}", "func CreateRoom(w http.ResponseWriter, request *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tswitch request.Method {\n\tcase \"POST\":\n\t\tdata := request.URL.Query()\n\t\tif !createRoomValidator(w, data) {\n\t\t\treturn\n\t\t}\n\t\tvar room roomJSON\n\t\tmaxUsers, _ := strconv.Atoi(data[\"users\"][0])\n\t\ti := 0\n\t\tfor {\n\t\t\ti++\n\t\t\troomID := rand.Intn(99) + 1\n\t\t\tif ok, _ := getRoomByID(roomID, &Rooms); !ok {\n\t\t\t\troom.ID = roomID\n\t\t\t\troom.MaxUsers = maxUsers\n\t\t\t\troom.State = \"joining\"\n\t\t\t\troom.Daytime = \"day\"\n\t\t\t\troom.Mafia = make([]int, 0)\n\t\t\t\troom.Peaceful = make([]int, 0)\n\t\t\t\troom.Alive = make([]int, 0)\n\t\t\t\troom.Killed = make([]int, 0)\n\t\t\t\troom.Jailed = make([]int, 0)\n\t\t\t\tRooms = append(Rooms, room)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i >= 100 {\n\t\t\t\thttp.Error(w, \"503 Game is not available\", http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tresp, err := json.Marshal(&room)\n\t\tif err == nil {\n\t\t\tw.Write(resp)\n\t\t}\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(405)\n\t\tfmt.Fprintf(w, \"Only POST method is allowed\")\n\t}\n}", "func NewGetRoomsParams() *GetRoomsParams {\n\tvar ()\n\treturn &GetRoomsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func TestGet_Unit(t *testing.T) {\n\n\tvar dr Router\n\tdr = &MockedResources{}\n\n\tvar vs Router\n\tvs = &MockedResources{}\n\n\tvar op Operator\n\top = &Istiops{\n\t\tDrRouter: dr,\n\t\tVsRouter: vs,\n\t}\n\n\tirl, err := op.Get(map[string]string{})\n\tassert.Equal(t, router.IstioRouteList{\n\t\tVList: &v1alpha3.VirtualServiceList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.VirtualService{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t\tDList: &v1alpha3.DestinationRuleList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.DestinationRule{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t}, irl)\n\tassert.NoError(t, err)\n}", "func (c *ExaminationroomClient) Get(ctx context.Context, id int) (*Examinationroom, error) {\n\treturn c.Query().Where(examinationroom.ID(id)).Only(ctx)\n}", "func (ns *NSConn) Room(roomName string) *Room {\n\tif ns == nil {\n\t\treturn nil\n\t}\n\n\tns.roomsMutex.RLock()\n\troom := ns.rooms[roomName]\n\tns.roomsMutex.RUnlock()\n\n\treturn room\n}", "func (s *Server) MustJoinRoom(t *testing.T, deployment *docker.Deployment, remoteServer gomatrixserverlib.ServerName, roomID string, userID string) *ServerRoom {\n\tt.Helper()\n\tfedClient := s.FederationClient(deployment)\n\tmakeJoinResp, err := fedClient.MakeJoin(context.Background(), remoteServer, roomID, userID, SupportedRoomVersions())\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: make_join failed: %v\", err)\n\t}\n\troomVer := makeJoinResp.RoomVersion\n\tjoinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), gomatrixserverlib.ServerName(s.ServerName), s.KeyID, s.Priv, roomVer)\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: failed to sign event: %v\", err)\n\t}\n\tsendJoinResp, err := fedClient.SendJoin(context.Background(), gomatrixserverlib.ServerName(remoteServer), joinEvent, roomVer)\n\tif err != nil {\n\t\tt.Fatalf(\"MustJoinRoom: send_join failed: %v\", err)\n\t}\n\n\troom := newRoom(roomVer, roomID)\n\tfor _, ev := range sendJoinResp.StateEvents {\n\t\troom.replaceCurrentState(ev)\n\t}\n\troom.AddEvent(joinEvent)\n\ts.rooms[roomID] = room\n\n\tt.Logf(\"Server.MustJoinRoom joined room ID %s\", roomID)\n\n\treturn room\n}", "func (o *GetRoomsParams) WithTimeout(timeout time.Duration) *GetRoomsParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (c *Mock) SetRoom(r interfaces.Room) {\n\tc.FakeSetRoom(r)\n}", "func (c *OperationroomClient) Get(ctx context.Context, id int) (*Operationroom, error) {\n\treturn c.Query().Where(operationroom.ID(id)).Only(ctx)\n}", "func (rl *roomList) get(name string) *Room {\n\trl.RLock()\n\tdefer rl.RUnlock()\n\tr, ok := rl.list[name]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}", "func (c *Client) ShowRoom(ctx context.Context, path string) (*http.Response, error) {\n\treq, err := c.NewShowRoomRequest(ctx, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Client.Do(ctx, req)\n}", "func MyRoomHandler(w http.ResponseWriter, r *http.Request) {\n\n\tuname := r.URL.Query().Get(\"uname\")\n\tlog.Println(\"User checking room:\" + uname)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tif roomID, ok := paired.Get(uname).(string); ok {\n\t\tw.Write([]byte(`{\"code\":200,\"data\":\"` + roomID + `\"}`))\n\t} else {\n\t\tw.Write([]byte(`{\"code\":200,\"msg\":\"Room not found\", \"data\": null}`))\n\t}\n}", "func (a *API) GetAll(ctx context.Context, param *protos.PaginationParam) (*protos.Rooms, error) {\n\tdatas := []RoomModel{}\n\tcount := uint64(0)\n\tkeyword := strings.ToLower(param.Keyword)\n\terr := a.DB.\n\t\tPreload(\"Members\").\n\t\tWhere(\"LOWER(name) LIKE ?\", \"%\"+keyword+\"%\").\n\t\tOffset(int(param.Offset)).\n\t\tLimit(int(param.Limit)).\n\t\tOrder(\"id\").\n\t\tFind(&datas).\n\t\tError\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = a.DB.\n\t\tModel(&RoomModel{}).\n\t\tWhere(\"LOWER(name) LIKE ?\", \"%\"+keyword+\"%\").\n\t\tCount(&count).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trooms := []*protos.Room{}\n\tfor _, data := range datas {\n\t\troom := RoomModelToProto(&data)\n\t\trooms = append(rooms, room)\n\t}\n\treturn &protos.Rooms{\n\t\tRooms: rooms,\n\t\tCount: count,\n\t}, nil\n}", "func FindRoom(db *gorm.DB, user User) (Room, error) {\n\tvar room Room\n\n\tdb.Where(`((owner_id = ? AND owner_app = ?) OR (guest_id = ? AND guest_app = ?))\n\t\t\t\t\t\t\t\t\tAND active = TRUE`, user.ID, user.App, user.ID, user.App).First(&room)\n\n\tif db.NewRecord(room) {\n\t\treturn Room{}, errors.New(\"no rooms found\")\n\t}\n\n\treturn room, nil\n}", "func (c *constructedSchedule) findAvailableRoom(se ScheduledEvent, excluded []Room) (*Room, bool, error) {\n\tlookup := make(map[RoomID]struct{})\n\tfor _, r := range excluded {\n\t\tlookup[r.ID] = struct{}{}\n\t}\n\n\tfor _, room := range se.Request.PossibleRooms {\n\t\tif _, ignored := lookup[room.ID]; ignored {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, overlaps, err := room.Calendar.Overlap(se.TimeInterval)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\t\tif !overlaps {\n\t\t\treturn &room, true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}", "func (m *MockIRoomService) SGetRoomByID(arg0 string) (models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SGetRoomByID\", arg0)\n\tret0, _ := ret[0].(models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewRoom(name string, u user.Service, logger logger.Service, server *Server) *Room {\n\tlogger.Info(\"cmp\", \"Room\", \"method\", \"NewRoom\", \"msg\", fmt.Sprintf(\"new Room %s Created\", name))\n\t// clientService := client.NewService()\n\treturn &Room{\n\t\tName: name,\n\t\tuserService: u,\n\t\tAddClientChan: make(chan *websocket.Conn, 100),\n\t\tEventDespatcher: NewEventDispatcher(),\n\t\tClients: make(map[string]*Client),\n\t\tlogger: logger,\n\t\tserver: server,\n\t}\n}", "func GetDevicesByRoom(buildingName string, roomName string) (toReturn []accessors.Device, err error) {\n\terr = GetData(os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\")+\"/buildings/\"+buildingName+\"/rooms/\"+roomName+\"/devices\", &toReturn)\n\treturn\n}", "func ListRoomPath() string {\n\n\treturn fmt.Sprintf(\"/api/rooms\")\n}", "func NewRoom() *room {\n\treturn &room{}\n}", "func (io *IO) Room(name string) *Room {\n\tif _, ok := io.rooms[name]; ok {\n\t\treturn io.rooms[name]\n\t}\n\treturn io.NewRoom(name)\n}", "func GetRoomsById(id int) (v *Rooms, err error) {\n\to := orm.NewOrm()\n\tv = &Rooms{Id: id, DeletedAt: conf.NOT_DELETED}\n\tif err = o.Read(v, \"Id\", \"DeletedAt\"); err == nil {\n\t\treturn v, nil\n\t}\n\treturn nil, err\n}", "func (c *BuildingClient) QueryRooms(b *Building) *RoomQuery {\n\tquery := &RoomQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := b.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(building.Table, building.FieldID, id),\n\t\t\tsqlgraph.To(room.Table, room.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, building.RoomsTable, building.RoomsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(b.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func createRoom(gm *gomatrix.Client, roomAliasName string) (roomID string, err error) {\n req := &gomatrix.ReqCreateRoom{\n RoomAliasName: roomAliasName,\n Preset: \"public_chat\",\n }\n\n // Create the room\n resp, err := gm.CreateRoom(req)\n if err != nil {\n return\n }\n\n roomID = resp.RoomID\n return\n}", "func TestGetBook(t *testing.T) {\n\tbooks := book.GetBook()\n\n\tif len(books) < 1 {\n\t\tt.Errorf(\"No books loaded from database.\")\n\t} else {\n\t\tfmt.Println(\"book.go Func GetBook PASS\")\n\t}\n}", "func (rr *ReserveRoom) QueryRoom() *DataRoomQuery {\n\treturn (&ReserveRoomClient{config: rr.config}).QueryRoom(rr)\n}", "func (id DeviceID) Room() string {\n\tsplit := strings.SplitN(string(id), \"-\", 3)\n\tif len(split) != 3 {\n\t\treturn string(id)\n\t}\n\n\treturn split[0] + \"-\" + split[1]\n}", "func newRoom(id string, name string) *Room {\n\tr := &Room{\n\t\tid: id,\n\t\tname: name,\n\t\tmembers: make(map[string]*Member),\n\t}\n\treturn r\n}", "func (db *PgDB) FindRooms(callTime string, maxRetryCount int) ([]*model.Room, error) {\n\tvar rooms []*model.Room\n\terr := db.Model(&rooms).\n\t\tWhere(\"call_time = ?\", callTime).\n\t\tWhere(\"retry_count < ?\", maxRetryCount).\n\t\tSelect()\n\tif err != nil {\n\t\tif err == pg.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn rooms, nil\n}", "func (c *RoomuseClient) QueryRooms(r *Roomuse) *RoomQuery {\n\tquery := &RoomQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := r.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(roomuse.Table, roomuse.FieldID, id),\n\t\t\tsqlgraph.To(room.Table, room.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, roomuse.RoomsTable, roomuse.RoomsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(r.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (r Manager) GetRoomByID(id string) *objets.Room {\n\tif pos := r.GetRoomPosByID(id); pos != -1 {\n\t\treturn &r[pos]\n\t}\n\n\treturn nil\n}", "func (chatRoom ChatRoom) getName() string {\n return chatRoom.name\n}", "func (chatRoom ChatRoom) getGuests() map[string]Guest {\n return chatRoom.guests\n}", "func (ng *NameGenerator) GetRoomName() string {\n\treturn ng.generate(ng.generateRoomName)\n}", "func createRoom(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.CreateRoom(con, args.Get(0), args.Get(1))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func (c *RoomuseClient) Get(ctx context.Context, id int) (*Roomuse, error) {\n\treturn c.Query().Where(roomuse.ID(id)).Only(ctx)\n}", "func (m *mysqlDBRepo) GetRoomByID(id int) (models.Room, error) {\n\t// request last longer 3 second so discard write record into db\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `\n\t\tselect id, room_name, created_at, updated_at from rooms where id = ?\n\t`\n\n\tvar room models.Room\n\terr := m.DB.QueryRowContext(ctx, query, id).Scan(\n\t\t&room.ID,\n\t\t&room.RoomName,\n\t\t&room.CreatedAt,\n\t\t&room.UpdatedAt,\n\t)\n\tif err != nil {\n\t\treturn room, err\n\t}\n\treturn room, nil\n}", "func restGet(room string, client *http.Client, ip string, port string) (*http.Response, error) {\n\treturn client.Get(fmt.Sprintf(\"http://%v/rest/%v\", net.JoinHostPort(ip, port), room))\n}", "func (c *Client) ListRooms(ctx context.Context, req *ListRoomsRequest) (*ListRoomsResponse, error) {\n\tif req == nil {\n\t\treq = &ListRoomsRequest{}\n\t}\n\tresp := &ListRoomsResponse{}\n\treturn resp, c.request(ctx, \"GET\", \"rooms\", req, resp)\n}", "func printRoomDetails(room controllers.Room) {\n\tfmt.Println()\n\tfmt.Println(\"Room Details\")\n\tfmt.Println(\"=====================\")\n\tfmt.Println(\"Capacity :\", room.Capacity)\n\tfmt.Println(\"ID :\", room.ID)\n\tfmt.Println(\"Name :\", room.Name)\n\tfmt.Println(\"Type :\", room.Type)\n\tfmt.Println(\"Occupants -\")\n\tfor index, user := range room.Occupants {\n\t\tfmt.Println(\"\\tCount :\", index+1)\n\t\tfmt.Println(\"\\tFirstName :\", user.FirstName)\n\t\tfmt.Println(\"\\tID :\", user.ID)\n\t\tfmt.Println(\"\\tLastName\", user.LastName)\n\t\tfmt.Println(\"\\tType :\", user.Type)\n\t\tfmt.Println()\n\t}\n\tfmt.Println(\"=====================\")\n\tfmt.Println()\n\n}", "func (a *API) GetByID(ctx context.Context, param *protos.GetRoomParam) (*protos.Room, error) {\n\t// get room detail\n\troom := &RoomModel{}\n\terr := a.DB.Preload(\"Members\").\n\t\tWhere(&RoomModel{ID: param.Id}).\n\t\tFirst(room).Error\n\tif err != nil {\n\t\tif err == gorm.ErrRecordNotFound {\n\t\t\treturn nil, fmt.Errorf(RoomNotFoundError)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn RoomModelToProto(room), nil\n}", "func (s *Server) listRooms(c *client.Client, args []string) {\n\t// validate arg input\n\tif len(args) > 1 {\n\t\tc.Msg(\"please use /createRoom\")\n\t\treturn\n\t}\n\tmsg := \"\"\n\tfor room := range s.rooms {\n\t\tmsg += room + \"\\n\"\n\t}\n\tc.Msg(msg)\n\t// loop over current rooms and write to client availible rooms\n}", "func (lobby *Lobby) createRoom(rs *models.RoomSettings) (room *Room, err error) {\n\n\tid := utils.RandomString(16) // вынести в кофиг\n\troom, err = NewRoom(lobby.config().Field, lobby,\n\t\t&models.Game{Settings: rs}, id)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = lobby.addRoom(room); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func TestClientSpacesSummary(t *testing.T) {\n\tdeployment := Deploy(t, b.BlueprintOneToOneRoom)\n\tdefer deployment.Destroy(t)\n\n\troomNames := make(map[string]string)\n\n\t// create the rooms\n\talice := deployment.Client(t, \"hs1\", \"@alice:hs1\")\n\troot := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Root\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[root] = \"Root\"\n\tr1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R1\",\n\t})\n\troomNames[r1] = \"R1\"\n\tss1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Sub-Space 1\",\n\t\t\"topic\": \"Some topic for sub-space 1\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss1] = \"Sub-Space 1\"\n\tr2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R2\",\n\t})\n\troomNames[r2] = \"R2\"\n\tss2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"SS2\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss2] = \"SS2\"\n\tr3 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R3\",\n\t})\n\troomNames[r3] = \"R3\"\n\t// alice is not joined to R4\n\tbob := deployment.Client(t, \"hs1\", \"@bob:hs1\")\n\tr4 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R4\",\n\t\t\"initial_state\": []map[string]interface{}{\n\t\t\t{\n\t\t\t\t\"type\": \"m.room.history_visibility\",\n\t\t\t\t\"state_key\": \"\",\n\t\t\t\t\"content\": map[string]string{\n\t\t\t\t\t\"history_visibility\": \"world_readable\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\troomNames[r4] = \"R4\"\n\tr5 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R5\",\n\t})\n\n\t// create the links\n\trootToR1 := eventKey(root, r1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\trootToSS1 := eventKey(root, ss1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\trootToR2 := eventKey(root, r2, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\t// Note that this link gets ignored since R2 is not a space.\n\talice.SendEventSynced(t, r2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r5,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\talice.SendEventSynced(t, r2, b.Event{ // parent link\n\t\tType: spaceParentEventType,\n\t\tStateKey: &root,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss1ToSS2 := eventKey(ss1, ss2, spaceChildEventType)\n\talice.SendEventSynced(t, ss1, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR3 := eventKey(ss2, r3, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r3,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR4 := eventKey(ss2, r4, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r4,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\n\t// - Querying the root returns the entire graph\n\t// - Rooms are returned correctly along with the custom fields `room_type`.\n\t// - Events are returned correctly.\n\tt.Run(\"query whole graph\", func(t *testing.T) {\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_rooms_per_space works correctly\n\tt.Run(\"max_rooms_per_space\", func(t *testing.T) {\n\t\t// should omit either R3 or R4 if we start from SS1 because we only return 1 link per room which will be:\n\t\t// SS1 -> SS2\n\t\t// SS2 -> R3,R4 (but only 1 is allowed)\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_rooms_per_space\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", ss1, \"spaces\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\twantItems := []interface{}{\n\t\t\tss1ToSS2,\n\t\t\tss2ToR3, ss2ToR4, // one of these\n\t\t}\n\t\tbody := must.ParseJSON(t, res.Body)\n\t\tgjson.GetBytes(body, \"events\").ForEach(func(_, val gjson.Result) bool {\n\t\t\twantItems = must.CheckOff(t, wantItems, eventKey(val.Get(\"room_id\").Str, val.Get(\"state_key\").Str, val.Get(\"type\").Str))\n\t\t\treturn true\n\t\t})\n\t\tif len(wantItems) != 1 {\n\t\t\tif wantItems[0] != ss2ToR3 && wantItems[0] != ss2ToR4 {\n\t\t\t\tt.Errorf(\"expected fewer events to be returned: %s\", string(body))\n\t\t\t}\n\t\t}\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"max_depth\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_depth\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, ss1,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1, ss1ToSS2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting suggested_only works correctly\n\tt.Run(\"suggested_only\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"suggested_only\", \"true\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"pagination\", func(t *testing.T) {\n\t\t// The initial page should only include Root, R1, SS1, and SS2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"limit\", \"4\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tbody := must.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\t// The following page should include R3, R4, and R2.\n\t\tquery = make(url.Values, 1)\n\t\tquery.Set(\"from\", client.GetJSONFieldStr(t, body, \"next_batch\"))\n\t\tres = alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\tr3, r4, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\tt.Run(\"redact link\", func(t *testing.T) {\n\t\t// Remove the root -> SS1 link\n\t\talice.SendEventSynced(t, root, b.Event{\n\t\t\tType: spaceChildEventType,\n\t\t\tStateKey: &ss1,\n\t\t\tContent: map[string]interface{}{},\n\t\t})\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n}", "func (m *postgresDBRepo) GetAllRooms() ([]models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar rooms []models.Room\n\tquery := `select id, room_name, created_at, updated_at from rooms order by room_name`\n\n\trows, err := m.DB.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn rooms, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\troom := models.Room{}\n\t\terr = rows.Scan(&room.ID, &room.RoomName, &room.CreatedAt, &room.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn rooms, err\n\t\t}\n\t\trooms = append(rooms, room)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn rooms, err\n\t}\n\treturn rooms, nil\n}", "func NewRoom() *Room {\n\tid := xid.New().String()\n\tsecret, err := GenerateRandomString(64)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\troom := &Room{\n\t\tID: id,\n\t\tconnections: make(map[string]*Connection),\n\t\tSecret: secret,\n\t}\n\treturn room\n}", "func (e *Event) Room() *Room {\n\treturn e.room\n}", "func (r GetRoomRequest) Send() (*GetRoomOutput, error) {\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*GetRoomOutput), nil\n}", "func (cs *ChatServer) Rooms() int {\n\treturn cs.rooms\n}", "func (m *MemoryRoomStorage) Get(id int) (rooms.Room, error) {\n\tvar room rooms.Room\n\n\tfor _, r := range m.rooms {\n\t\tif r.ID == id {\n\t\t\treturn r, nil\n\t\t}\n\t}\n\n\treturn room, rooms.ErrNotFound\n}", "func getProgrammingsTest(e *httpexpect.Expect, t *testing.T) {\n\ttestCases := []testCase{\n\t\tnotLoggedTestCase,\n\t\t{\n\t\t\tToken: testCtx.Admin.Token,\n\t\t\tParam: \"2018\",\n\t\t\tStatus: http.StatusOK,\n\t\t\tBodyContains: []string{\"Programmings\", `\"PrevCommitmentTotal\":96730644861`},\n\t\t\tCountItemName: `\"id\"`,\n\t\t\tArraySize: 626},\n\t}\n\tf := func(tc testCase) *httpexpect.Response {\n\t\treturn e.GET(\"/api/programmings\").WithHeader(\"Authorization\", \"Bearer \"+tc.Token).\n\t\t\tWithQuery(\"year\", tc.Param).Expect()\n\t}\n\tfor _, r := range chkTestCases(testCases, f, \"GetProgrammings\") {\n\t\tt.Error(r)\n\t}\n}", "func GetAllRooms(query map[string]string, fields []string, sortby []string, order []string,\n\toffset int64, limit int64) (ml []interface{}, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(Rooms))\n\t// query k=v\n\tqs = RebuildConditions(qs, query)\n\t// order by:\n\tqs, errorMq := MakeOrderForQuery(qs, sortby, order)\n\n\tif errorMq != nil {\n\t\treturn ml, errorMq\n\t}\n\n\tvar l []Rooms\n\tif _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {\n\t\tvar result1 []interface{}\n\t\tfor _, v := range l {\n\t\t\tresult1 = append(result1, v)\n\t\t}\n\t\t//filter data by using array field\n\t\tml, err := FilterResultByField(fields, result1)\n\t\treturn ml, err\n\t}\n\treturn nil, err\n}", "func ListRooms() ([]*Room, error) {\n\trows, err := DB.Model(&Room{}).Rows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rooms []*Room\n\tfor rows.Next() {\n\t\tvar room Room\n\t\tDB.ScanRows(rows, &room)\n\t\trooms = append(rooms, &room)\n\t}\n\n\treturn rooms, nil\n}", "func TestListMessages(t *testing.T) {\n\ts = getSpark(t)\n\tif len(allRooms) < 1 {\n\t\tgetAllRooms(t)\n\t}\n\n\tuv := url.Values{}\n\tfmt.Println(\"Title: \", allRooms[0].Title)\n\tuv.Add(\"roomId\", allRooms[0].Id)\n\tallMessages, err := s.ListMessages(&uv)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(allMessages) < 1 {\n\t\tt.Fatal(\"Expected there to be at least one message in the room\")\n\n\t}\n\n\t// test Get messages\n\tfirstMessage := allMessages[0]\n\t_, err = s.GetMessage(firstMessage.Id)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (s *BBRequestTestSuite) TestGetPatient() {\n\tp, err := s.bbClient.GetPatient(\"012345\", \"543210\", \"A0000\", \"\", now)\n\tassert.Nil(s.T(), err)\n\tassert.Equal(s.T(), 1, len(p.Entries))\n\tassert.Equal(s.T(), \"20000000000001\", p.Entries[0][\"resource\"].(map[string]interface{})[\"id\"])\n}", "func NewRoom() *Room {\n\treturn &Room{\n\t\tgroup: pitaya.NewGroup(\"room\"),\n\t\tstats: &stats{},\n\t}\n}", "func (m *PrinterLocation) GetRoomName()(*string) {\n val, err := m.GetBackingStore().Get(\"roomName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}" ]
[ "0.7378574", "0.6891477", "0.6777567", "0.67103434", "0.6702325", "0.661111", "0.65437686", "0.6481392", "0.64439714", "0.64006823", "0.6385708", "0.63080615", "0.6284031", "0.6278071", "0.62430644", "0.6231621", "0.61557883", "0.6125862", "0.6125862", "0.6103171", "0.6053602", "0.60253656", "0.59328747", "0.5902286", "0.586022", "0.5802138", "0.5755588", "0.5752744", "0.57310444", "0.5703284", "0.5689695", "0.5683605", "0.5661596", "0.56468743", "0.56387895", "0.5601516", "0.55876124", "0.5572959", "0.55437243", "0.55314493", "0.5474351", "0.547399", "0.54476106", "0.5438263", "0.54008013", "0.53981453", "0.53853166", "0.5383862", "0.5383767", "0.53598166", "0.5353799", "0.5338378", "0.53374773", "0.5312077", "0.5301692", "0.53004414", "0.5300343", "0.5296079", "0.5291801", "0.52861685", "0.52807367", "0.52747273", "0.5257961", "0.5254248", "0.52532184", "0.5247881", "0.52468044", "0.52393395", "0.5236155", "0.52186644", "0.5212776", "0.52119195", "0.5209486", "0.52083516", "0.5203834", "0.519425", "0.518935", "0.51884097", "0.51816976", "0.51770854", "0.5174251", "0.5140051", "0.5136468", "0.51256585", "0.5112212", "0.51105213", "0.5110226", "0.510119", "0.5086647", "0.50852585", "0.5080153", "0.507127", "0.50616926", "0.50554967", "0.50518125", "0.5051184", "0.5041986", "0.5040953", "0.5035531", "0.50235754" ]
0.78954643
0
TestGetRoomAllocations tests the functionality of GetRoomAllocations
func TestGetRoomAllocations(t *testing.T) { var ( err error user User room Room rooms []Room fetchRoom = func(fname, lname, userType, rmName, rmType string) { room, err = CreateRoom(con, rmName, rmType) So(err, ShouldBeNil) So(room.ID, ShouldNotBeBlank) user, err = AddPerson(con, fname, lname, userType, room.Name, "") So(err, ShouldBeNil) So(user, ShouldNotResemble, (User{})) rooms, err = GetRoomAllocations(con) } ) Convey("Tests for GetRoomAllocations ", t, func() { Convey("GetRoomAllocations should return a slice of Room with all the correct values present and an error", func() { fetchRoom("Garbrielle", "Wanjigi", "fellow", "Timbuktu", "office") So(err, ShouldBeNil) for _, room = range rooms { So(room.Capacity, ShouldEqual, 6) So(room.ID, ShouldNotBeBlank) So(room.Name, ShouldEqual, "Timbuktu") So(room.Occupants, ShouldNotBeEmpty) So(room.Type, ShouldNotBeBlank) So(room.Occupants[0].FirstName, ShouldEqual, "Garbrielle") So(room.Occupants[0].ID, ShouldNotBeBlank) So(room.Occupants[0].LastName, ShouldEqual, "Wanjigi") So(room.Occupants[0].Type, ShouldEqual, "fellow") } }) Convey("Print the successfully created Room and User", func() { fetchRoom("Ashley", "Wanjigi", "fellow", "Golang", "office") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printAllocations(c *cli.Context) error {\n\tvar rooms, err = controllers.GetRoomAllocations(con)\n\n\texitOnError(err)\n\n\tfor _, room := range rooms {\n\t\tprintRoomDetails(room)\n\t}\n\n\treturn nil\n}", "func TestGetRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = GetRoom(con, rmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoom \", t, func() {\n\t\tConvey(\"GetRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Joshua\", \"Mwaniki\", \"staff\", \"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Valhalla\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Joshua\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Mwaniki\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"staff\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"James\", \"Kaberia\", \"staff\", \"Pretoria\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestGetRoomDetails(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tusers []models.User\n\t\trm models.Room\n\t\troom Room\n\n\t\tgetRoomDetails = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\t_, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\trm, users, err = getRoomDetails(con, rmName, rmType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for getRoomDetails \", t, func() {\n\t\tConvey(\"getRoomDetaiils should return the room, a slice of user and an error \", func() {\n\t\t\tgetRoomDetails(\"Daniel\", \"Ikigai\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(rm.Capacity, ShouldEqual, 6)\n\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\tSo(rm.Name, ShouldEqual, \"Tsavoo\")\n\t\t\tSo(rm.Type, ShouldEqual, \"office\")\n\n\t\t\tSo(users[0].FirstName, ShouldEqual, \"Daniel\")\n\t\t\tSo(users[0].ID, ShouldNotBeBlank)\n\t\t\tSo(users[0].LastName, ShouldEqual, \"Ikigai\")\n\t\t\tSo(users[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tgetRoomDetails(\"Christine\", \"J\", \"fellow\", \"Tsavoo\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestGetUnallocatedPeople(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\tusers []User\n\n\t\tfetchUsers = func(fname, lname, userType string) {\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, \"\", \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\tusers, err = GetUnallocatedPeople(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetUnallocatedPeople \", t, func() {\n\t\tConvey(\"GetUnallocatedPeople should return a slice of User with all the correct values present and an error\", func() {\n\t\t\tfetchUsers(\"David\", \"Holmes\", \"staff\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, user = range users {\n\t\t\t\tSo(user.FirstName, ShouldEqual, \"David\")\n\t\t\t\tSo(user.ID, ShouldNotBeBlank)\n\t\t\t\tSo(user.LastName, ShouldEqual, \"Holmes\")\n\t\t\t\tSo(user.LivingSpace, ShouldResemble, (User{}))\n\t\t\t\tSo(user.Office, ShouldResemble, (User{}))\n\t\t\t\tSo(user.Type, ShouldEqual, \"staff\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchUsers(\"Mark\", \"Oyaboade\", \"fellow\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func GetRooms(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\trows, err := DB.Queryx(`\n\t\tSELECT permissions.*, users.*,\n\t\trooms.id as r_id,\trooms.name AS r_name, rooms.home_id AS r_homeid, rooms.created_at AS r_createdat, rooms.updated_at AS r_updatedat FROM permissions\n\t\tJOIN rooms ON permissions.type_id = rooms.id\n\t\tJOIN users ON rooms.creator_id = users.id\n\t\tWHERE permissions.type=$1 AND permissions.user_id=$2 AND rooms.home_id=$3 AND (permissions.read=true OR permissions.admin=true)\n\t`, \"room\", user.ID, c.Param(\"homeId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS001\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRGRS001\",\n\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t})\n\t}\n\tdefer rows.Close()\n\n\trooms := []roomRes{}\n\tfor rows.Next() {\n\t\tvar permission permissionRoom\n\t\terr := rows.StructScan(&permission)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS002\"}).Errorf(\"%s\", err.Error())\n\t\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\t\tCode: \"CSRGRS002\",\n\t\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t\t})\n\t\t}\n\n\t\trooms = append(rooms, roomRes{\n\t\t\tID: permission.RoomID,\n\t\t\tName: permission.RoomName,\n\t\t\tHomeID: permission.RoomHomeID,\n\t\t\tCreatedAt: permission.RoomCreatedAt,\n\t\t\tUpdatedAt: permission.RoomUpdatedAt,\n\t\t\tCreator: permission.User,\n\t\t\tRead: permission.Permission.Read,\n\t\t\tWrite: permission.Permission.Write,\n\t\t\tManage: permission.Permission.Manage,\n\t\t\tAdmin: permission.Permission.Admin,\n\t\t})\n\t}\n\n\ttotalRooms := strconv.Itoa(len(rooms))\n\tc.Response().Header().Set(\"Content-Range\", \"0-\"+totalRooms+\"/\"+totalRooms)\n\treturn c.JSON(http.StatusOK, rooms)\n}", "func TestAllocGarbageCollector_MakeRoomFor_MaxAllocs(t *testing.T) {\n\tci.Parallel(t)\n\n\tconst maxAllocs = 6\n\trequire := require.New(t)\n\n\tserver, serverAddr, cleanupS := testServer(t, nil)\n\tdefer cleanupS()\n\ttestutil.WaitForLeader(t, server.RPC)\n\n\tclient, cleanup := TestClient(t, func(c *config.Config) {\n\t\tc.GCMaxAllocs = maxAllocs\n\t\tc.GCDiskUsageThreshold = 100\n\t\tc.GCInodeUsageThreshold = 100\n\t\tc.GCParallelDestroys = 1\n\t\tc.GCInterval = time.Hour\n\t\tc.RPCHandler = server\n\t\tc.Servers = []string{serverAddr}\n\t\tc.ConsulConfig.ClientAutoJoin = new(bool)\n\t})\n\tdefer cleanup()\n\twaitTilNodeReady(client, t)\n\n\tjob := mock.Job()\n\tjob.TaskGroups[0].Count = 1\n\tjob.TaskGroups[0].Tasks[0].Driver = \"mock_driver\"\n\tjob.TaskGroups[0].Tasks[0].Config = map[string]interface{}{\n\t\t\"run_for\": \"30s\",\n\t}\n\n\tindex := uint64(98)\n\tnextIndex := func() uint64 {\n\t\tindex++\n\t\treturn index\n\t}\n\n\tupsertJobFn := func(server *nomad.Server, j *structs.Job) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertJob(structs.MsgTypeTestSetup, nextIndex(), j))\n\t\trequire.NoError(state.UpsertJobSummary(nextIndex(), mock.JobSummary(j.ID)))\n\t}\n\n\t// Insert the Job\n\tupsertJobFn(server, job)\n\n\tupsertAllocFn := func(server *nomad.Server, a *structs.Allocation) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertAllocs(structs.MsgTypeTestSetup, nextIndex(), []*structs.Allocation{a}))\n\t}\n\n\tupsertNewAllocFn := func(server *nomad.Server, j *structs.Job) *structs.Allocation {\n\t\talloc := mock.Alloc()\n\t\talloc.Job = j\n\t\talloc.JobID = j.ID\n\t\talloc.NodeID = client.NodeID()\n\n\t\tupsertAllocFn(server, alloc)\n\n\t\treturn alloc.Copy()\n\t}\n\n\tvar allocations []*structs.Allocation\n\n\t// Fill the node with allocations\n\tfor i := 0; i < maxAllocs; i++ {\n\t\tallocations = append(allocations, upsertNewAllocFn(server, job))\n\t}\n\n\t// Wait until the allocations are ready\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := len(client.getAllocRunners())\n\n\t\treturn ar == maxAllocs, fmt.Errorf(\"Expected %d allocs, got %d\", maxAllocs, ar)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not start: %v\", err)\n\t})\n\n\t// Mark the first three as terminal\n\tfor i := 0; i < 3; i++ {\n\t\tallocations[i].DesiredStatus = structs.AllocDesiredStatusStop\n\t\tupsertAllocFn(server, allocations[i].Copy())\n\t}\n\n\t// Wait until the allocations are stopped\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tstopped := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.Alloc().TerminalStatus() {\n\t\t\t\tstopped++\n\t\t\t}\n\t\t}\n\n\t\treturn stopped == 3, fmt.Errorf(\"Expected %d terminal allocs, got %d\", 3, stopped)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not terminate: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// A single allocation should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 1, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 1, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// 2 allocations should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 2, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 2, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// check that all 8 get run eventually\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tif len(ar) != 8 {\n\t\t\treturn false, fmt.Errorf(\"expected 8 ARs, found %d: %v\", len(ar), ar)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(err)\n\t})\n}", "func TestClientSpacesSummary(t *testing.T) {\n\tdeployment := Deploy(t, b.BlueprintOneToOneRoom)\n\tdefer deployment.Destroy(t)\n\n\troomNames := make(map[string]string)\n\n\t// create the rooms\n\talice := deployment.Client(t, \"hs1\", \"@alice:hs1\")\n\troot := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Root\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[root] = \"Root\"\n\tr1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R1\",\n\t})\n\troomNames[r1] = \"R1\"\n\tss1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Sub-Space 1\",\n\t\t\"topic\": \"Some topic for sub-space 1\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss1] = \"Sub-Space 1\"\n\tr2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R2\",\n\t})\n\troomNames[r2] = \"R2\"\n\tss2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"SS2\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss2] = \"SS2\"\n\tr3 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R3\",\n\t})\n\troomNames[r3] = \"R3\"\n\t// alice is not joined to R4\n\tbob := deployment.Client(t, \"hs1\", \"@bob:hs1\")\n\tr4 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R4\",\n\t\t\"initial_state\": []map[string]interface{}{\n\t\t\t{\n\t\t\t\t\"type\": \"m.room.history_visibility\",\n\t\t\t\t\"state_key\": \"\",\n\t\t\t\t\"content\": map[string]string{\n\t\t\t\t\t\"history_visibility\": \"world_readable\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\troomNames[r4] = \"R4\"\n\tr5 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R5\",\n\t})\n\n\t// create the links\n\trootToR1 := eventKey(root, r1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\trootToSS1 := eventKey(root, ss1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\trootToR2 := eventKey(root, r2, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\t// Note that this link gets ignored since R2 is not a space.\n\talice.SendEventSynced(t, r2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r5,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\talice.SendEventSynced(t, r2, b.Event{ // parent link\n\t\tType: spaceParentEventType,\n\t\tStateKey: &root,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss1ToSS2 := eventKey(ss1, ss2, spaceChildEventType)\n\talice.SendEventSynced(t, ss1, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR3 := eventKey(ss2, r3, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r3,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR4 := eventKey(ss2, r4, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r4,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\n\t// - Querying the root returns the entire graph\n\t// - Rooms are returned correctly along with the custom fields `room_type`.\n\t// - Events are returned correctly.\n\tt.Run(\"query whole graph\", func(t *testing.T) {\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_rooms_per_space works correctly\n\tt.Run(\"max_rooms_per_space\", func(t *testing.T) {\n\t\t// should omit either R3 or R4 if we start from SS1 because we only return 1 link per room which will be:\n\t\t// SS1 -> SS2\n\t\t// SS2 -> R3,R4 (but only 1 is allowed)\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_rooms_per_space\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", ss1, \"spaces\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\twantItems := []interface{}{\n\t\t\tss1ToSS2,\n\t\t\tss2ToR3, ss2ToR4, // one of these\n\t\t}\n\t\tbody := must.ParseJSON(t, res.Body)\n\t\tgjson.GetBytes(body, \"events\").ForEach(func(_, val gjson.Result) bool {\n\t\t\twantItems = must.CheckOff(t, wantItems, eventKey(val.Get(\"room_id\").Str, val.Get(\"state_key\").Str, val.Get(\"type\").Str))\n\t\t\treturn true\n\t\t})\n\t\tif len(wantItems) != 1 {\n\t\t\tif wantItems[0] != ss2ToR3 && wantItems[0] != ss2ToR4 {\n\t\t\t\tt.Errorf(\"expected fewer events to be returned: %s\", string(body))\n\t\t\t}\n\t\t}\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"max_depth\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_depth\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, ss1,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1, ss1ToSS2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting suggested_only works correctly\n\tt.Run(\"suggested_only\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"suggested_only\", \"true\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"pagination\", func(t *testing.T) {\n\t\t// The initial page should only include Root, R1, SS1, and SS2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"limit\", \"4\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tbody := must.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\t// The following page should include R3, R4, and R2.\n\t\tquery = make(url.Values, 1)\n\t\tquery.Set(\"from\", client.GetJSONFieldStr(t, body, \"next_batch\"))\n\t\tres = alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\tr3, r4, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\tt.Run(\"redact link\", func(t *testing.T) {\n\t\t// Remove the root -> SS1 link\n\t\talice.SendEventSynced(t, root, b.Event{\n\t\t\tType: spaceChildEventType,\n\t\t\tStateKey: &ss1,\n\t\t\tContent: map[string]interface{}{},\n\t\t})\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n}", "func roomToTestRoom(room *level.RoomData, inputLevel level.Level) Room {\n\treturn Room{\n\t\tType: \"room\",\n\t\tOrigin: Point{\n\t\t\troom.TopLeft.Row,\n\t\t\troom.TopLeft.Col,\n\t\t},\n\t\tBounds: Bounds{\n\t\t\tRows: room.Size.Row,\n\t\t\tColumns: room.Size.Col,\n\t\t},\n\t\tLayout: TilesToArray(inputLevel.GetTiles(room.TopLeft, room.Size)),\n\t}\n}", "func TestCreateRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\troom Room\n\n\t\tcreateRoom = func(name, roomType string) {\n\t\t\troom, err = CreateRoom(con, name, roomType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for CreateRoom \", t, func() {\n\t\tConvey(\"CreateRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tcreateRoom(\"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants, ShouldBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tcreateRoom(\"Golang\", \"livingspace\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestAddRoom(t *testing.T) {\n\t// first create a new controller\n\tapi := NewRoomApiController()\n\troomrouter := NewRouter(api)\n\ttestserver := httptest.NewServer(roomrouter)\n\tdefer testserver.Close()\n\n\t// api configuration\n\tapiConfig := roomapi.NewConfiguration()\n\tapiConfig.HTTPClient = testserver.Client()\n\ttesturl, err := url.Parse(testserver.URL)\n\tif err != nil {\n\t\tt.Errorf(\"error parsing url from test server: %s\", err)\n\t\treturn\n\t}\n\tapiConfig.Host = testurl.Host\n\n\t// create first client\n\tapic := roomapi.NewAPIClient(apiConfig)\n\tbackground := context.Background()\n\tretRoom, _, err := apic.RoomApi.AddRoom(background)\n\tif err != nil {\n\t\tt.Errorf(\"error adding room: %s\", err)\n\t\treturn\n\t}\n\tt.Logf(\"room id: %d, room id str: %s\\n\", retRoom.Id, retRoom.Code)\n}", "func (u teamHandler) findAllocations(req *restful.Request, resp *restful.Response) {\n\thandleErrors(req, resp, func() error {\n\t\tteam := req.PathParameter(\"team\")\n\t\tassigned := req.QueryParameter(\"assigned\")\n\t\tkind := req.QueryParameter(\"kind\")\n\t\tgroup := req.QueryParameter(\"group\")\n\n\t\tif assigned == \"false\" {\n\t\t\tlist, err := u.Teams().Team(team).Allocations().List(req.Request.Context())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn resp.WriteHeaderAndEntity(http.StatusOK, list)\n\t\t}\n\n\t\tlist, err := u.Teams().Team(team).Allocations().ListAllocationsAssigned(req.Request.Context())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// @step: perform any filtering required\n\t\tif kind != \"\" || group != \"\" {\n\t\t\tvar filtered []configv1.Allocation\n\n\t\t\tfor _, x := range list.Items {\n\t\t\t\tswitch {\n\t\t\t\tcase kind != \"\" && kind != x.Spec.Resource.Kind:\n\t\t\t\t\tcontinue\n\t\t\t\tcase group != \"\" && group != x.Spec.Resource.Group:\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfiltered = append(filtered, x)\n\t\t\t}\n\t\t\tlist.Items = filtered\n\t\t}\n\n\t\treturn resp.WriteHeaderAndEntity(http.StatusOK, list)\n\t})\n}", "func getRooms(api *slack.Client) map[string]string {\n\trooms := make(map[string]string)\n\t// get public channels\n\tchannels, _ := api.GetChannels(true)\n\tfor _, channel := range channels {\n\t\trooms[channel.Name] = channel.ID\n\t}\n\t// get private channels\n\tgroups, _ := api.GetGroups(true)\n\tfor _, group := range groups {\n\t\trooms[group.Name] = group.ID\n\t}\n\treturn rooms\n}", "func GetRoomsByBuilding(building string) ([]accessors.Room, error) {\n\n\tlog.Printf(\"dbo.GetRoomsByBuilding called\")\n\n\tlog.Printf(\"getting all rooms from %v ...\", building)\n\turl := os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\") + \"/buildings/\" + building + \"/rooms\"\n\tvar rooms []accessors.Room\n\terr := GetData(url, &rooms)\n\treturn rooms, err\n}", "func (m *MemoryRoomStorage) GetAll() []rooms.Room {\n\treturn m.rooms\n}", "func (m *MockFullNode) StateGetAllocations(arg0 context.Context, arg1 address.Address, arg2 types0.TipSetKey) (map[verifreg.AllocationId]verifreg.Allocation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateGetAllocations\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(map[verifreg.AllocationId]verifreg.Allocation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetDevicesByRoom(buildingName string, roomName string) (toReturn []accessors.Device, err error) {\n\terr = GetData(os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\")+\"/buildings/\"+buildingName+\"/rooms/\"+roomName+\"/devices\", &toReturn)\n\treturn\n}", "func (m *MockIRoomService) SGetAllRoom() ([]models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SGetAllRoom\")\n\tret0, _ := ret[0].([]models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetAllRooms(storage storage.Storage) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar rooms []*models.Room\n\t\tvar err error\n\n\t\trooms, err = storage.GetAllRooms()\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"rooms\": rooms,\n\t\t})\n\t}\n}", "func (m *MockPoolRegistry) GetAllocationsForVolume(volume registry.VolumeName) ([]registry.BrickAllocation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllocationsForVolume\", volume)\n\tret0, _ := ret[0].([]registry.BrickAllocation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *API) GetAll(ctx context.Context, param *protos.PaginationParam) (*protos.Rooms, error) {\n\tdatas := []RoomModel{}\n\tcount := uint64(0)\n\tkeyword := strings.ToLower(param.Keyword)\n\terr := a.DB.\n\t\tPreload(\"Members\").\n\t\tWhere(\"LOWER(name) LIKE ?\", \"%\"+keyword+\"%\").\n\t\tOffset(int(param.Offset)).\n\t\tLimit(int(param.Limit)).\n\t\tOrder(\"id\").\n\t\tFind(&datas).\n\t\tError\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = a.DB.\n\t\tModel(&RoomModel{}).\n\t\tWhere(\"LOWER(name) LIKE ?\", \"%\"+keyword+\"%\").\n\t\tCount(&count).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trooms := []*protos.Room{}\n\tfor _, data := range datas {\n\t\troom := RoomModelToProto(&data)\n\t\trooms = append(rooms, room)\n\t}\n\treturn &protos.Rooms{\n\t\tRooms: rooms,\n\t\tCount: count,\n\t}, nil\n}", "func (c *Mock) Room() interfaces.Room {\n\treturn c.FakeRoom()\n}", "func TestGetLoots(t *testing.T) {\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tloots, err := db.GetLoots(344178872)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif loots[0].Price != 0.12 || loots[0].Amout != \"100002.0\" || loots[0].Coin != \"MNT\" {\n\t\tt.Errorf(\"I wanna see price = 1000, but %f, amount = 1000, but %s, coin = MNT, but %s\", loots[0].Price, loots[0].Amout, loots[0].Coin)\n\t}\n}", "func TestGetLedgers(t *testing.T) {\n\tt.Parallel()\n\targs := GetLedgersOptions{Start: \"LRUHXI-IWECY-K4JYGO\", End: \"L5NIY7-JZQJD-3J4M2V\", Ofs: 15}\n\t_, err := k.GetLedgers(context.Background(), args)\n\tif err == nil {\n\t\tt.Error(\"GetLedgers() Expected error\")\n\t}\n}", "func TestReallocatePerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, oldRmName, newRmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, oldRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom, err = CreateRoom(con, newRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = ReallocatePerson(con, fname, lname, newRmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for ReallocatePerson \", t, func() {\n\t\tConvey(\"ReallocatePerson should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"James\", \"Bond\", \"fellow\", \"Valhalla\", \"Mogadishu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Mogadishu\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"James\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Bond\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"TheSecret\", \"Coder\", \"fellow\", \"Narnia\", \"Shell\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\t// So(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (m *MockPoolRegistry) GetAllocationsForHost(hostname string) ([]registry.BrickAllocation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllocationsForHost\", hostname)\n\tret0, _ := ret[0].([]registry.BrickAllocation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mysqlDBRepo) SearchAvailabilityForAllRooms(start, end time.Time) ([]models.Room, error) {\n\t// request last longer 3 second so discard write record into db\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar rooms []models.Room\n\n\tquery := `select\n\t\t\t\tr.id, r.room_name\n\t\t\tfrom\n\t\t\t\trooms as r\n\t\t\twhere\n\t\t\t\tr.id not in \n\t\t\t\t(select rr.room_id from room_restrictions as rr where ? < rr.end_date and ? > rr.start_date)`\n\n\trows, err := m.DB.QueryContext(ctx, query, start, end)\n\tif err != nil {\n\t\treturn rooms, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar room models.Room\n\t\terr := rows.Scan(\n\t\t\t&room.ID,\n\t\t\t&room.RoomName,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn rooms, err\n\t\t}\n\t\trooms = append(rooms, room)\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn rooms, err\n\t}\n\n\treturn rooms, nil\n}", "func (a *RoomHandler) GetRoomList(c echo.Context) error {\n\tsortParam := c.QueryParam(\"sort_by\")\n\torderParam := c.QueryParam(\"order_by\")\n\n\tsortField := formSortField(sortParam)\n\tif sortField == usecase.ErrField {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"sort_by field must be price or date_added\"}, \" \")\n\t}\n\n\tsortOrder := formSortOrder(orderParam)\n\tif sortOrder == usecase.ErrOrder {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"order_by field must be asc or desc\"}, \" \")\n\t}\n\n\trooms, err := a.RoomUsecase.GetList(sortField, sortOrder)\n\tif err != nil {\n\t\treturn c.JSONPretty(getStatusCode(err), ResponseError{Message: err.Error()}, \" \")\n\t}\n\n\treturn c.JSONPretty(http.StatusOK, rooms, \" \")\n}", "func GetAllRooms(query map[string]string, fields []string, sortby []string, order []string,\n\toffset int64, limit int64) (ml []interface{}, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(Rooms))\n\t// query k=v\n\tqs = RebuildConditions(qs, query)\n\t// order by:\n\tqs, errorMq := MakeOrderForQuery(qs, sortby, order)\n\n\tif errorMq != nil {\n\t\treturn ml, errorMq\n\t}\n\n\tvar l []Rooms\n\tif _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {\n\t\tvar result1 []interface{}\n\t\tfor _, v := range l {\n\t\t\tresult1 = append(result1, v)\n\t\t}\n\t\t//filter data by using array field\n\t\tml, err := FilterResultByField(fields, result1)\n\t\treturn ml, err\n\t}\n\treturn nil, err\n}", "func TestGetPartnersWorking(t *testing.T) {\n\tclearTable()\n\tinsertGame()\n\tapitest.New().\n\t\tDebug().\n\t\tHandler(newApp().Router).\n\t\tGet(\"/api/assoc_partners\").\n\t\tExpect(t).\n\t\tStatus(http.StatusOK).\n\t\tEnd()\n}", "func TestGetPeople(t *testing.T) {\n\tpeople := GetPeople()\n\tif len(people) != 0 {\n\t\tt.Errorf(\"Expected len(GetPeople()) = %d, got: %d\", 0, len(people))\n\t}\n}", "func (d *DAO) Rooms() RoomDao {\n\treturn d.roomDao\n}", "func hotelsRooms(response http.ResponseWriter, request *http.Request){\n\thotelsRoom := FindAllHotelsRoom()\n\tresult, err := json.Marshal(hotelsRoom)\n\tif err != nil {\n\t\thttp.Error(response, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\tresponse.Write(result)\n}", "func TestEmpty(t *testing.T) {\n\t_, storage, _, _, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := storage.Allocate(31000); !strings.Contains(err.Error(), \"cannot allocate resources of type servicenodeportallocations at this time\") {\n\t\tt.Fatal(err)\n\t}\n}", "func AddRoom(xxStart, yyStart, xxCount, yyCount int) {\n\taddRoom(xxStart, yyStart, xxCount, yyCount)\n}", "func (m *PlacesRequestBuilder) Room()(*ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.RoomRequestBuilder) {\n return ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.NewRoomRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func RenderRooms() *Manager {\n\tif _, err := os.Stat(\"./public/res/temp\"); !os.IsNotExist(err) {\n\t\terr = os.RemoveAll(\"./public/res/temp\")\n\t\tutils.CheckPanic(&err)\n\t}\n\n\terr := os.MkdirAll(\"./public/res/temp\", 0777)\n\n\tutils.CheckPanic(&err)\n\n\trs := make(Manager, 0)\n\n\tdatabase.Conn.ForEachRoom(func(id int, r *objets.Room) (moveOn bool) {\n\t\te := render(r)\n\n\t\tif e != nil {\n\t\t\tlog.Manager.GetLogLevel(\"docker\").AppendLog(e.Error())\n\t\t}\n\n\t\trs = append(rs, *r)\n\n\t\treturn true\n\t})\n\n\treturn &rs\n}", "func printRoomDetails(room controllers.Room) {\n\tfmt.Println()\n\tfmt.Println(\"Room Details\")\n\tfmt.Println(\"=====================\")\n\tfmt.Println(\"Capacity :\", room.Capacity)\n\tfmt.Println(\"ID :\", room.ID)\n\tfmt.Println(\"Name :\", room.Name)\n\tfmt.Println(\"Type :\", room.Type)\n\tfmt.Println(\"Occupants -\")\n\tfor index, user := range room.Occupants {\n\t\tfmt.Println(\"\\tCount :\", index+1)\n\t\tfmt.Println(\"\\tFirstName :\", user.FirstName)\n\t\tfmt.Println(\"\\tID :\", user.ID)\n\t\tfmt.Println(\"\\tLastName\", user.LastName)\n\t\tfmt.Println(\"\\tType :\", user.Type)\n\t\tfmt.Println()\n\t}\n\tfmt.Println(\"=====================\")\n\tfmt.Println()\n\n}", "func (s *stateManager) Allocations() ([]*Allocation, error) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\tdefer cancel()\n\n\topts := []clientv3.OpOption{\n\t\tclientv3.WithPrefix(),\n\t}\n\n\tkey := fmt.Sprintf(\"%s/allocations\", etcdPrefix)\n\tgr, err := s.kv.Get(ctx, key, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallocations := make([]*Allocation, gr.Count)\n\tfor i, item := range gr.Kvs {\n\t\tallocations[i], err = decode(item.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn allocations, nil\n}", "func (suite *TestAgentSuite) TestListAgents(c *C) {\n\ttestCases := []*struct {\n\t\tquery *nqmModel.AgentQuery\n\t\tpageSize int32\n\t\tpagePosition int32\n\t\texpectedCountOfCurrentPage int\n\t\texpectedCountOfAll int32\n\t}{\n\t\t{ // All data\n\t\t\t&nqmModel.AgentQuery{IspId: -2, HasStatusParam: false},\n\t\t\t10, 1, 3, 3,\n\t\t},\n\t\t{ // 2nd page\n\t\t\t&nqmModel.AgentQuery{IspId: -2, HasStatusParam: false},\n\t\t\t2, 2, 1, 3,\n\t\t},\n\t\t{ // Match nothing for further page\n\t\t\t&nqmModel.AgentQuery{IspId: -2, HasStatusParam: false},\n\t\t\t10, 10, 0, 3,\n\t\t},\n\t\t{ // Match 1 row by all of the conditions\n\t\t\t&nqmModel.AgentQuery{\n\t\t\t\tName: \"ag-name-1\",\n\t\t\t\tConnectionId: \"ag-list-1\",\n\t\t\t\tHostname: \"hn-list-1\",\n\t\t\t\tIspId: 3,\n\t\t\t\tHasIspIdParam: true,\n\t\t\t\tIpAddress: \"123.52\",\n\t\t\t\tHasStatusParam: true,\n\t\t\t\tStatus: true,\n\t\t\t}, 10, 1, 1, 1,\n\t\t},\n\t\t{ // Match 1 row(by special IP address)\n\t\t\t&nqmModel.AgentQuery{\n\t\t\t\tIspId: -2,\n\t\t\t\tHasStatusParam: false,\n\t\t\t\tIpAddress: \"12.37\",\n\t\t\t}, 10, 1, 1, 1,\n\t\t},\n\t\t{ // Match nothing\n\t\t\t&nqmModel.AgentQuery{\n\t\t\t\tIspId: -2,\n\t\t\t\tHasStatusParam: false,\n\t\t\t\tConnectionId: \"ag-list-1\",\n\t\t\t\tHostname: \"hn-list-2\",\n\t\t\t}, 10, 1, 0, 0,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tpaging := commonModel.Paging{\n\t\t\tSize: testCase.pageSize,\n\t\t\tPosition: testCase.pagePosition,\n\t\t\tOrderBy: []*commonModel.OrderByEntity{\n\t\t\t\t{\"status\", commonModel.Ascending},\n\t\t\t\t{\"name\", commonModel.Ascending},\n\t\t\t\t{\"connection_id\", commonModel.Ascending},\n\t\t\t\t{\"comment\", commonModel.Ascending},\n\t\t\t\t{\"province\", commonModel.Ascending},\n\t\t\t\t{\"city\", commonModel.Ascending},\n\t\t\t\t{\"last_heartbeat_time\", commonModel.Ascending},\n\t\t\t\t{\"name_tag\", commonModel.Ascending},\n\t\t\t\t{\"group_tag\", commonModel.Descending},\n\t\t\t},\n\t\t}\n\n\t\ttestedResult, newPaging := ListAgents(\n\t\t\ttestCase.query, paging,\n\t\t)\n\n\t\tc.Logf(\"[List] Query: %#v. Number of agents: %d\", testCase.query, len(testedResult))\n\n\t\tfor _, agent := range testedResult {\n\t\t\tc.Logf(\"\\t[List] Matched Agent: %#v.\", agent)\n\t\t}\n\t\tc.Assert(testedResult, HasLen, testCase.expectedCountOfCurrentPage)\n\t\tc.Assert(newPaging.TotalCount, Equals, testCase.expectedCountOfAll)\n\t}\n}", "func (gs *GameServer) InitializeRoomGarbageCollector() {\n\tintervalTicker := time.NewTicker(1 * time.Minute)\n\tfor {\n\t\t<-intervalTicker.C\n\t\tcount := 0\n\t\tgs.mu.Lock()\n\t\tfor name, room := range gs.rooms {\n\t\t\tif len(room.Players) == 0 {\n\t\t\t\tcount++\n\t\t\t\tdelete(gs.rooms, name)\n\t\t\t}\n\t\t}\n\t\tgs.mu.Unlock()\n\t\tif count > 0 {\n\t\t\tfmt.Println(\"Cleaned up\", count, \"rooms\")\n\t\t}\n\t}\n}", "func (m *MockPoolRegistry) HardDeleteAllocations(allocations []registry.BrickAllocation) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HardDeleteAllocations\", allocations)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func All() []Room {\n\treturn rooms\n}", "func (db *PgDB) FindRooms(callTime string, maxRetryCount int) ([]*model.Room, error) {\n\tvar rooms []*model.Room\n\terr := db.Model(&rooms).\n\t\tWhere(\"call_time = ?\", callTime).\n\t\tWhere(\"retry_count < ?\", maxRetryCount).\n\t\tSelect()\n\tif err != nil {\n\t\tif err == pg.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn rooms, nil\n}", "func ListRoomPath() string {\n\n\treturn fmt.Sprintf(\"/api/rooms\")\n}", "func (m *postgresDBRepo) GetAllRooms() ([]models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar rooms []models.Room\n\tquery := `select id, room_name, created_at, updated_at from rooms order by room_name`\n\n\trows, err := m.DB.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn rooms, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\troom := models.Room{}\n\t\terr = rows.Scan(&room.ID, &room.RoomName, &room.CreatedAt, &room.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn rooms, err\n\t\t}\n\t\trooms = append(rooms, room)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn rooms, err\n\t}\n\treturn rooms, nil\n}", "func (s *Server) GetAllocations() ([]string, error) {\n\tvar allocations []string\n\terr := s.database.Select(&allocations, \"SELECT id FROM allocations\")\n\tif err == sql.ErrNoRows {\n\t\ts.logger.Error(\"No allocations found\")\n\t\treturn allocations, nil\n\t}\n\n\tif err != nil {\n\t\ts.logger.Error(\"Get allocations\", \"error\", err)\n\t\treturn allocations, err\n\t}\n\n\treturn allocations, nil\n}", "func TestRoomsSplitSpots(t *testing.T) {\n\tg := &rooms{grid{}, 4, 7}\n\trm := room{0, 0, 9, 7}\n\tspots := g.splitSpots(&rm, topBottom)\n\tif spots != 0 {\n\t\tt.Error(\"Only one spot for a 9x7 top/bottom split\")\n\t}\n\trm = room{7, 7, 9, 7}\n\tspots = g.splitSpots(&rm, leftRight)\n\tif spots != 2 {\n\t\tt.Error(\"Three possibilities for a 9x7 left/right split\")\n\t}\n\trm = room{0, 0, 21, 10}\n\tspots = g.splitSpots(&rm, leftRight)\n\tif spots != 14 {\n\t\tt.Error(\"Fourteen spots for a 21x21\")\n\t}\n}", "func CreateRoom(w http.ResponseWriter, request *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tswitch request.Method {\n\tcase \"POST\":\n\t\tdata := request.URL.Query()\n\t\tif !createRoomValidator(w, data) {\n\t\t\treturn\n\t\t}\n\t\tvar room roomJSON\n\t\tmaxUsers, _ := strconv.Atoi(data[\"users\"][0])\n\t\ti := 0\n\t\tfor {\n\t\t\ti++\n\t\t\troomID := rand.Intn(99) + 1\n\t\t\tif ok, _ := getRoomByID(roomID, &Rooms); !ok {\n\t\t\t\troom.ID = roomID\n\t\t\t\troom.MaxUsers = maxUsers\n\t\t\t\troom.State = \"joining\"\n\t\t\t\troom.Daytime = \"day\"\n\t\t\t\troom.Mafia = make([]int, 0)\n\t\t\t\troom.Peaceful = make([]int, 0)\n\t\t\t\troom.Alive = make([]int, 0)\n\t\t\t\troom.Killed = make([]int, 0)\n\t\t\t\troom.Jailed = make([]int, 0)\n\t\t\t\tRooms = append(Rooms, room)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i >= 100 {\n\t\t\t\thttp.Error(w, \"503 Game is not available\", http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tresp, err := json.Marshal(&room)\n\t\tif err == nil {\n\t\t\tw.Write(resp)\n\t\t}\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(405)\n\t\tfmt.Fprintf(w, \"Only POST method is allowed\")\n\t}\n}", "func (r Virtual_Guest) GetServerRoom() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getServerRoom\", nil, &r.Options, &resp)\n\treturn\n}", "func newGameServerAllocations(c *AllocationV1Client, namespace string) *gameServerAllocations {\n\treturn &gameServerAllocations{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func (s *Server) listRooms(c *client.Client, args []string) {\n\t// validate arg input\n\tif len(args) > 1 {\n\t\tc.Msg(\"please use /createRoom\")\n\t\treturn\n\t}\n\tmsg := \"\"\n\tfor room := range s.rooms {\n\t\tmsg += room + \"\\n\"\n\t}\n\tc.Msg(msg)\n\t// loop over current rooms and write to client availible rooms\n}", "func (m *PlacesRequestBuilder) GraphRoomList()(*GraphRoomListRequestBuilder) {\n return NewGraphRoomListRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func TestEmployeeManagerMapGetAll(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetAll(w, r)\n\texpectedResponse := `{\"Jonas\":{\"Sophie\":{\"Nick\":{\"Barbara\":{},\"Peter\":{}}}}}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func TestListMessages(t *testing.T) {\n\ts = getSpark(t)\n\tif len(allRooms) < 1 {\n\t\tgetAllRooms(t)\n\t}\n\n\tuv := url.Values{}\n\tfmt.Println(\"Title: \", allRooms[0].Title)\n\tuv.Add(\"roomId\", allRooms[0].Id)\n\tallMessages, err := s.ListMessages(&uv)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(allMessages) < 1 {\n\t\tt.Fatal(\"Expected there to be at least one message in the room\")\n\n\t}\n\n\t// test Get messages\n\tfirstMessage := allMessages[0]\n\t_, err = s.GetMessage(firstMessage.Id)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (ns *NSConn) Rooms() []*Room {\n\tns.roomsMutex.RLock()\n\trooms := make([]*Room, len(ns.rooms))\n\ti := 0\n\tfor _, room := range ns.rooms {\n\t\trooms[i] = room\n\t\ti++\n\t}\n\tns.roomsMutex.RUnlock()\n\n\treturn rooms\n}", "func (f *Framework) CycleAllocations(ctx context.Context, t *testing.T, flt *agonesv1.Fleet, period time.Duration, allocDuration time.Duration) {\n\terr := wait.PollImmediateUntil(period, func() (bool, error) {\n\t\tgsa := GetAllocation(flt)\n\t\tgsa, err := f.AgonesClient.AllocationV1().GameServerAllocations(flt.Namespace).Create(context.Background(), gsa, metav1.CreateOptions{})\n\t\tif err != nil || gsa.Status.State != allocationv1.GameServerAllocationAllocated {\n\t\t\t// Ignore error. Could be that the buffer was empty, will try again next cycle.\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Deallocate after allocDuration.\n\t\tgo func(gsa *allocationv1.GameServerAllocation) {\n\t\t\ttime.Sleep(allocDuration)\n\t\t\terr := f.AgonesClient.AgonesV1().GameServers(gsa.Namespace).Delete(context.Background(), gsa.Status.GameServerName, metav1.DeleteOptions{})\n\t\t\trequire.NoError(t, err)\n\t\t}(gsa)\n\n\t\treturn false, nil\n\t}, ctx.Done())\n\t// Ignore wait timeout error, will always be returned when the context is cancelled at the end of the test.\n\tif err != wait.ErrWaitTimeout {\n\t\trequire.NoError(t, err)\n\t}\n}", "func getProgrammingsTest(e *httpexpect.Expect, t *testing.T) {\n\ttestCases := []testCase{\n\t\tnotLoggedTestCase,\n\t\t{\n\t\t\tToken: testCtx.Admin.Token,\n\t\t\tParam: \"2018\",\n\t\t\tStatus: http.StatusOK,\n\t\t\tBodyContains: []string{\"Programmings\", `\"PrevCommitmentTotal\":96730644861`},\n\t\t\tCountItemName: `\"id\"`,\n\t\t\tArraySize: 626},\n\t}\n\tf := func(tc testCase) *httpexpect.Response {\n\t\treturn e.GET(\"/api/programmings\").WithHeader(\"Authorization\", \"Bearer \"+tc.Token).\n\t\t\tWithQuery(\"year\", tc.Param).Expect()\n\t}\n\tfor _, r := range chkTestCases(testCases, f, \"GetProgrammings\") {\n\t\tt.Error(r)\n\t}\n}", "func GenerateRoom(xxStart, yyStart, xxCount, yyCount int, dirHoriz bool) {\n\tgenerateRoom(xxStart, yyStart, xxCount, yyCount, dirHoriz)\n}", "func TestNetworkPktRanges(t *testing.T) {\n\t// verify auto allocation of vlans\n\tcheckCreateNetwork(t, false, \"default\", \"contiv\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv\", \"vlan\", \"10.1.1.1\", \"10.1.1.254\", 24, 1, 0)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv\")\n\n\t// auto allocation of vxlan\n\tcheckCreateNetwork(t, false, \"default\", \"contiv\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv\", \"vxlan\", \"10.1.1.1\", \"10.1.1.254\", 24, 1, 1)\n\tcheckCreateNetwork(t, false, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1\", \"10.1.2.254\", 24, 2, 2)\n\tcheckCreateNetwork(t, false, \"default\", \"contiv3\", \"vxlan\", \"10.1.3.1/24\", \"10.1.3.254\", 1000)\n\tverifyNetworkState(t, \"default\", \"contiv3\", \"vxlan\", \"10.1.3.1\", \"10.1.3.254\", 24, 3, 1000)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv\")\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv2\")\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv3\")\n\n\t// verify duplicate values fail\n\tcheckCreateNetwork(t, false, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv1\")\n\n\tcheckCreateNetwork(t, false, \"default\", \"contiv1\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv1\")\n\n\t// shrink ranges and try allocating\n\tcheckGlobalSet(t, false, \"default\", \"100-1000\", \"1001-2000\")\n\tcheckCreateNetwork(t, true, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1001)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 99)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 2001)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 1000)\n\n\t// reset back to default values\n\tcheckGlobalSet(t, false, \"default\", \"1-4094\", \"1-10000\")\n}", "func (cs *ChatServer) Rooms() int {\n\treturn cs.rooms\n}", "func LoadRooms(ctx context.Context) error {\n\tos.Mkdir(fmt.Sprintf(\"%s/rooms\", config.GetString(\"save_path\")), 0755)\n\tfiles, err := ioutil.ReadDir(fmt.Sprintf(\"%s/rooms/\", config.GetString(\"save_path\")))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tdata, err := ioutil.ReadFile(fmt.Sprintf(\"%s/rooms/%s\", config.GetString(\"save_path\"), file.Name()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\troom := NewRoom()\n\t\terr = json.Unmarshal(data, &room.Data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Debug().Str(\"name\", room.GetName()).Msg(\"loaded room\")\n\t\tAtlas.AddRoom(room)\n\t\t// Save the room after load in order to apply any possible migrations.\n\t\tif err := room.Save(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Loop through all rooms and link their exits in memory. Somewhat expensive\n\t// in large worlds, but only needs to be done once. This allows for fast room\n\t// movement without global lookups.\n\tfor _, room := range Atlas.worldMap {\n\t\tfor _, dir := range exitDirections {\n\t\t\texit := room.Exit(ctx, dir)\n\t\t\tif exit.Target != \"\" {\n\t\t\t\troom.exitRooms[dir] = Atlas.GetRoomByUUID(exit.Target)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func (chatRoom ChatRoom) getGuests() map[string]Guest {\n return chatRoom.guests\n}", "func getRoomMock(cfg roomMockConfig) roomMock {\n\tvar conf config.WorkerConfig\n\tif _, err := config.LoadConfig(&conf, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tconf.Worker.Library.BasePath = cfg.gamesPath\n\n\tfixEmulators(&conf, cfg.autoGlContext)\n\tl := logger.NewConsole(conf.Worker.Debug, \"w\", false)\n\tif cfg.noLog {\n\t\tlogger.SetGlobalLevel(logger.Disabled)\n\t}\n\n\t// sync cores\n\tif err := remotehttp.CheckCores(conf.Emulator, l); err != nil {\n\t\tl.Error().Err(err).Msg(\"cores sync error\")\n\t}\n\tconf.Encoder.Video.Codec = string(cfg.vCodec)\n\n\troom := NewRoom(cfg.roomName, cfg.game, nil, conf, l)\n\n\tif !cfg.dontStartEmulator {\n\t\troom.StartEmulator()\n\t}\n\n\t// loop-wait the room initialization\n\tvar init sync.WaitGroup\n\tinit.Add(1)\n\twasted := 0\n\tgo func() {\n\t\tsleepDeltaMs := 10\n\t\tfor room.emulator == nil {\n\t\t\ttime.Sleep(time.Duration(sleepDeltaMs) * time.Millisecond)\n\t\t\twasted++\n\t\t\tif wasted > 1000 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tinit.Done()\n\t}()\n\tinit.Wait()\n\treturn roomMock{Room: room, startEmulator: !cfg.dontStartEmulator}\n}", "func TestAllocate(t *testing.T) {\n\t_, storage, _, si, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := si.Create(context.TODO(), key(), validNewRangeAllocation(), nil, 0); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tport int\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"Allocate base port\",\n\t\t\tport: basePortRange,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate maximum from the port range\",\n\t\t\tport: basePortRange + sizePortRange - 1,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: base port minus 1\",\n\t\t\tport: basePortRange - 1,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: maximum port from the port range plus 1\",\n\t\t\tport: basePortRange + sizePortRange,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port\",\n\t\t\tport: -2,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\ttt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := storage.Allocate(tt.port)\n\t\t\tif (err == nil) != (tt.errMsg == \"\") {\n\t\t\t\tt.Fatalf(\"Error expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t\tif err != nil && err.Error() != tt.errMsg {\n\t\t\t\tt.Fatalf(\"Error message expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t})\n\t}\n\n}", "func (c *Client) ListRooms(ctx context.Context, req *ListRoomsRequest) (*ListRoomsResponse, error) {\n\tif req == nil {\n\t\treq = &ListRoomsRequest{}\n\t}\n\tresp := &ListRoomsResponse{}\n\treturn resp, c.request(ctx, \"GET\", \"rooms\", req, resp)\n}", "func testGetExamLists(t *testing.T) {\n\tlimit := uint(1)\n\texamLists, err := MainService.GetExamLists(limit, 0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif len(examLists.ExamLists) != int(limit) && examLists.Count != limit {\n\t\tt.Errorf(\"There is an error, the length should be %d but got %d\",\n\t\t\tlimit, len(examLists.ExamLists))\n\t}\n}", "func checkNodeAllocatableTest(f *framework.Framework) {\n\n\tnodeMem := getNodeMemory(f)\n\tframework.Logf(\"nodeMem says: %+v\", nodeMem)\n\n\t// calculate the allocatable mem based on capacity - reserved amounts\n\tcalculatedNodeAlloc := nodeMem.capacity.Copy()\n\tcalculatedNodeAlloc.Sub(nodeMem.systemReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.kubeReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.softEviction)\n\tcalculatedNodeAlloc.Sub(nodeMem.hardEviction)\n\n\tginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc))\n\n\t// sanity check against stated allocatable\n\tgomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0))\n}", "func (suite *ServiceTestSuite) TestHostsService_GetCompletedReservation() {\n\tdefer suite.mockCtrl.Finish()\n\tctx := context.Background()\n\n\tsuite.hostMgrClient.EXPECT().GetCompletedReservations(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(nil, errReturn)\n\t_, err := suite.hostService.GetCompletedReservation(ctx)\n\trequire.Error(suite.T(), err)\n\tsuite.Equal(err.Error(), errReturn.Error())\n\n\tsuite.hostMgrClient.EXPECT().GetCompletedReservations(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(&hostsvc.GetCompletedReservationResponse{\n\t\t\tError: &hostsvc.GetCompletedReservationResponse_Error{\n\t\t\t\tNotFound: &hostsvc.NotFound{\n\t\t\t\t\tMessage: \"not found\",\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil)\n\t_, err = suite.hostService.GetCompletedReservation(ctx)\n\trequire.Error(suite.T(), err)\n\tsuite.Equal(err.Error(), \"not found\")\n\n\tsuite.hostMgrClient.EXPECT().GetCompletedReservations(\n\t\tgomock.Any(), gomock.Any()).\n\t\tReturn(&hostsvc.GetCompletedReservationResponse{\n\t\t\tCompletedReservations: []*hostsvc.CompletedReservation{\n\t\t\t\t{Host: &hostsvc.HostInfo{}}},\n\t\t}, nil)\n\n\treservations, err := suite.hostService.GetCompletedReservation(ctx)\n\trequire.NoError(suite.T(), err)\n\tsuite.Equal(len(reservations), 1)\n}", "func (bpdb *BitpartmentDB) CreateRoomsTable() error {\n\treturn bpdb.createSomeTable(&Room{}, \"ROOM\")\n}", "func TestGetMinterAddresses(t *testing.T) {\n\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\taddresses, err := db.GetMinterAddresses(344178872)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif addresses != nil {\n\t\tt.Errorf(\"Addresses must be empty %d!\", len(addresses))\n\t}\n\n}", "func (f Factory) TestGetMapIDsPagination(t *testing.T) {\n\ta := f.initAdapter(t)\n\tdefer f.free(a)\n\n\tfor i := 0; i < 10; i++ {\n\t\tfor j := 0; j < 10; j++ {\n\t\t\tsegment := cstesting.RandomSegment()\n\t\t\tsegment.Link.Meta[\"mapId\"] = fmt.Sprintf(\"map%d\", i)\n\t\t\ta.SaveSegment(segment)\n\t\t}\n\t}\n\n\tslice, err := a.GetMapIDs(&store.MapFilter{Pagination: store.Pagination{Offset: 3, Limit: 5}})\n\tif err != nil {\n\t\tt.Fatalf(\"a.GetMapIDs(): err: %s\", err)\n\t}\n\n\tif got, want := len(slice), 5; got != want {\n\t\tt.Errorf(\"len(slice) = %d want %d\", got, want)\n\t}\n}", "func TestQueryLedgers(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.QueryLedgers(context.Background(), \"LVTSFS-NHZVM-EXNZ5M\")\n\tif err == nil {\n\t\tt.Error(\"QueryLedgers() Expected error\")\n\t}\n}", "func getAvailableRoomId() int {\n\tfor i, used := range roomIdsFlag {\n\t\tif !used {\n\t\t\troomIdsFlag[i] = true\n\t\t\treturn i + 1\n\t\t}\n\t}\n\treturn 0\n}", "func (c *Client) GetRoom(ctx context.Context, name string) (*GetRoomResponse, error) {\n\tresp := &GetRoomResponse{}\n\treturn resp, c.request(ctx, \"GET\", \"rooms/\"+name, nil, resp)\n}", "func (c *BuildingClient) QueryRooms(b *Building) *RoomQuery {\n\tquery := &RoomQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := b.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(building.Table, building.FieldID, id),\n\t\t\tsqlgraph.To(room.Table, room.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, building.RoomsTable, building.RoomsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(b.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func TestGetRoutes(t *testing.T) {\n\n\tvar table = []struct {\n\t\t// name of the test case\n\t\tname string\n\n\t\t// advertised prefixes\n\t\tadvertisedPrefixes []netip.Prefix\n\t\t// expected prefixes\n\t\texpectedPrefixes []netip.Prefix\n\n\t\t// GetRoutes params\n\t\trouterASN *int64\n\t\ttableType string\n\t\tafi string\n\t\tsafi string\n\t\tneighbor *string\n\n\t\t// non-nil if error is expected, nil if not\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tname: \"single IPv4 prefix - retrieve IPv4\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: testSingleIPv4Prefix,\n\t\t\trouterASN: pointer.Int64(int64(testRouterASN)),\n\t\t\ttableType: tableTypeLocRib,\n\t\t\tafi: afiIPv4,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"single IPv4 prefix - retrieve IPv6\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: nil,\n\t\t\trouterASN: pointer.Int64(int64(testRouterASN)),\n\t\t\ttableType: tableTypeLocRib,\n\t\t\tafi: afiIPv6,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"single IPv6 prefix - retrieve IPv6\",\n\t\t\tadvertisedPrefixes: testSingleIPv6Prefix,\n\t\t\texpectedPrefixes: testSingleIPv6Prefix,\n\t\t\trouterASN: nil,\n\t\t\ttableType: tableTypeLocRib,\n\t\t\tafi: afiIPv6,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"mixed IPv4 & IPv6 prefixes - retrieve IPv6\",\n\t\t\tadvertisedPrefixes: []netip.Prefix{testSingleIPv4Prefix[0], testSingleIPv6Prefix[0]},\n\t\t\trouterASN: nil,\n\t\t\texpectedPrefixes: testSingleIPv6Prefix,\n\t\t\ttableType: tableTypeLocRib,\n\t\t\tafi: afiIPv6,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"incorrect ASN\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: nil,\n\t\t\trouterASN: pointer.Int64(int64(testInvalidRouterASN)),\n\t\t\ttableType: tableTypeLocRib,\n\t\t\tafi: afiIPv4,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: fmt.Errorf(\"\"),\n\t\t},\n\t\t{\n\t\t\tname: \"missing neighbor for adj-rib-out\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: nil,\n\t\t\trouterASN: nil,\n\t\t\ttableType: tableTypeLocAdjRibOut,\n\t\t\tafi: afiIPv4,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: nil,\n\t\t\texpectedErr: fmt.Errorf(\"\"),\n\t\t},\n\t\t{\n\t\t\tname: \"valid neighbor\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: nil, // nil as the neighbor never goes UP\n\t\t\trouterASN: nil,\n\t\t\ttableType: tableTypeLocAdjRibOut,\n\t\t\tafi: afiIPv4,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: pointer.String(testNeighborIP),\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"non-existing neighbor\",\n\t\t\tadvertisedPrefixes: testSingleIPv4Prefix,\n\t\t\texpectedPrefixes: nil,\n\t\t\trouterASN: nil,\n\t\t\ttableType: tableTypeLocAdjRibOut,\n\t\t\tafi: afiIPv4,\n\t\t\tsafi: safiUnicast,\n\t\t\tneighbor: pointer.String(testInvalidNeighborIP),\n\t\t\texpectedErr: fmt.Errorf(\"\"),\n\t\t},\n\t}\n\n\tfor _, tt := range table {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// set up BGPRouterManager with one BGP server\n\t\t\tsrvParams := types.ServerParameters{\n\t\t\t\tGlobal: types.BGPGlobal{\n\t\t\t\t\tASN: uint32(testRouterASN),\n\t\t\t\t\tRouterID: \"127.0.0.1\",\n\t\t\t\t\tListenPort: -1,\n\t\t\t\t},\n\t\t\t}\n\t\t\ttestSC, err := NewServerWithConfig(context.Background(), srvParams)\n\t\t\trequire.NoError(t, err)\n\n\t\t\ttestSC.Config = &v2alpha1api.CiliumBGPVirtualRouter{\n\t\t\t\tLocalASN: int64(testRouterASN),\n\t\t\t\tNeighbors: []v2alpha1api.CiliumBGPNeighbor{},\n\t\t\t}\n\t\t\tbrm := &BGPRouterManager{\n\t\t\t\tServers: map[int64]*ServerWithConfig{\n\t\t\t\t\tint64(testRouterASN): testSC,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\t// add a neighbor\n\t\t\tn := &v2alpha1api.CiliumBGPNeighbor{\n\t\t\t\tPeerAddress: testNeighborIP + \"/32\",\n\t\t\t\tPeerASN: 64100,\n\t\t\t}\n\t\t\tn.SetDefaults()\n\t\t\terr = testSC.Server.AddNeighbor(context.Background(), types.NeighborRequest{\n\t\t\t\tNeighbor: n,\n\t\t\t\tVR: testSC.Config,\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// advertise test-provided prefixes\n\t\t\tfor _, cidr := range tt.advertisedPrefixes {\n\t\t\t\t_, err := testSC.Server.AdvertisePath(context.Background(), types.PathRequest{\n\t\t\t\t\tPath: types.NewPathForPrefix(cidr),\n\t\t\t\t})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\n\t\t\t// retrieve routes from server's local RIB and\n\t\t\troutes, err := brm.GetRoutes(context.Background(), restapi.GetBgpRoutesParams{\n\t\t\t\tRouterAsn: tt.routerASN,\n\t\t\t\tTableType: tt.tableType,\n\t\t\t\tAfi: tt.afi,\n\t\t\t\tSafi: tt.safi,\n\t\t\t\tNeighbor: tt.neighbor,\n\t\t\t})\n\t\t\tif tt.expectedErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Error(t, err)\n\t\t\t}\n\n\t\t\t// ensure retrieved routes match expected prefixes\n\t\t\tvar retrievedPrefixes []netip.Prefix\n\t\t\tfor _, r := range routes {\n\t\t\t\tretrievedPrefixes = append(retrievedPrefixes, netip.MustParsePrefix(r.Prefix))\n\t\t\t}\n\t\t\trequire.EqualValues(t, tt.expectedPrefixes, retrievedPrefixes)\n\t\t})\n\t}\n}", "func (config *AppConfig) GetNodeAllocations(nodeID int) (allocations NodeAllocations, err error) {\n\t// Get allocation info from the panel\n\tallocBytes, err := config.queryApplicationAPI(fmt.Sprintf(\"nodes/%d/allocations?page=%d\", nodeID), \"get\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(allocBytes, &allocations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := 1; i >= allocations.Meta.Pagination.TotalPages; i++ {\n\t\tallocations, err := config.getNodeAllocationsByPage(nodeID, i)\n\t\tif err != nil {\n\t\t\treturn allocations, err\n\t\t}\n\t\tfor _, allocation := range allocations.Allocations {\n\t\t\tallocations.Allocations = append(allocations.Allocations, allocation)\n\t\t}\n\t}\n\n\treturn\n}", "func TestGet_Unit(t *testing.T) {\n\n\tvar dr Router\n\tdr = &MockedResources{}\n\n\tvar vs Router\n\tvs = &MockedResources{}\n\n\tvar op Operator\n\top = &Istiops{\n\t\tDrRouter: dr,\n\t\tVsRouter: vs,\n\t}\n\n\tirl, err := op.Get(map[string]string{})\n\tassert.Equal(t, router.IstioRouteList{\n\t\tVList: &v1alpha3.VirtualServiceList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.VirtualService{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t\tDList: &v1alpha3.DestinationRuleList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.DestinationRule{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t}, irl)\n\tassert.NoError(t, err)\n}", "func (c *RoomuseClient) QueryRooms(r *Roomuse) *RoomQuery {\n\tquery := &RoomQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := r.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(roomuse.Table, roomuse.FieldID, id),\n\t\t\tsqlgraph.To(room.Table, room.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, roomuse.RoomsTable, roomuse.RoomsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(r.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func createRoom(gm *gomatrix.Client, roomAliasName string) (roomID string, err error) {\n req := &gomatrix.ReqCreateRoom{\n RoomAliasName: roomAliasName,\n Preset: \"public_chat\",\n }\n\n // Create the room\n resp, err := gm.CreateRoom(req)\n if err != nil {\n return\n }\n\n roomID = resp.RoomID\n return\n}", "func TestApi_ListMotorcycles_NotEmpty(t *testing.T) {\n\n\t// ARRANGE\n\n\t// Configure the application...\n\troles := map[authorizationrole.AuthorizationRole]bool{\n\t\tauthorizationrole.AdminAuthorizationRole: true,\n\t}\n\n\tauthService, _ := security.NewAuthService(true, roles)\n\tmotorcycleRepository, _ := repository.NewMotorcycleRepository()\n\trouter := httprouter.New()\n\n\t// Create an instance of the API web service.\n\tourApi, err := NewApi(roles, authService, motorcycleRepository, router)\n\tif err != nil {\n\t\tprintln(\"Failed to create an instance of the API web service: &s\", err.Error())\n\t\treturn\n\t}\n\n\t// Insert two motorcycles into the repository using the Api.\n\tmotorcycle, _ := entity.NewMotorcycle(\"Honda\", \"Shadow\", 2006, \"01234567890123456\")\n\tInsertMotorcycle(ourApi, motorcycle)\n\tmotorcycle, _ = entity.NewMotorcycle(\"Honda\", \"Shadow\", 2010, \"01234567890199999\")\n\tInsertMotorcycle(ourApi, motorcycle)\n\n\t// ACT\n\tresp, err := GetMotorcycles(ourApi)\n\n\t// ASSERT\n\tassert.True(t, resp.StatusCode == http.StatusOK)\n}", "func (suite *TestAgentItSuite) TestListAgents(c *C) {\n\tclient := sling.New().Get(httpClientConfig.String()).\n\t\tPath(\"/api/v1/nqm/agents\")\n\n\tslintChecker := testingHttp.NewCheckSlint(c, client)\n\n\tslintChecker.AssertHasPaging()\n\tmessage := slintChecker.GetJsonBody(http.StatusOK)\n\n\tc.Logf(\"[List Agents] JSON Result: %s\", json.MarshalPrettyJSON(message))\n\tc.Assert(len(message.MustArray()), Equals, 3)\n}", "func minMeetingRooms(intervals [][]int) int {\n\t// sort using start times\n\tsort.SliceStable(intervals, func(i, j int) bool {\n\t\t// for same start times, sort by increasing end times\n\t\t// if intervals[i][0] == intervals[j][0] {\n\t\t// \treturn intervals[i][1] > intervals[j][1]\n\t\t// }\n\t\treturn intervals[i][0] < intervals[j][0]\n\t})\n\n\t// walk through the array and find the conflict and add extra room\n\t// rooms := 1\n\troomSet := []int{}\n\n\t// for i := 0; i < len(intervals)-1; i++ {\n\tfor _, interval := range intervals {\n\n\t\t// find the lowest index in room set\n\t\tindex := sort.SearchInts(roomSet, interval[0])\n\n\t\tfmt.Printf(\"Start time: %d, Search index: %d\\n\", interval[0], index)\n\t\t// TODO: this needs to be changed to priority queue, since we need to find the element with the earliest finish time\n\t\t// it the current start time > earliest finish time, then we can reuse a meeting room, else we need to create a new room\n\t\tif index < len(roomSet) && roomSet[index] <= interval[0] {\n\t\t\t// found an interval which ends before start\n\t\t\troomSet[index] = interval[1]\n\t\t} else if index != 0 {\n\t\t\troomSet[index-1] = interval[1]\n\t\t} else {\n\t\t\t// index = len(roomSet)\n\t\t\troomSet = append(roomSet, interval[1])\n\t\t}\n\n\t\tsort.SliceStable(roomSet, func(i, j int) bool { return roomSet[i] < roomSet[j] })\n\n\t\t// if no entry in rooms or a conflict with next event add a room\n\t\t// if intervals[i+1][0] < intervals[i][1] {\n\t\t// \trooms++\n\t\t// }\n\t\tfmt.Println(roomSet)\n\n\t}\n\treturn len(roomSet)\n}", "func (l *Leaf) CreateRooms() {\n\tif l.Left != nil || l.Right != nil {\n\t\t// if split, go into children leafs\n\t\tif l.Left != nil {\n\t\t\tl.Left.CreateRooms()\n\t\t}\n\t\tif l.Right != nil {\n\t\t\tl.Right.CreateRooms()\n\t\t}\n\t\tif l.Left != nil && l.Right != nil {\n\t\t\tl.CreateHall(l.Left.GetRoom(), l.Right.GetRoom())\n\t\t}\n\t} else {\n\t\t// ready to make a room\n\t\tx := l.Bounds.Min.X\n\t\ty := l.Bounds.Min.Y\n\t\twidth := l.Bounds.Dx()\n\t\theight := l.Bounds.Dy()\n\t\troomSize := image.Pt(randNum(3, width-2), randNum(3, height-2))\n\n\t\t// place the room within the Leaf, but don't put it right\n\t\t// against the side of the Leaf (that would merge rooms together)\n\t\troomPos := image.Pt(randNum(1, width-roomSize.X-1), randNum(1, height-roomSize.Y-1))\n\n\t\tx0 := x + roomPos.X\n\t\ty0 := y + roomPos.Y\n\t\tx1 := x0 + roomSize.X\n\t\ty1 := y0 + roomSize.Y\n\t\tl.Room = image.Rect(x0, y0, x1, y1)\n\t}\n}", "func Test_DeviceService_GetAll_Success(t *testing.T) {\n\th := TestHelper{}\n\trep := new(mocks.IDeviceRepository)\n\trepAuth := new(mocks.IDeviceAuthRepository)\n\ts := h.CreateTestDeviceService(rep, repAuth)\n\n\tdevices := make([]models.Device, 2)\n\tdevices[0] = models.Device{\n\t\tIP: \"192.168.11.4\",\n\t\tPort: 37777,\n\t}\n\n\tdevices[1] = models.Device{\n\t\tIP: \"192.168.11.5\",\n\t\tPort: 37777,\n\t}\n\n\trep.On(\"GetAll\").Return(devices, nil)\n\n\treal, err := s.GetAll()\n\n\tassert.NoError(t, err)\n\tassert.True(t, len(real) == 2)\n\tassert.Equal(t, real[0], devices[0])\n\tassert.Equal(t, real[1], devices[1])\n}", "func (s *RoomsNightService) Room(ctx context.Context, id int) (*NightRoomResponsePayload, *Response, error) {\n\treq, err := s.NewRequest(id)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpayload := &NightRoomResponsePayload{}\n\tresp, err := s.client.Do(ctx, req, payload)\n\n\treturn payload, resp, nil\n}", "func GetAllRoomTypes(storage storage.Storage) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar roomTypes []*models.RoomType\n\t\tvar err error\n\n\t\tif roomTypes, err = storage.GetAllRoomTypes(); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"roomTypes\": roomTypes,\n\t\t})\n\t}\n}", "func GetDevicesByBuildingAndRoomAndRole(building string, room string, roleName string) (toReturn []accessors.Device, err error) {\n\terr = GetData(os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\")+\"/buildings/\"+building+\"/rooms/\"+room+\"/devices/roles/\"+roleName, &toReturn)\n\tif err != nil {\n\t\tlog.Printf(\"Error getting device by role: %s\", err.Error())\n\t}\n\treturn\n}", "func (m *mysqlDBRepo) AllRooms() ([]models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `select id, room_name, created_at, updated_at from rooms order by room_name`\n\n\tvar rooms []models.Room\n\n\trows, err := m.DB.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn rooms, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar i models.Room\n\t\terr := rows.Scan(\n\t\t\t&i.ID,\n\t\t\t&i.RoomName,\n\t\t\t&i.CreatedAt,\n\t\t\t&i.UpdatedAt,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn rooms, err\n\t\t}\n\t\trooms = append(rooms, i)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn rooms, err\n\t}\n\n\treturn rooms, nil\n}", "func TestCreateManagerToEmployeeList(t *testing.T) {\n\templyMgrMap := getTestEmployeeManagerMap()\n\n\texpectedMgrEmployeeList := map[string][]string{\n\t\t\"Nick\": []string{\"Peter\", \"Barbara\"},\n\t\t\"Jonas\": []string{\"Sophie\"},\n\t\t\"Sophie\": []string{\"Nick\"},\n\t}\n\tassert.Equal(t, expectedMgrEmployeeList, emplyMgrMap.CreateManagerToEmployeeList())\n}", "func TestClientEndpoint_GetClientAllocs_WithoutMigrateTokens(t *testing.T) {\n\tt.Parallel()\n\tassert := assert.New(t)\n\n\ts1 := TestServer(t, nil)\n\tdefer s1.Shutdown()\n\tcodec := rpcClient(t, s1)\n\ttestutil.WaitForLeader(t, s1.RPC)\n\n\t// Create the register request\n\tnode := mock.Node()\n\treg := &structs.NodeRegisterRequest{\n\t\tNode: node,\n\t\tWriteRequest: structs.WriteRequest{Region: \"global\"},\n\t}\n\n\t// Fetch the response\n\tvar resp structs.GenericResponse\n\tif err := msgpackrpc.CallWithCodec(codec, \"Node.Register\", reg, &resp); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tnode.CreateIndex = resp.Index\n\tnode.ModifyIndex = resp.Index\n\n\t// Inject fake evaluations\n\tprevAlloc := mock.Alloc()\n\tprevAlloc.NodeID = node.ID\n\talloc := mock.Alloc()\n\talloc.NodeID = node.ID\n\talloc.PreviousAllocation = prevAlloc.ID\n\talloc.DesiredStatus = structs.AllocClientStatusComplete\n\tstate := s1.fsm.State()\n\tstate.UpsertJobSummary(99, mock.JobSummary(alloc.JobID))\n\terr := state.UpsertAllocs(100, []*structs.Allocation{prevAlloc, alloc})\n\tassert.Nil(err)\n\n\t// Lookup the allocs\n\tget := &structs.NodeSpecificRequest{\n\t\tNodeID: node.ID,\n\t\tSecretID: node.SecretID,\n\t\tQueryOptions: structs.QueryOptions{Region: \"global\"},\n\t}\n\tvar resp2 structs.NodeClientAllocsResponse\n\n\terr = msgpackrpc.CallWithCodec(codec, \"Node.GetClientAllocs\", get, &resp2)\n\tassert.Nil(err)\n\n\tassert.Equal(uint64(100), resp2.Index)\n\tassert.Equal(2, len(resp2.Allocs))\n\tassert.Equal(uint64(100), resp2.Allocs[alloc.ID])\n\tassert.Equal(0, len(resp2.MigrateTokens))\n}", "func (suite *TestAgentSuite) TestBuildQueryForListAgents(c *C) {\n\ttestCases := []struct {\n\t\tparams string\n\t\texpectedQuery *commonNqmModel.AgentQuery\n\t} {\n\t\t{ \"\", &commonNqmModel.AgentQuery{ HasIspId: false, HasStatusCondition: false} }, // Nothing\n\t\t{ // With all of the supported parameters\n\t\t\t\"name=name-1&connection_id=gtk-01&hostname=host-1&ip_address=34.55&isp_id=406&status=1\",\n\t\t\t&commonNqmModel.AgentQuery{\n\t\t\t\tName: \"name-1\",\n\t\t\t\tHostname: \"host-1\",\n\t\t\t\tConnectionId: \"gtk-01\",\n\t\t\t\tIpAddress: \"34.55\",\n\t\t\t\tHasIspId: true,\n\t\t\t\tIspId: 406,\n\t\t\t\tHasStatusCondition: true,\n\t\t\t\tStatus: true,\n\t\t\t},\n\t\t},\n\t}\n\n\tsampleContext := &gin.Context{}\n\n\tfor i, testCase := range testCases {\n\t\tsampleContext.Request, _ = http.NewRequest(\"GET\", \"/a?\" + testCase.params, nil)\n\n\t\tc.Assert(buildQueryForListAgents(sampleContext), DeepEquals, testCase.expectedQuery, Commentf(\"Test Case: %d\", i + 1))\n\t}\n}", "func Test_DeviceService_GetAll_Empty(t *testing.T) {\n\th := TestHelper{}\n\trep := new(mocks.IDeviceRepository)\n\trepAuth := new(mocks.IDeviceAuthRepository)\n\ts := h.CreateTestDeviceService(rep, repAuth)\n\n\tdevices := make([]models.Device, 0)\n\trep.On(\"GetAll\").Return(devices, nil)\n\n\tall, err := s.GetAll()\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, len(all), len(devices))\n}", "func (rf *RoomFinder) Write() (b []byte) {\n\n\tif rf.regRoomIds == nil {\n\t\trf.regRoomIds = make( map[int64] *tools.SI64Set, 0 )\n\t}\n\tif rf.sdRoomIds == nil {\n\t\trf.sdRoomIds = make( map[int64] *tools.SI64Set, 0 )\n\t}\n\tif rf.ldRoomIds == nil {\n\t\trf.ldRoomIds = make( map[int64] *tools.SI64Set, 0 )\n\t}\n\tif rf.elRoomIds == nil {\n\t\trf.elRoomIds = make( map[int32] *tools.SI64Set, 0 )\n\t}\n\t// each index (region, short, long, & exits) is set up like this:\n\t// [len]\n\t// V\n\t// [key][len]->[val]...\n\t// .\n\t// .\n\t// .\n\tb = make( []byte, 0, 1000 )\n\tlk := len( rf.regRoomIds )\n\tb = append( b, persistence.IToB( lk )... )\n\tfor key, vals := range rf.regRoomIds {\n\t\tb = append( b, persistence.I64ToB( key )... )\n\t\tlv := vals.Size()\n\t\tb = append( b, persistence.IToB( lv )... )\n\t\tit := vals.Iterator()\n\t\tfor it.HasNext() {\n\t\t\tv, _ := it.Next()\n\t\t\tb = append( b, persistence.I64ToB( v )... )\n\t\t}\n\t}\n\tlk = len( rf.sdRoomIds )\n\tb = append( b, persistence.IToB( lk )... )\n\tfor key, vals := range rf.sdRoomIds {\n\t\tb = append( b, persistence.I64ToB( key )... )\n\t\tlv := vals.Size()\n\t\tb = append( b, persistence.IToB( lv )... )\n\t\tit := vals.Iterator()\n\t\tfor it.HasNext() {\n\t\t\tv, _ := it.Next()\n\t\t\tb = append( b, persistence.I64ToB( v )... )\n\t\t}\n\t}\n\tlk = len( rf.ldRoomIds )\n\tb = append( b, persistence.IToB( lk )... )\n\tfor key, vals := range rf.ldRoomIds {\n\t\tb = append( b, persistence.I64ToB( key )... )\n\t\tlv := vals.Size()\n\t\tb = append( b, persistence.IToB( lv )... )\n\t\tit := vals.Iterator()\n\t\tfor it.HasNext() {\n\t\t\tv, _ := it.Next()\n\t\t\tb = append( b, persistence.I64ToB( v )... )\n\t\t}\n\t}\n\tlk = len( rf.elRoomIds )\n\tb = append( b, persistence.IToB( lk )... )\n\tfor key, vals := range rf.elRoomIds {\n\t\tb = append( b, persistence.I32ToB( key )... )\n\t\tlv := vals.Size()\n\t\tb = append( b, persistence.IToB( lv )... )\n\t\tit := vals.Iterator()\n\t\tfor it.HasNext() {\n\t\t\tv, _ := it.Next()\n\t\t\tb = append( b, persistence.I64ToB( v )... )\n\t\t}\n\t}\n\treturn b\n}", "func (aec *AddEntryCmd) RequiresRoom() {}", "func ListRooms() ([]*Room, error) {\n\trows, err := DB.Model(&Room{}).Rows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar rooms []*Room\n\tfor rows.Next() {\n\t\tvar room Room\n\t\tDB.ScanRows(rows, &room)\n\t\trooms = append(rooms, &room)\n\t}\n\n\treturn rooms, nil\n}", "func getRandomEndpointsManager(t testing.TB) connection.Endpoint {\n\teps := getEndpointsFromEnv(t)\n\trand.Seed(time.Now().UnixNano())\n\tif rand.Intn(2) == 1 {\n\t\tt.Log(\"Using MaglevHashEndpoints\")\n\t\tep, err := connection.NewMaglevHashEndpoints(eps, connection.RequestDBNameValueExtractor)\n\t\trequire.NoError(t, err)\n\t\treturn ep\n\t}\n\tt.Log(\"Using RoundRobinEndpoints\")\n\treturn connection.NewRoundRobinEndpoints(eps)\n}", "func (f Factory) TestGetMapIDs(t *testing.T) {\n\ta := f.initAdapter(t)\n\tdefer f.free(a)\n\n\tfor i := 0; i < store.DefaultLimit; i++ {\n\t\tfor j := 0; j < store.DefaultLimit; j++ {\n\t\t\ts := cstesting.RandomSegment()\n\t\t\ts.Link.Meta[\"mapId\"] = fmt.Sprintf(\"map%d\", i)\n\t\t\ta.SaveSegment(s)\n\t\t}\n\t}\n\n\tslice, err := a.GetMapIDs(&store.MapFilter{Pagination: store.Pagination{Limit: store.DefaultLimit * store.DefaultLimit}})\n\tif err != nil {\n\t\tt.Fatalf(\"a.GetMapIDs(): err: %s\", err)\n\t}\n\n\tif got, want := len(slice), store.DefaultLimit; got != want {\n\t\tt.Errorf(\"len(slice) = %d want %d\", got, want)\n\t}\n\n\tfor i := 0; i < store.DefaultLimit; i++ {\n\t\tmapID := fmt.Sprintf(\"map%d\", i)\n\t\tif !testutil.ContainsString(slice, mapID) {\n\t\t\tt.Errorf(\"slice does not contain %q\", mapID)\n\t\t}\n\t}\n}" ]
[ "0.6600379", "0.6474636", "0.6459547", "0.59002614", "0.573544", "0.5703511", "0.5692829", "0.56784165", "0.566074", "0.56518143", "0.5624134", "0.55817044", "0.55706024", "0.5521844", "0.55034983", "0.5493293", "0.5441245", "0.54098433", "0.54007494", "0.5268259", "0.52670586", "0.52625525", "0.5244635", "0.5220129", "0.5171535", "0.5152349", "0.51425976", "0.51292044", "0.51176274", "0.5111271", "0.5107828", "0.5077899", "0.5073263", "0.50662386", "0.50651896", "0.5032409", "0.50026065", "0.50020754", "0.4996796", "0.49878287", "0.49728632", "0.49719474", "0.49645966", "0.4963309", "0.49584687", "0.4948477", "0.49466273", "0.49434045", "0.4940282", "0.4939675", "0.49347994", "0.49205315", "0.49189124", "0.4909221", "0.49039397", "0.49038714", "0.48927075", "0.48710456", "0.4858343", "0.48476866", "0.48424667", "0.4828809", "0.4828809", "0.48250806", "0.4823015", "0.48202097", "0.48140645", "0.48083982", "0.48045218", "0.47929707", "0.4787582", "0.47672182", "0.47593355", "0.4750227", "0.4749488", "0.474918", "0.47448444", "0.4743991", "0.4732768", "0.47320637", "0.47291005", "0.47215006", "0.47200727", "0.47187746", "0.4710224", "0.47002536", "0.4698391", "0.46949872", "0.4691888", "0.46892565", "0.46883118", "0.4680486", "0.46770114", "0.46658316", "0.46524376", "0.46449867", "0.4644977", "0.46405572", "0.46323028", "0.46174577" ]
0.8472192
0
TestGetUnallocatedPeople tests the functionality of GetUnallocatedPeople
func TestGetUnallocatedPeople(t *testing.T) { var ( err error user User users []User fetchUsers = func(fname, lname, userType string) { user, err = AddPerson(con, fname, lname, userType, "", "") So(err, ShouldBeNil) So(user, ShouldNotResemble, (User{})) users, err = GetUnallocatedPeople(con) } ) Convey("Tests for GetUnallocatedPeople ", t, func() { Convey("GetUnallocatedPeople should return a slice of User with all the correct values present and an error", func() { fetchUsers("David", "Holmes", "staff") So(err, ShouldBeNil) for _, user = range users { So(user.FirstName, ShouldEqual, "David") So(user.ID, ShouldNotBeBlank) So(user.LastName, ShouldEqual, "Holmes") So(user.LivingSpace, ShouldResemble, (User{})) So(user.Office, ShouldResemble, (User{})) So(user.Type, ShouldEqual, "staff") } }) Convey("Print the successfully created Room and User", func() { fetchUsers("Mark", "Oyaboade", "fellow") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printUnallocatedPeople(c *cli.Context) error {\n\tvar users, err = controllers.GetUnallocatedPeople(con)\n\n\texitOnError(err)\n\n\tfor _, user := range users {\n\t\tprintUserDetails(user)\n\t}\n\n\treturn nil\n}", "func TestGetPeople(t *testing.T) {\n\tpeople := GetPeople()\n\tif len(people) != 0 {\n\t\tt.Errorf(\"Expected len(GetPeople()) = %d, got: %d\", 0, len(people))\n\t}\n}", "func TestGetRoomAllocations(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\t\trooms []Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\trooms, err = GetRoomAllocations(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoomAllocations \", t, func() {\n\t\tConvey(\"GetRoomAllocations should return a slice of Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Garbrielle\", \"Wanjigi\", \"fellow\", \"Timbuktu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, room = range rooms {\n\n\t\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Name, ShouldEqual, \"Timbuktu\")\n\t\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Garbrielle\")\n\t\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Wanjigi\")\n\t\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"Ashley\", \"Wanjigi\", \"fellow\", \"Golang\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (s *StorageMemory) GetPeople() ([]Person, error) {\n\treturn s.People, nil\n}", "func TestEmpty(t *testing.T) {\n\t_, storage, _, _, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := storage.Allocate(31000); !strings.Contains(err.Error(), \"cannot allocate resources of type servicenodeportallocations at this time\") {\n\t\tt.Fatal(err)\n\t}\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func checkNodeAllocatableTest(f *framework.Framework) {\n\n\tnodeMem := getNodeMemory(f)\n\tframework.Logf(\"nodeMem says: %+v\", nodeMem)\n\n\t// calculate the allocatable mem based on capacity - reserved amounts\n\tcalculatedNodeAlloc := nodeMem.capacity.Copy()\n\tcalculatedNodeAlloc.Sub(nodeMem.systemReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.kubeReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.softEviction)\n\tcalculatedNodeAlloc.Sub(nodeMem.hardEviction)\n\n\tginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc))\n\n\t// sanity check against stated allocatable\n\tgomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0))\n}", "func SKIPPEDTestAccessAfterUnmap(t *testing.T) {\n\ttmpDir, _ := ioutil.TempDir(\"\", \"mossMMap\")\n\tdefer os.RemoveAll(tmpDir)\n\n\tf, err := os.Create(tmpDir + string(os.PathSeparator) + \"test.file\")\n\tif err != nil {\n\t\tt.Errorf(\"expected open file to work, err: %v\", err)\n\t}\n\n\tdefer f.Close()\n\n\toffset := 1024 * 1024 * 1024 // 1 GB.\n\n\tf.WriteAt([]byte(\"hello\"), int64(offset))\n\n\tvar mm mmap.MMap\n\n\tmm, err = mmap.Map(f, mmap.RDONLY, 0)\n\tif err != nil {\n\t\tt.Errorf(\"expected mmap to work, err: %v\", err)\n\t}\n\n\tx := mm[offset : offset+5]\n\n\tif string(x) != \"hello\" {\n\t\tt.Errorf(\"expected hello\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"Recovered in f\", r)\n\t\t} else {\n\t\t\tt.Errorf(\"expected recover from panic\")\n\t\t}\n\t}()\n\n\tmm.Unmap()\n\n\t/*\n\t\t\tThe following access of x results in a segfault, like...\n\n\t\t\t\tunexpected fault address 0x4060c000\n\t\t\t\tfatal error: fault\n\t\t\t\t[signal 0xb code=0x1 addr=0x4060c000 pc=0xb193f]\n\n\t\t The recover() machinery doesn't handle this situation, however,\n\t\t as it's not a normal kind of panic()\n\t*/\n\tif x[0] != 'h' {\n\t\tt.Errorf(\"expected h, but actually expected a segfault\")\n\t}\n\n\tt.Errorf(\"expected segfault, but instead unmmapped mem access worked\")\n}", "func GetPeople() models.People { return people }", "func TestClientEndpoint_GetClientAllocs_WithoutMigrateTokens(t *testing.T) {\n\tt.Parallel()\n\tassert := assert.New(t)\n\n\ts1 := TestServer(t, nil)\n\tdefer s1.Shutdown()\n\tcodec := rpcClient(t, s1)\n\ttestutil.WaitForLeader(t, s1.RPC)\n\n\t// Create the register request\n\tnode := mock.Node()\n\treg := &structs.NodeRegisterRequest{\n\t\tNode: node,\n\t\tWriteRequest: structs.WriteRequest{Region: \"global\"},\n\t}\n\n\t// Fetch the response\n\tvar resp structs.GenericResponse\n\tif err := msgpackrpc.CallWithCodec(codec, \"Node.Register\", reg, &resp); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tnode.CreateIndex = resp.Index\n\tnode.ModifyIndex = resp.Index\n\n\t// Inject fake evaluations\n\tprevAlloc := mock.Alloc()\n\tprevAlloc.NodeID = node.ID\n\talloc := mock.Alloc()\n\talloc.NodeID = node.ID\n\talloc.PreviousAllocation = prevAlloc.ID\n\talloc.DesiredStatus = structs.AllocClientStatusComplete\n\tstate := s1.fsm.State()\n\tstate.UpsertJobSummary(99, mock.JobSummary(alloc.JobID))\n\terr := state.UpsertAllocs(100, []*structs.Allocation{prevAlloc, alloc})\n\tassert.Nil(err)\n\n\t// Lookup the allocs\n\tget := &structs.NodeSpecificRequest{\n\t\tNodeID: node.ID,\n\t\tSecretID: node.SecretID,\n\t\tQueryOptions: structs.QueryOptions{Region: \"global\"},\n\t}\n\tvar resp2 structs.NodeClientAllocsResponse\n\n\terr = msgpackrpc.CallWithCodec(codec, \"Node.GetClientAllocs\", get, &resp2)\n\tassert.Nil(err)\n\n\tassert.Equal(uint64(100), resp2.Index)\n\tassert.Equal(2, len(resp2.Allocs))\n\tassert.Equal(uint64(100), resp2.Allocs[alloc.ID])\n\tassert.Equal(0, len(resp2.MigrateTokens))\n}", "func (i *IPAM) Unallocated() uint32 {\n\to, _ := i.cidr.Mask.Size()\n\treturn uint32(1) << uint(32-o)\n}", "func (p *mockPolicy) GetAllocatableMemory(s state.State) []state.Block {\n\treturn []state.Block{}\n}", "func TestGetEmpty4A(t *testing.T) {\n}", "func TestUninitializedFree(t *testing.T) {\n\tcl := &Client{}\n\tFreeTest(t, cl)\n}", "func TestGetUnsolvedProblemsCPBookInvalidResponse(t *testing.T) {\n\tts := initAPITestServerInvalid(t, []string{\"[]\", \"[]\", \"\"})\n\tdefer test.CloseServer(ts)\n\n\tproblems := GetUnsolvedProblemsCPBook(userID, \"star\")\n\tif len(problems) != 0 {\n\t\tt.Fatalf(\"Expected empty problem list\")\n\t}\n}", "func appNumAllocatorGC(ctx *zedrouterContext) {\n\n\tpubUuidToNum := ctx.pubUuidToNum\n\n\tlog.Infof(\"appNumAllocatorGC\")\n\tfreedCount := 0\n\titems := pubUuidToNum.GetAll()\n\tfor _, st := range items {\n\t\tstatus := cast.CastUuidToNum(st)\n\t\tif status.NumType != \"appNum\" {\n\t\t\tcontinue\n\t\t}\n\t\tif status.InUse {\n\t\t\tcontinue\n\t\t}\n\t\tif status.CreateTime.After(ctx.agentStartTime) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Infof(\"appNumAllocatorGC: freeing %+v\", status)\n\t\tappNumFree(ctx, status.UUID)\n\t\tfreedCount++\n\t}\n\tlog.Infof(\"appNumAllocatorGC freed %d\", freedCount)\n}", "func TestMemoryOLE(t *testing.T) {\n\tif os.Getenv(\"TEST_MEM\") == \"\" {\n\t\tt.Skip(\"Skipping TestMemoryOLE; $TEST_MEM is not set\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Error(r)\n\t\t}\n\t}()\n\n\tstart := time.Now()\n\tlimit := 50000000\n\turl := \"http://localhost/slashdot.xml\" //http://rss.slashdot.org/Slashdot/slashdot\"\n\tfmt.Printf(\"Benchmark Iterations: %d (Private Memory should stabilize around 8MB to 12MB after ~2k full or 250k minimal)\\n\", limit)\n\n\t//On Server 2016 or Windows 10 changing leakMemory=true will cause it to leak ~1.5MB per 10000 calls to unknown.QueryInterface\n\tleakMemory := true\n\n\t////////////////////////////////////////\n\t//Start outer section\n\tvar unknown *ole.IUnknown\n\tvar xmlhttp *ole.IDispatch\n\tif !leakMemory {\n\t\tcomshim.Add(1)\n\t\tdefer comshim.Done()\n\n\t\t//fmt.Println(\"CreateObject Microsoft.XMLHTTP\")\n\t\tvar err error\n\t\tunknown, err = oleutil.CreateObject(\"Microsoft.XMLHTTP\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer unknown.Release()\n\n\t\t//Memory leak starts here\n\t\txmlhttp, err = unknown.QueryInterface(ole.IID_IDispatch)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer xmlhttp.Release()\n\t}\n\t//End outer section\n\t////////////////////////////////////////\n\n\ttotalItems := uint64(0)\n\tfor i := 0; i < limit; i++ {\n\t\tif i%2000 == 0 {\n\t\t\tprivateMB, allocMB, allocTotalMB := getMemoryUsageMB(t)\n\t\t\tfmt.Printf(\"Time: %4ds Count: %7d \", time.Now().Sub(start)/time.Second, i)\n\t\t\tprintlnMemUsage(privateMB, allocMB, allocTotalMB)\n\t\t}\n\t\t//This should use less than 10MB for 1 million iterations if xmlhttp was initialized above\n\t\t//On Server 2016 or Windows 10 changing leakMemory=true above will cause it to leak ~1.5MB per 10000 calls to unknown.QueryInterface\n\t\tcount, err := getRSS(url, xmlhttp, true) //last argument is for Minimal test. Doesn't effect leak just overall allocations/time\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\ttotalItems += uint64(count)\n\t}\n\tprivateMB, allocMB, allocTotalMB := getMemoryUsageMB(t)\n\tfmt.Printf(\"Final totalItems: %d \", totalItems)\n\tprintlnMemUsage(privateMB, allocMB, allocTotalMB)\n\n}", "func TestServiceGetAllMemoryReference(t *testing.T) {\n\tassert := assert.New(t)\n\tcollection := servicesCollection()\n\n\tservices := []Service{\n\t\t{\n\t\t\tService: kong.Service{\n\t\t\t\tID: kong.String(\"first\"),\n\t\t\t\tName: kong.String(\"my-service1\"),\n\t\t\t\tHost: kong.String(\"example.com\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tService: kong.Service{\n\t\t\t\tID: kong.String(\"second\"),\n\t\t\t\tName: kong.String(\"my-service2\"),\n\t\t\t\tHost: kong.String(\"example.com\"),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, s := range services {\n\t\tassert.Nil(collection.Add(s))\n\t}\n\n\tallServices, err := collection.GetAll()\n\tassert.Nil(err)\n\tassert.Equal(len(services), len(allServices))\n\n\tallServices[0].Host = kong.String(\"new.example.com\")\n\tallServices[1].Host = kong.String(\"new.example.com\")\n\n\tservice, err := collection.Get(\"my-service1\")\n\tassert.Nil(err)\n\tassert.NotNil(service)\n\tassert.Equal(\"example.com\", *service.Host)\n\n}", "func TestPallocBitsAlloc(t *testing.T) {\n\ttests := map[string]struct {\n\t\tbefore []BitRange\n\t\tafter []BitRange\n\t\tnpages uintptr\n\t\thits []uint\n\t}{\n\t\t\"AllFree1\": {\n\t\t\tnpages: 1,\n\t\t\thits: []uint{0, 1, 2, 3, 4, 5},\n\t\t\tafter: []BitRange{{0, 6}},\n\t\t},\n\t\t\"AllFree2\": {\n\t\t\tnpages: 2,\n\t\t\thits: []uint{0, 2, 4, 6, 8, 10},\n\t\t\tafter: []BitRange{{0, 12}},\n\t\t},\n\t\t\"AllFree5\": {\n\t\t\tnpages: 5,\n\t\t\thits: []uint{0, 5, 10, 15, 20},\n\t\t\tafter: []BitRange{{0, 25}},\n\t\t},\n\t\t\"AllFree64\": {\n\t\t\tnpages: 64,\n\t\t\thits: []uint{0, 64, 128},\n\t\t\tafter: []BitRange{{0, 192}},\n\t\t},\n\t\t\"AllFree65\": {\n\t\t\tnpages: 65,\n\t\t\thits: []uint{0, 65, 130},\n\t\t\tafter: []BitRange{{0, 195}},\n\t\t},\n\t\t\"SomeFree64\": {\n\t\t\tbefore: []BitRange{{0, 32}, {64, 32}, {100, PallocChunkPages - 100}},\n\t\t\tnpages: 64,\n\t\t\thits: []uint{^uint(0)},\n\t\t\tafter: []BitRange{{0, 32}, {64, 32}, {100, PallocChunkPages - 100}},\n\t\t},\n\t\t\"NoneFree1\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages}},\n\t\t\tnpages: 1,\n\t\t\thits: []uint{^uint(0), ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"NoneFree2\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages}},\n\t\t\tnpages: 2,\n\t\t\thits: []uint{^uint(0), ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"NoneFree5\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages}},\n\t\t\tnpages: 5,\n\t\t\thits: []uint{^uint(0), ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"NoneFree65\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages}},\n\t\t\tnpages: 65,\n\t\t\thits: []uint{^uint(0), ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"ExactFit1\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages/2 - 3}, {PallocChunkPages/2 - 2, PallocChunkPages/2 + 2}},\n\t\t\tnpages: 1,\n\t\t\thits: []uint{PallocChunkPages/2 - 3, ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"ExactFit2\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages/2 - 3}, {PallocChunkPages/2 - 1, PallocChunkPages/2 + 1}},\n\t\t\tnpages: 2,\n\t\t\thits: []uint{PallocChunkPages/2 - 3, ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"ExactFit5\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages/2 - 3}, {PallocChunkPages/2 + 2, PallocChunkPages/2 - 2}},\n\t\t\tnpages: 5,\n\t\t\thits: []uint{PallocChunkPages/2 - 3, ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"ExactFit65\": {\n\t\t\tbefore: []BitRange{{0, PallocChunkPages/2 - 31}, {PallocChunkPages/2 + 34, PallocChunkPages/2 - 34}},\n\t\t\tnpages: 65,\n\t\t\thits: []uint{PallocChunkPages/2 - 31, ^uint(0)},\n\t\t\tafter: []BitRange{{0, PallocChunkPages}},\n\t\t},\n\t\t\"SomeFree161\": {\n\t\t\tbefore: []BitRange{{0, 185}, {331, 1}},\n\t\t\tnpages: 161,\n\t\t\thits: []uint{332},\n\t\t\tafter: []BitRange{{0, 185}, {331, 162}},\n\t\t},\n\t}\n\tfor name, v := range tests {\n\t\tv := v\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tb := makePallocBits(v.before)\n\t\t\tfor iter, i := range v.hits {\n\t\t\t\ta, _ := b.Find(v.npages, 0)\n\t\t\t\tif i != a {\n\t\t\t\t\tt.Fatalf(\"find #%d picked wrong index: want %d, got %d\", iter+1, i, a)\n\t\t\t\t}\n\t\t\t\tif i != ^uint(0) {\n\t\t\t\t\tb.AllocRange(a, uint(v.npages))\n\t\t\t\t}\n\t\t\t}\n\t\t\twant := makePallocBits(v.after)\n\t\t\tcheckPallocBits(t, b, want)\n\t\t})\n\t}\n}", "func TestMemory_OLEArrays(t *testing.T) {\n\tif os.Getenv(\"TEST_MEM\") == \"\" {\n\t\tt.Skip(\"Skipping TestMemory_OLEArrays; $TEST_MEM is not set\")\n\t}\n\n\t// Actually we could use any class and use in system fields, but Win32_BIOS\n\t// already has arrays inside, so it's a free COMBO!\n\ttype miniBIOS struct {\n\t\tDerivation_ []string // System-property. Available for any class.\n\t\tBIOSVersion []string\n\t\tBiosCharacteristics []uint16\n\t}\n\tvar dumbRes []miniBIOS\n\ttestQueryMem(t, &dumbRes,\n\t\t// Write a query manually cos we shouldn't specify a system field in WQL string.\n\t\t\"SELECT * FROM Win32_BIOS\")\n}", "func TestGetUnsolvedProblemRandomInvalidResponse(t *testing.T) {\n\tts := initAPITestServerInvalid(t, []string{\"[]\", \"[]\", \"\"})\n\tdefer test.CloseServer(ts)\n\n\tproblems := GetUnsolvedProblemRandom(userID)\n\tif len(problems) != 0 {\n\t\tt.Fatalf(\"Expected empty problem list\")\n\t}\n}", "func TestNetworkPktRanges(t *testing.T) {\n\t// verify auto allocation of vlans\n\tcheckCreateNetwork(t, false, \"default\", \"contiv\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv\", \"vlan\", \"10.1.1.1\", \"10.1.1.254\", 24, 1, 0)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv\")\n\n\t// auto allocation of vxlan\n\tcheckCreateNetwork(t, false, \"default\", \"contiv\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv\", \"vxlan\", \"10.1.1.1\", \"10.1.1.254\", 24, 1, 1)\n\tcheckCreateNetwork(t, false, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 0)\n\tverifyNetworkState(t, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1\", \"10.1.2.254\", 24, 2, 2)\n\tcheckCreateNetwork(t, false, \"default\", \"contiv3\", \"vxlan\", \"10.1.3.1/24\", \"10.1.3.254\", 1000)\n\tverifyNetworkState(t, \"default\", \"contiv3\", \"vxlan\", \"10.1.3.1\", \"10.1.3.254\", 24, 3, 1000)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv\")\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv2\")\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv3\")\n\n\t// verify duplicate values fail\n\tcheckCreateNetwork(t, false, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv1\")\n\n\tcheckCreateNetwork(t, false, \"default\", \"contiv1\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 0)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1)\n\tcheckDeleteNetwork(t, false, \"default\", \"contiv1\")\n\n\t// shrink ranges and try allocating\n\tcheckGlobalSet(t, false, \"default\", \"100-1000\", \"1001-2000\")\n\tcheckCreateNetwork(t, true, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 1001)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv1\", \"vlan\", \"10.1.1.1/24\", \"10.1.1.254\", 99)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 2001)\n\tcheckCreateNetwork(t, true, \"default\", \"contiv2\", \"vxlan\", \"10.1.2.1/24\", \"10.1.2.254\", 1000)\n\n\t// reset back to default values\n\tcheckGlobalSet(t, false, \"default\", \"1-4094\", \"1-10000\")\n}", "func TestReallocatePerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, oldRmName, newRmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, oldRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom, err = CreateRoom(con, newRmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = ReallocatePerson(con, fname, lname, newRmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for ReallocatePerson \", t, func() {\n\t\tConvey(\"ReallocatePerson should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"James\", \"Bond\", \"fellow\", \"Valhalla\", \"Mogadishu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Mogadishu\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"James\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Bond\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"TheSecret\", \"Coder\", \"fellow\", \"Narnia\", \"Shell\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\t// So(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestGetMinterAddresses(t *testing.T) {\n\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\taddresses, err := db.GetMinterAddresses(344178872)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif addresses != nil {\n\t\tt.Errorf(\"Addresses must be empty %d!\", len(addresses))\n\t}\n\n}", "func TestMemory_Dereference(t *testing.T) {\n\tif os.Getenv(\"TEST_MEM\") == \"\" {\n\t\tt.Skip(\"Skipping TestMemory_Dereference; $TEST_MEM is not set\")\n\t}\n\n\ttype netAdapter struct {\n\t\tAdapter struct {\n\t\t\tMACAddress string\n\t\t} `wmi:\"Element,ref\"`\n\t\tSettings struct {\n\t\t\tIPEnabled bool\n\t\t\tDHCPEnabled bool\n\t\t} `wmi:\"Setting,ref\"`\n\t}\n\tvar dumbRes []netAdapter\n\ttestQueryMem(t, &dumbRes,\n\t\tCreateQueryFrom(netAdapter{}, \"Win32_NetworkAdapterSetting \", \"\"))\n}", "func (m *MockFullNode) StateGetAllocations(arg0 context.Context, arg1 address.Address, arg2 types0.TipSetKey) (map[verifreg.AllocationId]verifreg.Allocation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateGetAllocations\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(map[verifreg.AllocationId]verifreg.Allocation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (us DeptService) CheckIfPeopleInside(dto dto.GeneralDelDto) int64 {\n\treturn 0\n}", "func (f Factory) TestGetMapIDsEmpty(t *testing.T) {\n\ta := f.initAdapter(t)\n\tdefer f.free(a)\n\n\tslice, err := a.GetMapIDs(&store.MapFilter{Pagination: store.Pagination{Offset: 100000, Limit: 5}})\n\tif err != nil {\n\t\tt.Fatalf(\"a.GetMapIDs(): err: %s\", err)\n\t}\n\n\tif got, want := len(slice), 0; got != want {\n\t\tt.Errorf(\"len(slice) = %d want %d\", got, want)\n\t}\n}", "func GetInitialPeople(url string, wg *sync.WaitGroup) (PeoplePageResponse, error) {\n\tvar page PeoplePageResponse\n\treturn page, lib.GetJSONwg(url, &page, wg)\n}", "func Test_DeviceService_GetAll_Empty(t *testing.T) {\n\th := TestHelper{}\n\trep := new(mocks.IDeviceRepository)\n\trepAuth := new(mocks.IDeviceAuthRepository)\n\ts := h.CreateTestDeviceService(rep, repAuth)\n\n\tdevices := make([]models.Device, 0)\n\trep.On(\"GetAll\").Return(devices, nil)\n\n\tall, err := s.GetAll()\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, len(all), len(devices))\n}", "func TestGetDeleted4A(t *testing.T) {\n}", "func TestGetPaymentsByRef(t *testing.T) {\n\tfmt.Println(\"mp_test : GetPaymentsByRef\")\n\n\tpmtSearch, err := mp.GetPaymentsByRef(\"QBPL-E9Z9-CTGW-LK2\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error getting the payment: %v\", err)\n\t}\n\tfmt.Println(\"Payments: \", pmtSearch)\n}", "func TestGetUnsolvedProblemsValidUserid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tproblems := GetUnsolvedProblems(userID, \"star\")\n\tif len(problems) != nUnsolvedProblems {\n\t\tt.Fatalf(\"Expected %d problems to solve, got %d\", nUnsolvedProblems, len(problems))\n\t}\n}", "func TestNoMallocs(t *testing.T) {\n\ttcs := []struct {\n\t\tvaluePtrs bool\n\t\ttopLevel bool\n\t}{\n\t\t{false, false},\n\t\t{false, true},\n\t\t{true, false},\n\t\t{true, true},\n\t}\n\n\tfor _, tc := range tcs {\n\t\tt.Run(fmt.Sprintf(\"%+v\", tc), func(t *testing.T) {\n\t\t\ta := assert.New(t)\n\t\t\tx, _ := demo.NewContainer(tc.valuePtrs)\n\t\t\ttestNoMallocs(a, x, tc.topLevel)\n\t\t})\n\t}\n}", "func (s *BBRequestTestSuite) TestGetPatient() {\n\tp, err := s.bbClient.GetPatient(\"012345\", \"543210\", \"A0000\", \"\", now)\n\tassert.Nil(s.T(), err)\n\tassert.Equal(s.T(), 1, len(p.Entries))\n\tassert.Equal(s.T(), \"20000000000001\", p.Entries[0][\"resource\"].(map[string]interface{})[\"id\"])\n}", "func TestCollectGarbage(t *testing.T) {\n\tCollectGarbage()\n}", "func (m *User) GetPeople()([]Personable) {\n return m.people\n}", "func TestPeopleTracking(t *testing.T) {\n\tsomeone := trackSomeone()\n\tassert.NotNil(t, someone.location)\n}", "func overrideAllocatableMemoryTest(f *framework.Framework, allocatablePods int) {\n\tconst (\n\t\tpodType = \"memory_limit_test_pod\"\n\t)\n\n\ttotalAllocatable := getTotalAllocatableMemory(f)\n\n\tmemValue := totalAllocatable.Value()\n\tmemPerPod := memValue / int64(allocatablePods)\n\tginkgo.By(fmt.Sprintf(\"Deploying %d pods with mem limit %v, then one additional pod\", allocatablePods, memPerPod))\n\n\t// these should all work\n\tpods := newMemLimitTestPods(allocatablePods, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10))\n\tf.PodClient().CreateBatch(pods)\n\n\tfailurePods := newMemLimitTestPods(1, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10))\n\tf.PodClient().Create(failurePods[0])\n\n\tgomega.Eventually(func() bool {\n\t\teventList, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(metav1.ListOptions{})\n\t\tframework.ExpectNoError(err)\n\t\tfor _, e := range eventList.Items {\n\t\t\t// Look for an event that shows FailedScheduling\n\t\t\tif e.Type == \"Warning\" && e.Reason == \"FailedScheduling\" && e.InvolvedObject.Name == failurePods[0].ObjectMeta.Name {\n\t\t\t\tframework.Logf(\"Found %+v event with message %+v\", e.Reason, e.Message)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}, 3*time.Minute, 10*time.Second).Should(gomega.Equal(true))\n}", "func appNumMapOnUNetGC(ctx *zedrouterContext) {\n\n\tpub := ctx.pubUUIDPairAndIfIdxToNum\n\tnumType := appNumOnUNetType\n\n\tlog.Functionf(\"appNumOnUNetMapGC\")\n\tfreedCount := 0\n\titems := pub.GetAll()\n\tfor _, item := range items {\n\t\tappNumMap := item.(types.UUIDPairAndIfIdxToNum)\n\t\tif appNumMap.NumType != numType {\n\t\t\tcontinue\n\t\t}\n\t\tif appNumMap.InUse {\n\t\t\tcontinue\n\t\t}\n\t\tif appNumMap.CreateTime.After(ctx.agentStartTime) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Functionf(\"appNumMapOnUNetGC: freeing %+v\", appNumMap)\n\t\tappNumOnUNetFree(ctx, appNumMap.BaseID, appNumMap.AppID, appNumMap.IfIdx, false)\n\t\tfreedCount++\n\t}\n\tlog.Functionf(\"appNumMapOnUNetGC freed %d\", freedCount)\n}", "func TestAllocate(t *testing.T) {\n\t_, storage, _, si, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := si.Create(context.TODO(), key(), validNewRangeAllocation(), nil, 0); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tport int\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"Allocate base port\",\n\t\t\tport: basePortRange,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate maximum from the port range\",\n\t\t\tport: basePortRange + sizePortRange - 1,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: base port minus 1\",\n\t\t\tport: basePortRange - 1,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: maximum port from the port range plus 1\",\n\t\t\tport: basePortRange + sizePortRange,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port\",\n\t\t\tport: -2,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\ttt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := storage.Allocate(tt.port)\n\t\t\tif (err == nil) != (tt.errMsg == \"\") {\n\t\t\t\tt.Fatalf(\"Error expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t\tif err != nil && err.Error() != tt.errMsg {\n\t\t\t\tt.Fatalf(\"Error message expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t})\n\t}\n\n}", "func TestGetEmails(t *testing.T) {\n\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\taddresses, err := db.GetEmails(344178872)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif addresses != nil {\n\t\tt.Errorf(\"Addresses must be empty %d!\", len(addresses))\n\t}\n\n}", "func TestFreelist_allocate(t *testing.T) {\n\tf := &freelist{ids: []pgid{3, 4, 5, 6, 7, 9, 12, 13, 18}}\n\tif id := int(f.allocate(3)); id != 3 {\n\t\tt.Fatalf(\"exp=3; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 6 {\n\t\tt.Fatalf(\"exp=6; got=%v\", id)\n\t}\n\tif id := int(f.allocate(3)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif id := int(f.allocate(2)); id != 12 {\n\t\tt.Fatalf(\"exp=12; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 7 {\n\t\tt.Fatalf(\"exp=7; got=%v\", id)\n\t}\n\tif id := int(f.allocate(0)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif id := int(f.allocate(0)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif exp := []pgid{9, 18}; !reflect.DeepEqual(exp, f.ids) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.ids)\n\t}\n\n\tif id := int(f.allocate(1)); id != 9 {\n\t\tt.Fatalf(\"exp=9; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 18 {\n\t\tt.Fatalf(\"exp=18; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif exp := []pgid{}; !reflect.DeepEqual(exp, f.ids) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.ids)\n\t}\n}", "func TestJoeFridayGetMemBasic(t *testing.T) {\n\tprof, _ := basic.NewProfiler()\n\tmem, err := prof.Get()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tp, err := json.MarshalIndent(mem, \"\", \"\\t\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Logf(\"%s\\n\", string(p))\n}", "func TestPageAllocScavenge(t *testing.T) {\n\tif GOOS == \"openbsd\" && testing.Short() {\n\t\tt.Skip(\"skipping because virtual memory is limited; see #36210\")\n\t}\n\ttype test struct {\n\t\trequest, expect uintptr\n\t}\n\tminPages := PhysPageSize / PageSize\n\tif minPages < 1 {\n\t\tminPages = 1\n\t}\n\ttype setup struct {\n\t\tbeforeAlloc map[ChunkIdx][]BitRange\n\t\tbeforeScav map[ChunkIdx][]BitRange\n\t\texpect []test\n\t\tafterScav map[ChunkIdx][]BitRange\n\t}\n\ttests := map[string]setup{\n\t\t\"AllFreeUnscavExhaust\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 1: {},\n\t\t\t\tBaseChunkIdx + 2: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 1: {},\n\t\t\t\tBaseChunkIdx + 2: {},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{^uintptr(0), 3 * PallocChunkPages * PageSize},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 1: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 2: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t},\n\t\t\"NoneFreeUnscavExhaust\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 1: {},\n\t\t\t\tBaseChunkIdx + 2: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 1: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 2: {},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{^uintptr(0), 0},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 1: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 2: {},\n\t\t\t},\n\t\t},\n\t\t\"ScavHighestPageFirst\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{1, minPages * PageSize},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(minPages)}},\n\t\t\t},\n\t\t},\n\t\t\"ScavMultiple\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{minPages * PageSize, minPages * PageSize},\n\t\t\t\t{minPages * PageSize, minPages * PageSize},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t},\n\t\t\"ScavMultiple2\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 1: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},\n\t\t\t\tBaseChunkIdx + 1: {{0, PallocChunkPages - uint(2*minPages)}},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{2 * minPages * PageSize, 2 * minPages * PageSize},\n\t\t\t\t{minPages * PageSize, minPages * PageSize},\n\t\t\t\t{minPages * PageSize, minPages * PageSize},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 1: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t},\n\t\t\"ScavDiscontiguous\": {\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 0xe: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},\n\t\t\t\tBaseChunkIdx + 0xe: {{uint(2 * minPages), PallocChunkPages - uint(2*minPages)}},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{2 * minPages * PageSize, 2 * minPages * PageSize},\n\t\t\t\t{^uintptr(0), 2 * minPages * PageSize},\n\t\t\t\t{^uintptr(0), 0},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 0xe: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t},\n\t}\n\t// Disable these tests on iOS since we have a small address space.\n\t// See #46860.\n\tif PageAlloc64Bit != 0 && goos.IsIos == 0 {\n\t\ttests[\"ScavAllVeryDiscontiguous\"] = setup{\n\t\t\tbeforeAlloc: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 0x1000: {},\n\t\t\t},\n\t\t\tbeforeScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {},\n\t\t\t\tBaseChunkIdx + 0x1000: {},\n\t\t\t},\n\t\t\texpect: []test{\n\t\t\t\t{^uintptr(0), 2 * PallocChunkPages * PageSize},\n\t\t\t\t{^uintptr(0), 0},\n\t\t\t},\n\t\t\tafterScav: map[ChunkIdx][]BitRange{\n\t\t\t\tBaseChunkIdx: {{0, PallocChunkPages}},\n\t\t\t\tBaseChunkIdx + 0x1000: {{0, PallocChunkPages}},\n\t\t\t},\n\t\t}\n\t}\n\tfor name, v := range tests {\n\t\tv := v\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tb := NewPageAlloc(v.beforeAlloc, v.beforeScav)\n\t\t\tdefer FreePageAlloc(b)\n\n\t\t\tfor iter, h := range v.expect {\n\t\t\t\tif got := b.Scavenge(h.request); got != h.expect {\n\t\t\t\t\tt.Fatalf(\"bad scavenge #%d: want %d, got %d\", iter+1, h.expect, got)\n\t\t\t\t}\n\t\t\t}\n\t\t\twant := NewPageAlloc(v.beforeAlloc, v.afterScav)\n\t\t\tdefer FreePageAlloc(want)\n\n\t\t\tcheckPageAlloc(t, want, b)\n\t\t})\n\t}\n}", "func (b *B) ReportAllocs()", "func (m *MockDatabase) GetAllTopicsUnsafe() ([]TopicKey, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllTopicsUnsafe\")\n\tret0, _ := ret[0].([]TopicKey)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func getTopPeople(w http.ResponseWriter, r *http.Request) {\n\tpage, _ := strconv.Atoi(r.URL.Query().Get(\"page\"))\n\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\n\tparser, err := MalService.GetTopPeople(page)\n\n\tif err != nil {\n\t\tview.RespondWithJSON(w, parser.ResponseCode, err.Error(), nil)\n\t} else {\n\t\tview.RespondWithJSON(w, parser.ResponseCode, parser.ResponseMessage.Error(), parser.Data)\n\t}\n}", "func (m *MockTenantServiceDao) GetServiceMemoryByTenantIDs(tenantIDs, serviceIDs []string) (map[string]map[string]interface{}, error) {\n\tret := m.ctrl.Call(m, \"GetServiceMemoryByTenantIDs\", tenantIDs, serviceIDs)\n\tret0, _ := ret[0].(map[string]map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAllocGarbageCollector_MakeRoomFor_MaxAllocs(t *testing.T) {\n\tci.Parallel(t)\n\n\tconst maxAllocs = 6\n\trequire := require.New(t)\n\n\tserver, serverAddr, cleanupS := testServer(t, nil)\n\tdefer cleanupS()\n\ttestutil.WaitForLeader(t, server.RPC)\n\n\tclient, cleanup := TestClient(t, func(c *config.Config) {\n\t\tc.GCMaxAllocs = maxAllocs\n\t\tc.GCDiskUsageThreshold = 100\n\t\tc.GCInodeUsageThreshold = 100\n\t\tc.GCParallelDestroys = 1\n\t\tc.GCInterval = time.Hour\n\t\tc.RPCHandler = server\n\t\tc.Servers = []string{serverAddr}\n\t\tc.ConsulConfig.ClientAutoJoin = new(bool)\n\t})\n\tdefer cleanup()\n\twaitTilNodeReady(client, t)\n\n\tjob := mock.Job()\n\tjob.TaskGroups[0].Count = 1\n\tjob.TaskGroups[0].Tasks[0].Driver = \"mock_driver\"\n\tjob.TaskGroups[0].Tasks[0].Config = map[string]interface{}{\n\t\t\"run_for\": \"30s\",\n\t}\n\n\tindex := uint64(98)\n\tnextIndex := func() uint64 {\n\t\tindex++\n\t\treturn index\n\t}\n\n\tupsertJobFn := func(server *nomad.Server, j *structs.Job) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertJob(structs.MsgTypeTestSetup, nextIndex(), j))\n\t\trequire.NoError(state.UpsertJobSummary(nextIndex(), mock.JobSummary(j.ID)))\n\t}\n\n\t// Insert the Job\n\tupsertJobFn(server, job)\n\n\tupsertAllocFn := func(server *nomad.Server, a *structs.Allocation) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertAllocs(structs.MsgTypeTestSetup, nextIndex(), []*structs.Allocation{a}))\n\t}\n\n\tupsertNewAllocFn := func(server *nomad.Server, j *structs.Job) *structs.Allocation {\n\t\talloc := mock.Alloc()\n\t\talloc.Job = j\n\t\talloc.JobID = j.ID\n\t\talloc.NodeID = client.NodeID()\n\n\t\tupsertAllocFn(server, alloc)\n\n\t\treturn alloc.Copy()\n\t}\n\n\tvar allocations []*structs.Allocation\n\n\t// Fill the node with allocations\n\tfor i := 0; i < maxAllocs; i++ {\n\t\tallocations = append(allocations, upsertNewAllocFn(server, job))\n\t}\n\n\t// Wait until the allocations are ready\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := len(client.getAllocRunners())\n\n\t\treturn ar == maxAllocs, fmt.Errorf(\"Expected %d allocs, got %d\", maxAllocs, ar)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not start: %v\", err)\n\t})\n\n\t// Mark the first three as terminal\n\tfor i := 0; i < 3; i++ {\n\t\tallocations[i].DesiredStatus = structs.AllocDesiredStatusStop\n\t\tupsertAllocFn(server, allocations[i].Copy())\n\t}\n\n\t// Wait until the allocations are stopped\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tstopped := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.Alloc().TerminalStatus() {\n\t\t\t\tstopped++\n\t\t\t}\n\t\t}\n\n\t\treturn stopped == 3, fmt.Errorf(\"Expected %d terminal allocs, got %d\", 3, stopped)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not terminate: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// A single allocation should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 1, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 1, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// 2 allocations should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 2, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 2, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// check that all 8 get run eventually\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tif len(ar) != 8 {\n\t\t\treturn false, fmt.Errorf(\"expected 8 ARs, found %d: %v\", len(ar), ar)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(err)\n\t})\n}", "func TestGetMembers(t *testing.T) {\n\tmembers := member.GetMembers()\n\n\tif len(members) < 1 {\n\t\tt.Errorf(\"No members loaded from database.\")\n\t} else {\n\t\tfmt.Println(\"member.go Func GetMembers PASS\")\n\t}\n}", "func TestLookup(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Handle the case where the GDS returns an error\n\tmgds.UseError(gdsmock.LookupRPC, codes.NotFound, \"could not find peer with that common name\")\n\tpeer, err := cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"rpc error: code = NotFound desc = could not find peer with that common name\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Handle the case where the GDS returns an error in the lookup reply\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn &gds.LookupReply{\n\t\t\tError: &gds.Error{\n\t\t\t\tCode: 99,\n\t\t\t\tMessage: \"the GDS really shouldn't be returning these errors\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tpeer, err = cache.Lookup(\"unknown\")\n\trequire.EqualError(t, err, \"[99] the GDS really shouldn't be returning these errors\")\n\trequire.Nil(t, peer, \"peer should be nil when an error is returned\")\n\n\t// Lookup should not error if GDS returns a nil identity and nil signing certificate\n\trequire.NoError(t, mgds.UseFixture(gdsmock.LookupRPC, \"testdata/leonardo.trisa.dev.pb.json\"))\n\tpeer, err = cache.Lookup(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Nil(t, peer.SigningKey(), \"signing key should be nil when no certificate is returned\")\n\n\t// Configure a reply fixture for the other lookup test cases\n\treply := &gds.LookupReply{}\n\trequire.NoError(t, loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", reply))\n\tmgds.OnLookup = func(context.Context, *gds.LookupRequest) (*gds.LookupReply, error) {\n\t\treturn reply, nil\n\t}\n\n\t// Generate keys to distinguish between identity and signing certificates\n\torigCert, origKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tidentityCert, _, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\tsigningCert, signingKey, err := generateCertificate()\n\trequire.NoError(t, err, \"could not generate certificate\")\n\n\t// Lookup should store the identity key if the identity certificate is available on the lookup reply\n\treply.CommonName = \"identity\"\n\treply.IdentityCertificate = origCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should be stored\")\n\n\t// Lookup should not overwrite an existing key on the peer\n\treply.IdentityCertificate = identityCert\n\tpeer, err = cache.Lookup(\"identity\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, origKey, peer.SigningKey(), \"identity key should not be overwritten\")\n\n\t// Lookup should store the signing key if the signing certificate is available on the lookup reply\n\treply.CommonName = \"signing\"\n\treply.IdentityCertificate = nil\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"signing\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Lookup should prefer the signing certificate over the identity certificate if both are available on the lookup reply\n\treply.CommonName = \"both\"\n\treply.IdentityCertificate = identityCert\n\treply.SigningCertificate = signingCert\n\tpeer, err = cache.Lookup(\"both\")\n\trequire.NoError(t, err, \"could not lookup peer from directory service\")\n\trequire.Equal(t, signingKey, peer.SigningKey(), \"signing key should be stored\")\n\n\t// Handle the case where the GDS returns valid responses\n\tmgds.Reset()\n\tmgds.OnLookup = func(_ context.Context, in *gds.LookupRequest) (out *gds.LookupReply, err error) {\n\t\tout = &gds.LookupReply{}\n\t\tswitch in.CommonName {\n\t\tcase \"leonardo.trisa.dev\":\n\t\t\tif err = loadGRPCFixture(\"testdata/leonardo.trisa.dev.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase \"donatello.example.com\":\n\t\t\tif err = loadGRPCFixture(\"testdata/donatello.example.com.pb.json\", out); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.NotFound, \"unknown TRISA counterparty\")\n\t\t}\n\t\treturn out, nil\n\t}\n\n\t// Test concurrent Lookup calls\n\tt.Run(\"lookup\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tpeer string\n\t\t}{\n\t\t\t{\"lookup-leonardo\", \"leonardo.trisa.dev\"},\n\t\t\t{\"lookup-donatello\", \"donatello.example.com\"},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttt := tt\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tp, err := cache.Lookup(tt.peer)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, p)\n\t\t\t})\n\t\t}\n\t})\n\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.SearchRPC])\n\trequire.Equal(t, 2, mgds.Calls[gdsmock.LookupRPC])\n\trequire.Equal(t, 0, mgds.Calls[gdsmock.StatusRPC])\n\n\t// Cache should contain the two peers\n\tleonardo, err := cache.Get(\"leonardo.trisa.dev\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"19d84515-007a-48cc-9efd-b153a263e77c\", leonardo.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", leonardo.Info().RegisteredDirectory)\n\trequire.Equal(t, \"leonardo.trisa.dev\", leonardo.Info().CommonName)\n\trequire.Equal(t, \"leonardo.trisa.dev:8000\", leonardo.Info().Endpoint)\n\n\tdonatello, err := cache.Get(\"donatello.example.com\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\", donatello.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", donatello.Info().RegisteredDirectory)\n\trequire.Equal(t, \"donatello.example.com\", donatello.Info().CommonName)\n\trequire.Equal(t, \"donatello.example.com:443\", donatello.Info().Endpoint)\n}", "func (m *MockCandidatePropertyGetter) UnusedIsolatedDevices() []*core.IsolatedDeviceDesc {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UnusedIsolatedDevices\")\n\tret0, _ := ret[0].([]*core.IsolatedDeviceDesc)\n\treturn ret0\n}", "func (m *MockTenantServiceDao) GetServiceMemoryByServiceIDs(serviceIDs []string) (map[string]map[string]interface{}, error) {\n\tret := m.ctrl.Call(m, \"GetServiceMemoryByServiceIDs\", serviceIDs)\n\tret0, _ := ret[0].(map[string]map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestDeleteMembers(t *testing.T) {\n\tcalls := []testutils.TestCmd{\n\t\tfakeRestoreSuccessCommand,\n\t}\n\tioshim := common.NewMockIOShim(calls)\n\tdefer ioshim.VerifyCalls(t, calls)\n\tiMgr := NewIPSetManager(applyAlwaysCfg, ioshim)\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"1.1.1.1\", \"a\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"3.3.3.3\", \"c\"))\n\t// create to destroy later\n\tiMgr.CreateIPSets([]*IPSetMetadata{TestCIDRSet.Metadata})\n\t// clear dirty cache, otherwise a set deletion will be a no-op\n\tiMgr.clearDirtyCache()\n\n\t// will remove this member\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"1.1.1.1\", \"a\"))\n\t// will add this member\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"5.5.5.5\", \"e\"))\n\t// won't add/remove this member since the next two calls cancel each other out\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"4.4.4.4\", \"d\"))\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"4.4.4.4\", \"d\"))\n\t// won't add/remove this member since the next two calls cancel each other out\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\t// destroy extra set\n\tiMgr.DeleteIPSet(TestCIDRSet.PrefixName, util.SoftDelete)\n\n\texpectedLines := []string{\n\t\tfmt.Sprintf(\"-N %s --exist nethash\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-D %s 1.1.1.1\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-A %s 5.5.5.5\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-F %s\", TestCIDRSet.HashedName),\n\t\tfmt.Sprintf(\"-X %s\", TestCIDRSet.HashedName),\n\t\t\"\",\n\t}\n\tsortedExpectedLines := testAndSortRestoreFileLines(t, expectedLines)\n\tcreator := iMgr.fileCreatorForApply(len(calls))\n\tactualLines := testAndSortRestoreFileString(t, creator.ToString())\n\tdptestutils.AssertEqualLines(t, sortedExpectedLines, actualLines)\n\twasFileAltered, err := creator.RunCommandOnceWithFile(\"ipset\", \"restore\")\n\trequire.NoError(t, err, \"ipset restore should be successful\")\n\trequire.False(t, wasFileAltered, \"file should not be altered\")\n}", "func testCheckDDCloudAddressListDestroy(state *terraform.State) error {\n\tfor _, res := range state.RootModule().Resources {\n\t\tif res.Type != \"ddcloud_address_list\" {\n\t\t\tcontinue\n\t\t}\n\n\t\taddressListID := res.Primary.ID\n\n\t\tclient := testAccProvider.Meta().(*providerState).Client()\n\t\taddressList, err := client.GetIPAddressList(addressListID)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif addressList != nil {\n\t\t\treturn fmt.Errorf(\"address list '%s' still exists\", addressListID)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestMgmt_GetAllIDs(t *testing.T) {\n\tfor i, objType := range vpc.ObjTypes() {\n\t\tobjType := objType\n\t\tt.Run(objType.String(), func(t *testing.T) {\n\t\t\tmgr, err := mgmt.New(nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"[%d] unable to create new VPC Management handle: %v\", i, err)\n\t\t\t}\n\t\t\tdefer mgr.Close()\n\n\t\t\tids, err := mgr.GetAllIDs(objType)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"[%d] unable to get IDs for %s VPC objects: %v\", i, objType, err)\n\t\t\t}\n\n\t\t\t_ = ids // Not sure what to do with these UUIDs\n\t\t})\n\t}\n}", "func (m *MockPoolRegistry) HardDeleteAllocations(allocations []registry.BrickAllocation) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HardDeleteAllocations\", allocations)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestDryRunAllocate(t *testing.T) {\n\tpr, err := net.ParsePortRange(\"10000-10200\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Allocate some ports before calling\n\tpreviouslyAllocated := []int{10000, 10010, 10020}\n\tr, err := NewInMemory(*pr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, port := range previouslyAllocated {\n\t\t_ = r.Allocate(port)\n\t}\n\tfreeAtStart := r.Free()\n\n\t// Do some allocations with a dry run operation\n\ttoAllocate := []int{\n\t\t10000,\n\t\t10030,\n\t\t10030,\n\t\t10040,\n\t}\n\texpectedErrors := []error{\n\t\tErrAllocated,\n\t\tnil,\n\t\tErrAllocated,\n\t\tnil,\n\t}\n\top := StartOperation(r, true)\n\tfor i, port := range toAllocate {\n\t\terr := op.Allocate(port)\n\t\tif err != expectedErrors[i] {\n\t\t\tt.Errorf(\"%v: expected error %v but got %v\", i, expectedErrors[i], err)\n\t\t}\n\t}\n\n\t// Make sure no port allocations were actually made by the dry run\n\tfreeAtEnd := r.Free()\n\tif freeAtStart != freeAtEnd {\n\t\tt.Errorf(\"expected %v free ports but got %v\", freeAtStart, freeAtEnd)\n\t}\n}", "func (c IpRemoteHost_getUdpPort) AllocResults() (IpRemoteHost_getUdpPort_Results, error) {\n\tr, err := c.Call.AllocResults(capnp.ObjectSize{DataSize: 0, PointerCount: 1})\n\treturn IpRemoteHost_getUdpPort_Results{Struct: r}, err\n}", "func (v *Validator) GetPeople(id int) (*model.People, map[string]interface{}, int, error) {\n\tif id <= 0 {\n\t\treturn nil, nil, http.StatusBadRequest, errors.ErrInvalidID\n\t}\n\treturn v.api.GetPeople(id)\n}", "func (m *Mock) People(distinctId string) *MockPeople {\n\tp, _ := m.people.LoadOrStore(distinctId, &MockPeople{\n\t\tProperties: map[string]interface{}{},\n\t})\n\n\treturn p.(*MockPeople)\n}", "func TestHasNoCollisions(t *testing.T) {\n\tCOUNT := 100 * 1000\n\tused := make(map[string]bool)\n\tfor i := 0; i < COUNT; i++ {\n\t\tid, err := Gonoid()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Nanoid error: %v\", err)\n\t\t}\n\t\tif used[id] {\n\t\t\tt.Errorf(\"Collision error! Id %v found for test arr %v\", id, used)\n\t\t}\n\t\tused[id] = true\n\t}\n}", "func (c IpNetwork_getRemoteHostByName) AllocResults() (IpNetwork_getRemoteHostByName_Results, error) {\n\tr, err := c.Call.AllocResults(capnp.ObjectSize{DataSize: 0, PointerCount: 1})\n\treturn IpNetwork_getRemoteHostByName_Results{Struct: r}, err\n}", "func CheckinPeopleListGET(w http.ResponseWriter, r *http.Request) {\n\texclude := r.URL.Query().Get(\"exclude\")\n\n\tpeople, err := people.GetPeople(nil, 0, 0)\n\tif err != nil {\n\t\tError(w, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar excludePeople = make(map[string]int64)\n\tif exclude != \"\" {\n\t\texcludePeople, err = exclude_record.GetExcludePeopleSetNow()\n\t}\n\n\tvar peopleRet = []*schema.DBPerson{}\n\tfor _, p := range people {\n\t\tif _, ok := excludePeople[p.ID]; !ok {\n\t\t\tpeopleRet = append(peopleRet, p)\n\t\t}\n\t}\n\n\trespondJSON(peopleRet, w, r)\n}", "func Test_DeviceService_Get_EmptyIP(t *testing.T) {\n\ts := DeviceService{}\n\t_, err := s.Get(\"\")\n\tassert.Error(t, err)\n}", "func TestUnreachableMarks(t *testing.T) {\n\tseeds := []string {\"127.0.0.1:6000\",}\n\tmanager1 := CreatePeerManager(6000, 6001, nil, FullMode)\n\tmanager2 := CreatePeerManager(7000, 7001, seeds, FullMode)\n\tmanager3 := CreatePeerManager(8000, 8001, seeds, FullMode)\n\n\t// Change update period to lengthen the time between marking a peer unreachable \n\t// and the next status update\n\tmanager1.StatusUpdatePeriod=500*time.Millisecond\n\tmanager2.StatusUpdatePeriod=500*time.Millisecond\n\tmanager3.StatusUpdatePeriod=500*time.Millisecond\n\n\tmarkPeer := func(t *testing.T) {\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tmanager1.MarkPeerUnreachable(\"127.0.0.1:8001\")\n\t\tavailable := GetPeerManagerAvailablePeers(manager1)\n\t\texpected := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\"}\n\t\tif !MapOnlyContains(available, expected) {\n\t\t\tt.Errorf(\"Peer 127.0.0.1:8001 wasn't marked unreachable %v\\n\", available)\n\t\t}\n\t}\n\n\t// After some time has passed all the peers should be available again\n\tallPeers := []string {\"127.0.0.1:6001\", \"127.0.0.1:7001\", \"127.0.0.1:8001\"}\n\tPeerManagerPropagationHelper(t, manager1, manager2, manager3,\n\t\tallPeers, allPeers, allPeers, markPeer, 3200*time.Millisecond, 8*time.Second)\n}", "func TestGet1024(t *testing.T) {\n\thm, _ := NewHashMap(1024)\n\ttestGetN(testN, hm)\n}", "func TestGetWithBadUserUUID(t *testing.T) {\n\tclearTable()\n\n\treq, _ := http.NewRequest(\"GET\",\n\t\t\"/api/v1/namespace/pavedroad.io/{{.Name}}/43ae99c9\", nil)\n\tresponse := executeRequest(req)\n\n\tcheckResponseCode(t, http.StatusBadRequest, response.Code)\n\n\tvar m map[string]string\n\tjson.Unmarshal(response.Body.Bytes(), &m)\n\tif m[\"error\"] != \"400: invalid UUID: 43ae99c9\" {\n\t\tt.Errorf(\"Expected the 'error' key of the response to be set to '400: invalid UUID: 43ae99c9'. Got '%s'\", m[\"error\"])\n\t}\n}", "func (m *MalService) GetPeople(id int) (people.PeopleParser, error) {\n\treturn people.InitPeopleParser(m.Config, id)\n}", "func TestIDAllocator(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tstore, _, stopper := createTestStore(t)\n\tdefer stopper.Stop()\n\tallocd := make(chan int, 100)\n\tidAlloc, err := newIDAllocator(keys.RangeIDGenerator, store.ctx.DB, 2, 10, stopper)\n\tif err != nil {\n\t\tt.Errorf(\"failed to create idAllocator: %v\", err)\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\tgo func() {\n\t\t\tfor j := 0; j < 10; j++ {\n\t\t\t\tid, err := idAlloc.Allocate()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tallocd <- int(id)\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Verify all IDs accounted for.\n\tids := make([]int, 100)\n\tfor i := 0; i < 100; i++ {\n\t\tids[i] = <-allocd\n\t}\n\tsort.Ints(ids)\n\tfor i := 0; i < 100; i++ {\n\t\tif ids[i] != i+2 {\n\t\t\tt.Errorf(\"expected \\\"%d\\\"th ID to be %d; got %d\", i, i+2, ids[i])\n\t\t}\n\t}\n\n\t// Verify no leftover IDs.\n\tselect {\n\tcase id := <-allocd:\n\t\tt.Errorf(\"there appear to be leftover IDs, starting with %d\", id)\n\tdefault:\n\t\t// Expected; noop.\n\t}\n}", "func (f Factory) TestGetMapIDsPagination(t *testing.T) {\n\ta := f.initAdapter(t)\n\tdefer f.free(a)\n\n\tfor i := 0; i < 10; i++ {\n\t\tfor j := 0; j < 10; j++ {\n\t\t\tsegment := cstesting.RandomSegment()\n\t\t\tsegment.Link.Meta[\"mapId\"] = fmt.Sprintf(\"map%d\", i)\n\t\t\ta.SaveSegment(segment)\n\t\t}\n\t}\n\n\tslice, err := a.GetMapIDs(&store.MapFilter{Pagination: store.Pagination{Offset: 3, Limit: 5}})\n\tif err != nil {\n\t\tt.Fatalf(\"a.GetMapIDs(): err: %s\", err)\n\t}\n\n\tif got, want := len(slice), 5; got != want {\n\t\tt.Errorf(\"len(slice) = %d want %d\", got, want)\n\t}\n}", "func (b *B) ReportAllocs() {}", "func TestMacAddress(t *testing.T) {\n\tb := getMACAddr()\n\tzeroBytes := make([]byte, len(b))\n\tassert.NotEqual(t, b, zeroBytes, \"Random bytes all zero\")\n}", "func TestGetMinterDeposAddress(t *testing.T) {\n\n\ta := InitApp(\"https://mbank.dl-dev.ru/api/\")\n\n\taddr, err := a.GetMinterDeposAddress(BitcoinAddress, \"BIP\", 0.1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif addr == nil {\n\t\tt.Errorf(\"Empty responce\")\n\t}\n\n\tif addr.Data.Tag == \"\" || addr.Data.Address == \"\" {\n\t\tt.Errorf(\"Empty tag or address: %s and %s \", addr.Data.Tag, addr.Data.Address)\n\t}\n\n}", "func TestFreelist_free(t *testing.T) {\n\tf := newFreelist()\n\tf.free(100, &page{id: 12})\n\tif !reflect.DeepEqual([]pgid{12}, f.pending[100]) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", []pgid{12}, f.pending[100])\n\t}\n}", "func setupTrivialNoAllocTest(logf logger.Logf, traf *TrafficGen) {\n\tgo func() {\n\t\tb := make([]byte, 1600)\n\t\tfor {\n\t\t\tn := traf.Generate(b, 16)\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttraf.GotPacket(b[0:n+16], 16)\n\t\t}\n\t}()\n}", "func TestUnresponsive(t *testing.T) {\n\taddrs, teardown := gorums.TestSetup(t, 1, func(_ int) gorums.ServerIface {\n\t\tgorumsSrv := gorums.NewServer()\n\t\tsrv := &testSrv{}\n\t\tRegisterUnresponsiveServer(gorumsSrv, srv)\n\t\treturn gorumsSrv\n\t})\n\tdefer teardown()\n\n\tmgr := NewManager(\n\t\tgorums.WithDialTimeout(100*time.Millisecond),\n\t\tgorums.WithGrpcDialOptions(\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\t),\n\t)\n\t_, err := mgr.NewConfiguration(gorums.WithNodeList(addrs))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tnode := mgr.Nodes()[0]\n\n\tfor i := 0; i < 1000; i++ {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)\n\t\t_, err = node.TestUnresponsive(ctx, &Empty{})\n\t\tif err != nil && errors.Is(err, context.Canceled) {\n\t\t\tt.Error(err)\n\t\t}\n\t\tcancel()\n\t}\n}", "func FreeTest(t *testing.T, cl *Client) {\n\tpanicked := false\n\tif PanickedDuringFree(cl, &panicked); panicked {\n\t\tt.Errorf(\"panic while freeing an uninitialized client\")\n\t}\n}", "func TestGetNodeMonUsageNoZoneLabels(t *testing.T) {\n\tfor i := 1; i < 5; i++ {\n\t\tclientset := test.New(i)\n\t\tc := New(&clusterd.Context{Clientset: clientset}, \"ns\", \"\", false, metav1.OwnerReference{}, &sync.Mutex{})\n\t\tsetCommonMonProperties(c, 0, cephv1.MonSpec{Count: 3, AllowMultiplePerNode: true}, \"myversion\")\n\n\t\tnodeZones, err := c.getNodeMonUsage()\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, len(nodeZones), 1)\n\t\tassert.Equal(t, len(nodeZones[0]), i)\n\t}\n}", "func GetPeople() []Person {\n\treturn all()\n}", "func TestFreelist_free_overflow(t *testing.T) {\n\tf := newFreelist()\n\tf.free(100, &page{id: 12, overflow: 3})\n\tif exp := []pgid{12, 13, 14, 15}; !reflect.DeepEqual(exp, f.pending[100]) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.pending[100])\n\t}\n}", "func (th *testHelper) assertNotPresentInCollectionM(chaincodeName, marbleName string, peerList ...*nwo.Peer) {\n\tcommand := commands.ChaincodeQuery{\n\t\tChannelID: th.channelID,\n\t\tName: chaincodeName,\n\t\tCtor: fmt.Sprintf(`{\"Args\":[\"readMarble\",\"%s\"]}`, marbleName),\n\t}\n\texpectedMsg := \"private data matching public hash version is not available\"\n\tfor _, peer := range peerList {\n\t\tth.queryChaincode(peer, command, expectedMsg, false)\n\t}\n}", "func TestPallocBitsFree(t *testing.T) {\n\ttests := map[string]struct {\n\t\tbeforeInv []BitRange\n\t\tafterInv []BitRange\n\t\tfrees []uint\n\t\tnpages uintptr\n\t}{\n\t\t\"SomeFree\": {\n\t\t\tnpages: 1,\n\t\t\tbeforeInv: []BitRange{{0, 32}, {64, 32}, {100, 1}},\n\t\t\tfrees: []uint{32},\n\t\t\tafterInv: []BitRange{{0, 33}, {64, 32}, {100, 1}},\n\t\t},\n\t\t\"NoneFree1\": {\n\t\t\tnpages: 1,\n\t\t\tfrees: []uint{0, 1, 2, 3, 4, 5},\n\t\t\tafterInv: []BitRange{{0, 6}},\n\t\t},\n\t\t\"NoneFree2\": {\n\t\t\tnpages: 2,\n\t\t\tfrees: []uint{0, 2, 4, 6, 8, 10},\n\t\t\tafterInv: []BitRange{{0, 12}},\n\t\t},\n\t\t\"NoneFree5\": {\n\t\t\tnpages: 5,\n\t\t\tfrees: []uint{0, 5, 10, 15, 20},\n\t\t\tafterInv: []BitRange{{0, 25}},\n\t\t},\n\t\t\"NoneFree64\": {\n\t\t\tnpages: 64,\n\t\t\tfrees: []uint{0, 64, 128},\n\t\t\tafterInv: []BitRange{{0, 192}},\n\t\t},\n\t\t\"NoneFree65\": {\n\t\t\tnpages: 65,\n\t\t\tfrees: []uint{0, 65, 130},\n\t\t\tafterInv: []BitRange{{0, 195}},\n\t\t},\n\t}\n\tfor name, v := range tests {\n\t\tv := v\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tb := makePallocBits(v.beforeInv)\n\t\t\tinvertPallocBits(b)\n\t\t\tfor _, i := range v.frees {\n\t\t\t\tb.Free(i, uint(v.npages))\n\t\t\t}\n\t\t\twant := makePallocBits(v.afterInv)\n\t\t\tinvertPallocBits(want)\n\t\t\tcheckPallocBits(t, b, want)\n\t\t})\n\t}\n}", "func TestGetMemPages(t *testing.T) {\n\ttype testcase struct {\n\t\tname string\n\t\tmr *MemoryReader\n\t\tstart uint64\n\t\tend uint64\n\t\texpectedError error\n\t}\n\n\tpid, err := getTestImgPID()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create a temporary empty memory pages file for testing\n\ttmpFilePath := filepath.Join(os.TempDir(), \"pages-0.img\")\n\ttmpFile, err := os.Create(tmpFilePath)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\ttmpFile.Close()\n\t\tif err := os.Remove(tmpFile.Name()); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tmr, err := NewMemoryReader(testImgsDir, pid, sysPageSize)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttestCases := []testcase{\n\t\t{\n\t\t\tname: \"Zero memory area size\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: 0,\n\t\t\tend: 0,\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 1\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Valid pagemap entry 2\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"Invalid pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: testImgsDir,\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: mr.pagesID + 1,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[0].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[0].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[0].GetNrPages()),\n\t\t\texpectedError: errors.New(\"no such file or directory\"),\n\t\t},\n\t\t{\n\t\t\tname: \"Empty pages file\",\n\t\t\tmr: &MemoryReader{\n\t\t\t\tcheckpointDir: os.TempDir(),\n\t\t\t\tpid: pid,\n\t\t\t\tpageSize: sysPageSize,\n\t\t\t\tpagesID: 0,\n\t\t\t\tpagemapEntries: mr.GetPagemapEntries(),\n\t\t\t},\n\t\t\tstart: mr.pagemapEntries[1].GetVaddr(),\n\t\t\tend: mr.pagemapEntries[1].GetVaddr() + uint64(uint32(sysPageSize)*mr.pagemapEntries[1].GetNrPages()),\n\t\t\texpectedError: errors.New(\"EOF\"),\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tbuff, err := tc.mr.GetMemPages(tc.start, tc.end)\n\t\t\tif err != nil && tc.expectedError != nil {\n\t\t\t\tif !strings.Contains(err.Error(), tc.expectedError.Error()) {\n\t\t\t\t\tt.Errorf(\"Expected error: %v, got error: %v\", tc.expectedError, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tc.expectedError == nil && buff == nil {\n\t\t\t\tt.Errorf(\"Returned memory chunk is expected to be non-empty\")\n\t\t\t}\n\t\t})\n\t}\n}", "func TestPagination(t *testing.T) {\n\tts := NewTestServer(allowedAccessToken)\n\tdefer ts.Close()\n\n\tresp, _ := ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 4,\n\t\tOffset: 0,\n\t})\n\n\tif len(resp.Users) != 4 {\n\t\tt.Errorf(\"invalid nums of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[3].Id != 3 {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[3])\n\t\treturn\n\t}\n\n\tresp, _ = ts.Client.FindUsers(SearchRequest{\n\t\tLimit: 6,\n\t\tOffset: 3,\n\t})\n\n\tif len(resp.Users) != 6 {\n\t\tt.Errorf(\"invalid number of users: %d\", len(resp.Users))\n\t\treturn\n\t}\n\n\tif resp.Users[0].Name != \"Everett Dillard\" {\n\t\tt.Errorf(\"invalid user at row 3: %v\", resp.Users[0])\n\t\treturn\n\t}\n}", "func TestGetNone4A(t *testing.T) {\n}", "func TestHasNoCollisions(t *testing.T) {\n\tCOUNT := 100 * 1000\n\tused := make(map[string]bool)\n\tfor i := 0; i < COUNT; i++ {\n\t\tid, err := Nanoid()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Nanoid error: %v\", err)\n\t\t}\n\t\tif used[id] {\n\t\t\tt.Errorf(\"Collision error! Id %v found for test arr %v\", id, used)\n\t\t}\n\t\tused[id] = true\n\t}\n}", "func TestStripNames(t *testing.T) {\n\taddresses := []string{\n\t\t\"[email protected]\",\n\t\t\"[email protected]\",\n\t\t\"invalid1\",\n\t\t\"John Doe <[email protected]>\",\n\t\t\"<[email protected]>\",\n\t\t\"invalid2\",\n\t}\n\n\texpected := map[string]struct{}{\n\t\t\"[email protected]\": {},\n\t\t\"[email protected]\": {},\n\t\t\"invalid1\": {},\n\t\t\"[email protected]\": {},\n\t\t\"[email protected]\": {},\n\t\t\"invalid2\": {},\n\t}\n\n\tresult := stripNames(addresses)\n\n\tif len(result) != len(expected) {\n\t\tt.Fatalf(\"stripNames: Expected %d addresses, got %d: \\n%v\", len(expected), len(result), result)\n\t}\n\n\tfor _, addr := range result {\n\t\tif _, ok := expected[addr]; !ok {\n\t\t\tt.Errorf(\"stripNames: Address %q was not expected\", addr)\n\t\t}\n\t}\n}", "func testTLSCertsAllocate(t *testing.T) {\n\tvar (\n\t\terr error\n\t)\n\n\ttestTLSCerts = &testTLSCertsStruct{}\n\n\ttestTLSCerts.caCertPEMBlock, testTLSCerts.caKeyPEMBlock, err = icertpkg.GenCACert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization CA\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\ttime.Hour,\n\t\t\"\",\n\t\t\"\")\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.GenCACert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock, err = icertpkg.GenEndpointCert(\n\t\ticertpkg.GenerateKeyAlgorithmEd25519,\n\t\tpkix.Name{\n\t\t\tOrganization: []string{\"Test Organization Endpoint\"},\n\t\t\tCountry: []string{},\n\t\t\tProvince: []string{},\n\t\t\tLocality: []string{},\n\t\t\tStreetAddress: []string{},\n\t\t\tPostalCode: []string{},\n\t\t},\n\t\t[]string{},\n\t\t[]net.IP{net.ParseIP(\"127.0.0.1\")},\n\t\ttime.Hour,\n\t\ttestTLSCerts.caCertPEMBlock,\n\t\ttestTLSCerts.caKeyPEMBlock,\n\t\t\"\",\n\t\t\"\")\n\n\tif nil != err {\n\t\tt.Fatalf(\"icertpkg.genEndpointCert() failed: %v\", err)\n\t}\n\n\ttestTLSCerts.endpointTLSCert, err = tls.X509KeyPair(testTLSCerts.endpointCertPEMBlock, testTLSCerts.endpointKeyPEMBlock)\n\tif nil != err {\n\t\tt.Fatalf(\"tls.LoadX509KeyPair() failed: %v\", err)\n\t}\n}", "func (k *KRPC) notQueried(queriedNodes *boom.BloomFilter, contacts []bucket.ContactIdentifier) []bucket.ContactIdentifier {\n\tif contacts == nil {\n\t\treturn []bucket.ContactIdentifier{}\n\t}\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\tret := []bucket.ContactIdentifier{}\n\tfor _, c := range contacts {\n\t\tif !queriedNodes.TestAndAdd([]byte(c.GetAddr().String())) {\n\t\t\tret = append(ret, c)\n\t\t}\n\t}\n\treturn ret\n}", "func (o *User) GetPeopleOk() ([]MicrosoftGraphPerson, bool) {\n\tif o == nil || o.People == nil {\n\t\tvar ret []MicrosoftGraphPerson\n\t\treturn ret, false\n\t}\n\treturn *o.People, true\n}", "func testNoMallocs(a *assert.Assertions, x *demo.ContainerType, topLevel bool) {\n\tstats := runtime.MemStats{}\n\ttimer := time.NewTimer(1 * time.Second)\n\tfn := func(ctx demo.TargetContext, x demo.Target) (ret demo.TargetDecision) { return }\n\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\ta.Fail(\"timeout\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tvar err error\n\t\t\truntime.ReadMemStats(&stats)\n\t\t\tmemBefore := stats.Mallocs\n\n\t\t\tif topLevel {\n\t\t\t\t_, _, err = demo.WalkTarget(x, fn)\n\t\t\t} else {\n\t\t\t\t_, _, err = x.WalkTarget(fn)\n\t\t\t}\n\t\t\truntime.ReadMemStats(&stats)\n\n\t\t\ta.NoError(err)\n\t\t\tmemAfter := stats.Mallocs\n\t\t\tif memAfter == memBefore {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func TestUnset1024(t *testing.T) {\n\thm, _ := NewHashMap(1024)\n\ttestUnsetN(testN, hm)\n}", "func (m *MalService) GetTopPeople(page ...int) (top.PeopleParser, error) {\n\treturn top.InitPeopleParser(m.Config, page...)\n}", "func TestAvailableCalculation(t *testing.T) {\n\tassert := require.New(t)\n\n\ta, err := NewMemoryIPAllocator(\"10.0.0.1/24\", nil)\n\tassert.NoError(err)\n\tassert.Equal(255, a.Available())\n\n\ta, err = NewMemoryIPAllocator(\"10.0.0.0/24\", nil)\n\tassert.NoError(err)\n\tassert.Equal(256, a.Available())\n\n\ta, err = NewMemoryIPAllocator(\"10.0.0.10/24\", nil)\n\tassert.NoError(err)\n\tassert.Equal(246, a.Available())\n}", "func (o *InlineResponse20083) GetPeopleOk() (*[]InlineResponse20083People, bool) {\n\tif o == nil || o.People == nil {\n\t\treturn nil, false\n\t}\n\treturn o.People, true\n}", "func TestMemory_WbemConnection(t *testing.T) {\n\tif os.Getenv(\"TEST_MEM\") == \"\" {\n\t\tt.Skip(\"Skipping TestMemory_WbemConnection; $TEST_MEM is not set\")\n\t}\n\ts, err := ConnectSWbemServices()\n\tif err != nil {\n\t\tt.Fatalf(\"InitializeSWbemServices: %s\", err)\n\t}\n\n\tstart := time.Now()\n\tfmt.Printf(\"Benchmark Iterations: %d (Private Memory should stabilize around 7MB after ~3000)\\n\", memReps)\n\n\tvar privateMB, allocMB, allocTotalMB float64\n\tfor i := 0; i < memReps; i++ {\n\t\tprivateMB, allocMB, allocTotalMB = wbemConnGetMemoryUsageMB(t, s)\n\t\tif i%100 == 0 {\n\t\t\tfmt.Printf(\"Time: %4ds Count: %5d \", time.Now().Sub(start)/time.Second, i)\n\t\t\tprintlnMemUsage(privateMB, allocMB, allocTotalMB)\n\t\t}\n\t}\n\n\terrClose := s.Close()\n\tif errClose != nil {\n\t\tt.Fatalf(\"Close: %s\", err)\n\t}\n\n\tfmt.Printf(\"Final Time: %4ds \", time.Now().Sub(start)/time.Second)\n\tprintlnMemUsage(privateMB, allocMB, allocTotalMB)\n}", "func GetPeople(w http.ResponseWriter, r *http.Request) {\n\tvar people []model.Person\n\n\tvar db = database.DB()\n\n\tif err := db.Find(&people).Error; err != nil {\n\t\tfmt.Printf(\"can not get all people from db: %v\\n\", err)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(errors.ErrorMsg{\"can not get all people from db\"})\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(&people)\n}" ]
[ "0.70004886", "0.67369616", "0.5519704", "0.5406321", "0.5317886", "0.5157369", "0.5157369", "0.5105136", "0.51042885", "0.5022956", "0.49560836", "0.49405894", "0.49164796", "0.48984706", "0.48861027", "0.48836163", "0.48500133", "0.4846669", "0.48370564", "0.48336497", "0.48208937", "0.47936133", "0.47861996", "0.47739324", "0.4772601", "0.47713062", "0.47636417", "0.47366992", "0.47360253", "0.47307166", "0.47247085", "0.47190952", "0.47014958", "0.4698752", "0.46934402", "0.4692499", "0.46905988", "0.46871993", "0.46758017", "0.46686637", "0.4665587", "0.4663915", "0.46627495", "0.4662128", "0.46590832", "0.46502045", "0.4611057", "0.461033", "0.46098113", "0.45857444", "0.45777485", "0.45687377", "0.45671543", "0.45593965", "0.45571914", "0.4551282", "0.45455638", "0.45446143", "0.4544497", "0.45443878", "0.45289057", "0.45288754", "0.4528729", "0.4525604", "0.45226586", "0.45169804", "0.45111826", "0.45097917", "0.45055765", "0.45012084", "0.44916221", "0.44839472", "0.44818774", "0.44736856", "0.4469137", "0.4465432", "0.44632715", "0.4460324", "0.44594145", "0.4459193", "0.44504404", "0.44480902", "0.4445235", "0.4441265", "0.44379428", "0.44354507", "0.44259724", "0.44245762", "0.44182035", "0.44129285", "0.44118515", "0.44069776", "0.44030422", "0.44012845", "0.44005474", "0.44004798", "0.43947086", "0.43891597", "0.43799525", "0.4378293" ]
0.81991124
0
TestReallocatePerson tests the functionality of ReallocatePerson
func TestReallocatePerson(t *testing.T) { var ( err error user User room Room fetchRoom = func(fname, lname, userType, oldRmName, newRmName, rmType string) { room, err = CreateRoom(con, oldRmName, rmType) So(err, ShouldBeNil) So(room.ID, ShouldNotBeBlank) user, err = AddPerson(con, fname, lname, userType, room.Name, "") So(err, ShouldBeNil) So(user, ShouldNotResemble, (User{})) room, err = CreateRoom(con, newRmName, rmType) So(err, ShouldBeNil) So(room.ID, ShouldNotBeBlank) room = Room{} room, err = ReallocatePerson(con, fname, lname, newRmName) } ) Convey("Tests for ReallocatePerson ", t, func() { Convey("ReallocatePerson should return Room with all the correct values present and an error", func() { fetchRoom("James", "Bond", "fellow", "Valhalla", "Mogadishu", "office") So(err, ShouldBeNil) So(room.Capacity, ShouldEqual, 6) So(room.ID, ShouldNotBeBlank) So(room.Name, ShouldEqual, "Mogadishu") So(room.Occupants, ShouldNotBeEmpty) So(room.Type, ShouldNotBeBlank) So(room.Occupants[0].FirstName, ShouldEqual, "James") So(room.Occupants[0].ID, ShouldNotBeBlank) So(room.Occupants[0].LastName, ShouldEqual, "Bond") So(room.Occupants[0].Type, ShouldEqual, "fellow") }) Convey("Print the successfully created Room and User", func() { fetchRoom("TheSecret", "Coder", "fellow", "Narnia", "Shell", "office") So(err, ShouldBeNil) printRooms() printUsers() // So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func reallocatePerson(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.ReallocatePerson(con, args.Get(0), args.Get(1), args.Get(2))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func TestReallocate(t *testing.T) {\n\t_, storage, backing, si, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := si.Create(context.TODO(), key(), validNewRangeAllocation(), nil, 0); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// Allocate a port inside the valid port range\n\tif err := storage.Allocate(30100); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Try to allocate the same port in the local bitmap\n\t// The local bitmap stores the offset of the port\n\t// offset = port - base (30100 - 30000 = 100)\n\tok, err := backing.Allocate(100)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// It should not allocate the port because it was already allocated\n\tif ok {\n\t\tt.Fatal(\"Expected allocation to fail\")\n\t}\n\t// Try to allocate the port again should fail\n\tif err := storage.Allocate(30100); err != portallocator.ErrAllocated {\n\t\tt.Fatal(err)\n\t}\n\n\t// Release the port\n\tif err := storage.Release(30100); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Try to allocate the port again should succeed because we've released it\n\tif err := storage.Allocate(30100); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}", "func TestAllocate(t *testing.T) {\n\t_, storage, _, si, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := si.Create(context.TODO(), key(), validNewRangeAllocation(), nil, 0); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tport int\n\t\terrMsg string\n\t}{\n\t\t{\n\t\t\tname: \"Allocate base port\",\n\t\t\tport: basePortRange,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate maximum from the port range\",\n\t\t\tport: basePortRange + sizePortRange - 1,\n\t\t\terrMsg: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: base port minus 1\",\n\t\t\tport: basePortRange - 1,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port: maximum port from the port range plus 1\",\n\t\t\tport: basePortRange + sizePortRange,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t\t{\n\t\t\tname: \"Allocate invalid port\",\n\t\t\tport: -2,\n\t\t\terrMsg: fmt.Sprintf(\"provided port is not in the valid range. The range of valid ports is %d-%d\", basePortRange, basePortRange+sizePortRange-1),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\ttt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := storage.Allocate(tt.port)\n\t\t\tif (err == nil) != (tt.errMsg == \"\") {\n\t\t\t\tt.Fatalf(\"Error expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t\tif err != nil && err.Error() != tt.errMsg {\n\t\t\t\tt.Fatalf(\"Error message expected %v, received %v\", tt.errMsg, err)\n\t\t\t}\n\t\t})\n\t}\n\n}", "func (m *dirtySeriesMap) Reallocate() {\n\tif m.initialSize > 0 {\n\t\tm.lookup = make(map[dirtySeriesMapHash]dirtySeriesMapEntry, m.initialSize)\n\t} else {\n\t\tm.lookup = make(map[dirtySeriesMapHash]dirtySeriesMapEntry)\n\t}\n}", "func (this *PoolTestSuite) TestInvalidateFreesCapacity() {\n\tthis.pool.Config.MaxTotal = 2\n\tthis.pool.Config.MaxWaitMillis = 500\n\tthis.pool.Config.BlockWhenExhausted = true\n\t// Borrow an instance and hold if for 5 seconds\n\tch1 := waitTestGoroutine(this.pool, 5000)\n\t// Borrow another instance\n\tobj := this.NoErrorWithResult(this.pool.BorrowObject())\n\t// Launch another goroutine - will block, but fail in 500 ms\n\tch2 := waitTestGoroutine(this.pool, 100)\n\t// Invalidate the object borrowed by this goroutine - should allow goroutine2 to create\n\tsleep(20)\n\tthis.NoError(this.pool.InvalidateObject(obj))\n\tsleep(600) // Wait for goroutine2 to timeout\n\tresult2 := <-ch2\n\tclose(ch2)\n\tif result2.error != nil {\n\t\tthis.Fail(result2.error.Error())\n\t}\n\t<-ch1\n\tclose(ch1)\n}", "func (m *ValuesResultArrayHash) Reallocate() {\n\tif m.initialSize > 0 {\n\t\tm.lookup = make(map[ValuesResultArrayHashHash]ValuesResultArrayHashEntry, m.initialSize)\n\t} else {\n\t\tm.lookup = make(map[ValuesResultArrayHashHash]ValuesResultArrayHashEntry)\n\t}\n}", "func (m *spiralMemory) reallocate() {\n\t// add zero rows before/after the existing ones\n\tnewGrid := make([][]int, m.offset*4+1)\n\tcopy(newGrid[m.offset:], m.grid)\n\tm.grid = newGrid\n\tfor i := range m.grid {\n\t\tif i < 2 || i > m.offset*3 {\n\t\t\t// new blank row\n\t\t\tm.grid[i] = make([]int, m.offset*4+1)\n\t\t} else {\n\t\t\t// resize existing row\n\t\t\tnewRow := make([]int, m.offset*4+1)\n\t\t\t// copy existing values into the right position, leaving the existing\n\t\t\t// offset's worth of zero values\n\t\t\tcopy(newRow[m.offset:], m.grid[i])\n\t\t\tm.grid[i] = newRow\n\t\t}\n\t}\n\t// record new offset\n\tm.offset *= 2\n}", "func (*testSuite) TestRollbackAlloc(c *C) {\n\tstore, err := mockstore.NewMockTikvStore()\n\tc.Assert(err, IsNil)\n\tdefer store.Close()\n\tdbID := int64(1)\n\ttblID := int64(2)\n\terr = kv.RunInNewTxn(store, false, func(txn kv.Transaction) error {\n\t\tm := meta.NewMeta(txn)\n\t\terr = m.CreateDatabase(&model.DBInfo{ID: dbID, Name: model.NewCIStr(\"a\")})\n\t\tc.Assert(err, IsNil)\n\t\terr = m.CreateTableOrView(dbID, &model.TableInfo{ID: tblID, Name: model.NewCIStr(\"t\")})\n\t\tc.Assert(err, IsNil)\n\t\treturn nil\n\t})\n\tc.Assert(err, IsNil)\n\n\tinjectConf := new(kv.InjectionConfig)\n\tinjectConf.SetCommitError(errors.New(\"injected\"))\n\tinjectedStore := kv.NewInjectedStore(store, injectConf)\n\talloc := autoid.NewAllocator(injectedStore, 1, false)\n\t_, err = alloc.Alloc(2)\n\tc.Assert(err, NotNil)\n\tc.Assert(alloc.Base(), Equals, int64(0))\n\tc.Assert(alloc.End(), Equals, int64(0))\n\n\terr = alloc.Rebase(2, 100, true)\n\tc.Assert(err, NotNil)\n\tc.Assert(alloc.Base(), Equals, int64(0))\n\tc.Assert(alloc.End(), Equals, int64(0))\n}", "func TestAllocGarbageCollector_MakeRoomFor_MaxAllocs(t *testing.T) {\n\tci.Parallel(t)\n\n\tconst maxAllocs = 6\n\trequire := require.New(t)\n\n\tserver, serverAddr, cleanupS := testServer(t, nil)\n\tdefer cleanupS()\n\ttestutil.WaitForLeader(t, server.RPC)\n\n\tclient, cleanup := TestClient(t, func(c *config.Config) {\n\t\tc.GCMaxAllocs = maxAllocs\n\t\tc.GCDiskUsageThreshold = 100\n\t\tc.GCInodeUsageThreshold = 100\n\t\tc.GCParallelDestroys = 1\n\t\tc.GCInterval = time.Hour\n\t\tc.RPCHandler = server\n\t\tc.Servers = []string{serverAddr}\n\t\tc.ConsulConfig.ClientAutoJoin = new(bool)\n\t})\n\tdefer cleanup()\n\twaitTilNodeReady(client, t)\n\n\tjob := mock.Job()\n\tjob.TaskGroups[0].Count = 1\n\tjob.TaskGroups[0].Tasks[0].Driver = \"mock_driver\"\n\tjob.TaskGroups[0].Tasks[0].Config = map[string]interface{}{\n\t\t\"run_for\": \"30s\",\n\t}\n\n\tindex := uint64(98)\n\tnextIndex := func() uint64 {\n\t\tindex++\n\t\treturn index\n\t}\n\n\tupsertJobFn := func(server *nomad.Server, j *structs.Job) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertJob(structs.MsgTypeTestSetup, nextIndex(), j))\n\t\trequire.NoError(state.UpsertJobSummary(nextIndex(), mock.JobSummary(j.ID)))\n\t}\n\n\t// Insert the Job\n\tupsertJobFn(server, job)\n\n\tupsertAllocFn := func(server *nomad.Server, a *structs.Allocation) {\n\t\tstate := server.State()\n\t\trequire.NoError(state.UpsertAllocs(structs.MsgTypeTestSetup, nextIndex(), []*structs.Allocation{a}))\n\t}\n\n\tupsertNewAllocFn := func(server *nomad.Server, j *structs.Job) *structs.Allocation {\n\t\talloc := mock.Alloc()\n\t\talloc.Job = j\n\t\talloc.JobID = j.ID\n\t\talloc.NodeID = client.NodeID()\n\n\t\tupsertAllocFn(server, alloc)\n\n\t\treturn alloc.Copy()\n\t}\n\n\tvar allocations []*structs.Allocation\n\n\t// Fill the node with allocations\n\tfor i := 0; i < maxAllocs; i++ {\n\t\tallocations = append(allocations, upsertNewAllocFn(server, job))\n\t}\n\n\t// Wait until the allocations are ready\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := len(client.getAllocRunners())\n\n\t\treturn ar == maxAllocs, fmt.Errorf(\"Expected %d allocs, got %d\", maxAllocs, ar)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not start: %v\", err)\n\t})\n\n\t// Mark the first three as terminal\n\tfor i := 0; i < 3; i++ {\n\t\tallocations[i].DesiredStatus = structs.AllocDesiredStatusStop\n\t\tupsertAllocFn(server, allocations[i].Copy())\n\t}\n\n\t// Wait until the allocations are stopped\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tstopped := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.Alloc().TerminalStatus() {\n\t\t\t\tstopped++\n\t\t\t}\n\t\t}\n\n\t\treturn stopped == 3, fmt.Errorf(\"Expected %d terminal allocs, got %d\", 3, stopped)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not terminate: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// A single allocation should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 1, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 1, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// Upsert a new allocation\n\t// This does not get appended to `allocations` as we do not use them again.\n\tupsertNewAllocFn(server, job)\n\n\t// 2 allocations should be GC'd\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tdestroyed := 0\n\t\tfor _, r := range ar {\n\t\t\tif r.IsDestroyed() {\n\t\t\t\tdestroyed++\n\t\t\t}\n\t\t}\n\n\t\treturn destroyed == 2, fmt.Errorf(\"Expected %d gc'd ars, got %d\", 2, destroyed)\n\t}, func(err error) {\n\t\tt.Fatalf(\"Allocs did not get GC'd: %v\", err)\n\t})\n\n\t// check that all 8 get run eventually\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tar := client.getAllocRunners()\n\t\tif len(ar) != 8 {\n\t\t\treturn false, fmt.Errorf(\"expected 8 ARs, found %d: %v\", len(ar), ar)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.NoError(err)\n\t})\n}", "func checkNodeAllocatableTest(f *framework.Framework) {\n\n\tnodeMem := getNodeMemory(f)\n\tframework.Logf(\"nodeMem says: %+v\", nodeMem)\n\n\t// calculate the allocatable mem based on capacity - reserved amounts\n\tcalculatedNodeAlloc := nodeMem.capacity.Copy()\n\tcalculatedNodeAlloc.Sub(nodeMem.systemReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.kubeReserve)\n\tcalculatedNodeAlloc.Sub(nodeMem.softEviction)\n\tcalculatedNodeAlloc.Sub(nodeMem.hardEviction)\n\n\tginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc))\n\n\t// sanity check against stated allocatable\n\tgomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0))\n}", "func (c *Calcium) ReallocResource(ctx context.Context, opts *types.ReallocOptions) (err error) {\n\tlogger := log.WithFunc(\"calcium.ReallocResource\").WithField(\"opts\", opts)\n\tlogger.Infof(ctx, \"realloc workload %+v with options %+v\", opts.ID, opts.Resources)\n\tworkload, err := c.GetWorkload(ctx, opts.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\t// copy origin workload\n\toriginWorkload := *workload\n\treturn c.withNodePodLocked(ctx, workload.Nodename, func(ctx context.Context, node *types.Node) error {\n\t\treturn c.withWorkloadLocked(ctx, opts.ID, func(ctx context.Context, workload *types.Workload) error {\n\t\t\terr := c.doReallocOnNode(ctx, node, workload, originWorkload, opts)\n\t\t\tlogger.Error(ctx, err)\n\t\t\treturn err\n\t\t})\n\t})\n}", "func TestDryRunAllocate(t *testing.T) {\n\tpr, err := net.ParsePortRange(\"10000-10200\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Allocate some ports before calling\n\tpreviouslyAllocated := []int{10000, 10010, 10020}\n\tr, err := NewInMemory(*pr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, port := range previouslyAllocated {\n\t\t_ = r.Allocate(port)\n\t}\n\tfreeAtStart := r.Free()\n\n\t// Do some allocations with a dry run operation\n\ttoAllocate := []int{\n\t\t10000,\n\t\t10030,\n\t\t10030,\n\t\t10040,\n\t}\n\texpectedErrors := []error{\n\t\tErrAllocated,\n\t\tnil,\n\t\tErrAllocated,\n\t\tnil,\n\t}\n\top := StartOperation(r, true)\n\tfor i, port := range toAllocate {\n\t\terr := op.Allocate(port)\n\t\tif err != expectedErrors[i] {\n\t\t\tt.Errorf(\"%v: expected error %v but got %v\", i, expectedErrors[i], err)\n\t\t}\n\t}\n\n\t// Make sure no port allocations were actually made by the dry run\n\tfreeAtEnd := r.Free()\n\tif freeAtStart != freeAtEnd {\n\t\tt.Errorf(\"expected %v free ports but got %v\", freeAtStart, freeAtEnd)\n\t}\n}", "func (a *allocator) Recycle() {\n\ta.base.Recycle()\n}", "func Realloc(p Pointer, size uintptr) Pointer {\n\treturn Pointer(allocator.Realloc(uintptr(p), size))\n}", "func TestIntCreatePersonAndUpdate(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreatePersonAndUpdate\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t// Create a person in the DB.\n\tp := personModel.MakeInitialisedPerson(0, expectedSurname1, expectedForename1)\n\tperson, err := dao.Create(p)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\t// Update the person in the DB.\n\tperson.SetForename(expectedForename2)\n\tperson.SetSurname(expectedSurname2)\n\trows, err := dao.Update(person)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected 1 row to be updated, actually %d rows\", rows)\n\t}\n\n\t// fetch the updated record back and check it.\n\tpersonfetched, err := dao.FindByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif personfetched.Forename() != expectedForename2 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename2, personfetched.Forename())\n\t}\n\tif person.Surname() != expectedSurname2 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname2, personfetched.Surname())\n\t}\n\n\tclearDown(dao, t)\n}", "func overrideAllocatableMemoryTest(f *framework.Framework, allocatablePods int) {\n\tconst (\n\t\tpodType = \"memory_limit_test_pod\"\n\t)\n\n\ttotalAllocatable := getTotalAllocatableMemory(f)\n\n\tmemValue := totalAllocatable.Value()\n\tmemPerPod := memValue / int64(allocatablePods)\n\tginkgo.By(fmt.Sprintf(\"Deploying %d pods with mem limit %v, then one additional pod\", allocatablePods, memPerPod))\n\n\t// these should all work\n\tpods := newMemLimitTestPods(allocatablePods, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10))\n\tf.PodClient().CreateBatch(pods)\n\n\tfailurePods := newMemLimitTestPods(1, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10))\n\tf.PodClient().Create(failurePods[0])\n\n\tgomega.Eventually(func() bool {\n\t\teventList, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(metav1.ListOptions{})\n\t\tframework.ExpectNoError(err)\n\t\tfor _, e := range eventList.Items {\n\t\t\t// Look for an event that shows FailedScheduling\n\t\t\tif e.Type == \"Warning\" && e.Reason == \"FailedScheduling\" && e.InvolvedObject.Name == failurePods[0].ObjectMeta.Name {\n\t\t\t\tframework.Logf(\"Found %+v event with message %+v\", e.Reason, e.Message)\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}, 3*time.Minute, 10*time.Second).Should(gomega.Equal(true))\n}", "func TestIntCreateTwoPersonsAndReadBack(t *testing.T) {\n\tlog.SetPrefix(\"TestCreatePersonAndReadBack\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t//Create two people\n\tp1 := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\tperson1, err := dao.Create(p1)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"person1 %s\", person1.String())\n\tp2 := personModel.MakeInitialisedPerson(0, expectedForename2, expectedSurname2)\n\tperson2, err := dao.Create(p2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\t// read all the people in the DB - expect just the two we created\n\tpeople, err := dao.FindAll()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif len(people) != 2 {\n\t\tt.Errorf(\"expected 2 rows, actual %d\", len(people))\n\t}\n\n\tmatches := 0\n\tfor _, person := range people {\n\t\tswitch person.Forename() {\n\t\tcase expectedForename1:\n\t\t\tif person.Surname() == expectedSurname1 {\n\t\t\t\tmatches++\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"expected surname to be %s actually %s\", expectedSurname1, person.Surname())\n\t\t\t}\n\t\tcase expectedForename2:\n\t\t\tif person.Surname() == expectedSurname2 {\n\t\t\t\tmatches++\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"expected forename to be %s actually %s\", expectedForename2, person.Forename())\n\t\t\t}\n\t\tdefault:\n\t\t\tt.Errorf(\"unexpected forename - %s\", person.Forename())\n\t\t}\n\t}\n\n\t// We should have just the records we created\n\tif matches != 2 {\n\t\tt.Errorf(\"expected two matches, actual %d\", matches)\n\t}\n\n\t// Find each of the records by ID and check the fields\n\tlog.Printf(\"finding person %d\", person1.ID())\n\tperson1Returned, err := dao.FindByID(person1.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif person1Returned.Forename() != expectedForename1 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename1, person1Returned.Forename())\n\t}\n\tif person1Returned.Surname() != expectedSurname1 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname1, person1Returned.Surname())\n\t}\n\n\tvar IDStr = strconv.FormatUint(person2.ID(), 10)\n\tperson2Returned, err := dao.FindByIDStr(IDStr)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tlog.Printf(\"found person %s\", person2Returned.String())\n\n\tif person2Returned.Forename() != expectedForename2 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\texpectedForename2, person2Returned.Forename())\n\t}\n\tif person2Returned.Surname() != expectedSurname2 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\",\n\t\t\texpectedSurname2, person2Returned.Surname())\n\t}\n\n\tclearDown(dao, t)\n}", "func TestGetUnallocatedPeople(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\tusers []User\n\n\t\tfetchUsers = func(fname, lname, userType string) {\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, \"\", \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\tusers, err = GetUnallocatedPeople(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetUnallocatedPeople \", t, func() {\n\t\tConvey(\"GetUnallocatedPeople should return a slice of User with all the correct values present and an error\", func() {\n\t\t\tfetchUsers(\"David\", \"Holmes\", \"staff\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, user = range users {\n\t\t\t\tSo(user.FirstName, ShouldEqual, \"David\")\n\t\t\t\tSo(user.ID, ShouldNotBeBlank)\n\t\t\t\tSo(user.LastName, ShouldEqual, \"Holmes\")\n\t\t\t\tSo(user.LivingSpace, ShouldResemble, (User{}))\n\t\t\t\tSo(user.Office, ShouldResemble, (User{}))\n\t\t\t\tSo(user.Type, ShouldEqual, \"staff\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchUsers(\"Mark\", \"Oyaboade\", \"fellow\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestIntCreatePersonStoreFetchBackAndCheckContents(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreatePersonAndCheckContents\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\tp := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\n\t// Store the person in the DB\n\tperson, err := dao.Create(p)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"created person %s\\n\", person.String())\n\n\tretrievedPerson, err := dao.FindByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tlog.Printf(\"retrieved person %s\\n\", retrievedPerson.String())\n\n\tif retrievedPerson.ID() != person.ID() {\n\t\tt.Errorf(\"expected ID to be %d actually %d\", person.ID(),\n\t\t\tretrievedPerson.ID())\n\t}\n\tif retrievedPerson.Forename() != expectedForename1 {\n\t\tt.Errorf(\"expected forename to be %s actually %s\", expectedForename1,\n\t\t\tretrievedPerson.Forename())\n\t}\n\tif retrievedPerson.Surname() != expectedSurname1 {\n\t\tt.Errorf(\"expected surname to be %s actually %s\", expectedSurname1,\n\t\t\tretrievedPerson.Surname())\n\t}\n\n\t// Delete person and check response\n\tid := person.ID()\n\trows, err := dao.DeleteByID(person.ID())\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected delete to return 1, actual %d\", rows)\n\t}\n\tlog.Printf(\"deleted person with ID %d\\n\", id)\n\tclearDown(dao, t)\n}", "func TestAllocRunner_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\n\t// Ensure task takes some time\n\talloc := mock.BatchAlloc()\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Config[\"run_for\"] = \"10s\"\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\t// Use a MemDB to assert alloc state gets cleaned up\n\tconf.StateDB = state.NewMemDB(conf.Logger)\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tgo ar.Run()\n\n\t// Wait for alloc to be running\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tstate := ar.AllocState()\n\n\t\treturn state.ClientStatus == structs.AllocClientStatusRunning,\n\t\t\tfmt.Errorf(\"got client status %v; want running\", state.ClientStatus)\n\t}, func(err error) {\n\t\trequire.NoError(t, err)\n\t})\n\n\t// Assert state was stored\n\tls, ts, err := conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ls)\n\trequire.NotNil(t, ts)\n\n\t// Now destroy\n\tar.Destroy()\n\n\tselect {\n\tcase <-ar.DestroyCh():\n\t\t// Destroyed properly!\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(t, \"timed out waiting for alloc to be destroyed\")\n\t}\n\n\t// Assert alloc is dead\n\tstate := ar.AllocState()\n\trequire.Equal(t, structs.AllocClientStatusComplete, state.ClientStatus)\n\n\t// Assert the state was cleaned\n\tls, ts, err = conf.StateDB.GetTaskRunnerState(alloc.ID, task.Name)\n\trequire.NoError(t, err)\n\trequire.Nil(t, ls)\n\trequire.Nil(t, ts)\n\n\t// Assert the alloc directory was cleaned\n\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\trequire.Fail(t, \"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t} else if !os.IsNotExist(err) {\n\t\trequire.Failf(t, \"expected NotExist error\", \"found %v\", err)\n\t}\n}", "func (alloc *inMemoryAllocator) Rebase(_ context.Context, requiredBase int64, _ bool) error {\n\tif alloc.isUnsigned {\n\t\tif uint64(requiredBase) > uint64(alloc.base) {\n\t\t\talloc.base = requiredBase\n\t\t}\n\t} else {\n\t\tif requiredBase > alloc.base {\n\t\t\talloc.base = requiredBase\n\t\t}\n\t}\n\treturn nil\n}", "func Regalloc(n *Node, t *Type, o *Node)", "func TestAllocRunner_TaskFailed_KillTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.Alloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create two tasks in the task group\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Name = \"task1\"\n\ttask.Driver = \"mock_driver\"\n\ttask.KillTimeout = 10 * time.Millisecond\n\ttask.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\t// Set a service with check\n\ttask.Services = []*structs.Service{\n\t\t{\n\t\t\tName: \"fakservice\",\n\t\t\tPortLabel: \"http\",\n\t\t\tProvider: structs.ServiceProviderConsul,\n\t\t\tChecks: []*structs.ServiceCheck{\n\t\t\t\t{\n\t\t\t\t\tName: \"fakecheck\",\n\t\t\t\t\tType: structs.ServiceCheckScript,\n\t\t\t\t\tCommand: \"true\",\n\t\t\t\t\tInterval: 30 * time.Second,\n\t\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttask2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\ttask2.Name = \"task 2\"\n\ttask2.Driver = \"mock_driver\"\n\ttask2.Config = map[string]interface{}{\n\t\t\"start_error\": \"fail task please\",\n\t}\n\talloc.Job.TaskGroups[0].Tasks = append(alloc.Job.TaskGroups[0].Tasks, task2)\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\talloc.AllocatedResources.Tasks[task2.Name] = tr\n\n\t// Make the alloc be part of a deployment\n\talloc.DeploymentID = uuid.Generate()\n\talloc.Job.TaskGroups[0].Update = structs.DefaultUpdateStrategy.Copy()\n\talloc.Job.TaskGroups[0].Update.HealthCheck = structs.UpdateStrategyHealthCheck_Checks\n\talloc.Job.TaskGroups[0].Update.MaxParallel = 1\n\talloc.Job.TaskGroups[0].Update.MinHealthyTime = 10 * time.Millisecond\n\talloc.Job.TaskGroups[0].Update.HealthyDeadline = 2 * time.Second\n\n\tcheckHealthy := &api.AgentCheck{\n\t\tCheckID: uuid.Generate(),\n\t\tStatus: api.HealthPassing,\n\t}\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\tconsulClient := conf.Consul.(*regMock.ServiceRegistrationHandler)\n\tconsulClient.AllocRegistrationsFn = func(allocID string) (*serviceregistration.AllocRegistration, error) {\n\t\treturn &serviceregistration.AllocRegistration{\n\t\t\tTasks: map[string]*serviceregistration.ServiceRegistrations{\n\t\t\t\ttask.Name: {\n\t\t\t\t\tServices: map[string]*serviceregistration.ServiceRegistration{\n\t\t\t\t\t\t\"123\": {\n\t\t\t\t\t\t\tService: &api.AgentService{Service: \"fakeservice\"},\n\t\t\t\t\t\t\tChecks: []*api.AgentCheck{checkHealthy},\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}, nil\n\t}\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusFailed {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusFailed)\n\t\t}\n\n\t\t// Task One should be killed\n\t\tstate1 := last.TaskStates[task.Name]\n\t\tif state1.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state1.State, structs.TaskStateDead)\n\t\t}\n\t\tif len(state1.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tfound := false\n\t\tfor _, e := range state1.Events {\n\t\t\tif e.Type != structs.TaskSiblingFailed {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v\", structs.TaskSiblingFailed)\n\t\t}\n\n\t\t// Task Two should be failed\n\t\tstate2 := last.TaskStates[task2.Name]\n\t\tif state2.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state2.State, structs.TaskStateDead)\n\t\t}\n\t\tif !state2.Failed {\n\t\t\treturn false, fmt.Errorf(\"task2 should have failed\")\n\t\t}\n\n\t\tif !last.DeploymentStatus.HasHealth() {\n\t\t\treturn false, fmt.Errorf(\"Expected deployment health to be non nil\")\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func (suite *ReserverTestSuite) TestReservation() {\n\ttask := createResMgrTask()\n\thosts := []*models_v0.Host{\n\t\t{\n\t\t\tHost: creareHostInfo(),\n\t\t},\n\t}\n\n\t// Calling mockups for the host service which reserver will call\n\tsuite.hostService.EXPECT().GetHosts(gomock.Any(), gomock.Any(), gomock.Any()).Return(hosts, nil)\n\tsuite.hostService.EXPECT().ReserveHost(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)\n\n\t// Adding task to reservation queue which is simulating the behavior\n\t// for placement engine got the task from Resource Manager\n\tsuite.reserver.EnqueueReservation(\n\t\t&hostsvc.Reservation{\n\t\t\tTask: task,\n\t\t})\n\tdelay, err := suite.reserver.Reserve(context.Background())\n\tsuite.Equal(delay.Seconds(), float64(0))\n\tsuite.NoError(err)\n}", "func TestResizeJob(t *testing.T) {\n\n\turi0, err := NewURIFromAddress(\"host0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\turi1, err := NewURIFromAddress(\"host1\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\turi2, err := NewURIFromAddress(\"host2\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tnode0 := &Node{ID: \"node0\", URI: *uri0}\n\tnode1 := &Node{ID: \"node1\", URI: *uri1}\n\tnode2 := &Node{ID: \"node2\", URI: *uri2}\n\n\ttests := []struct {\n\t\texistingNodes []*Node\n\t\tnode *Node\n\t\taction string\n\t\texpectedIDs map[string]bool\n\t}{\n\t\t{\n\t\t\texistingNodes: []*Node{node0, node1},\n\t\t\tnode: node2,\n\t\t\taction: resizeJobActionAdd,\n\t\t\texpectedIDs: map[string]bool{node0.ID: false, node1.ID: false, node2.ID: false},\n\t\t},\n\t\t{\n\t\t\texistingNodes: []*Node{node0, node1, node2},\n\t\t\tnode: node2,\n\t\t\taction: resizeJobActionRemove,\n\t\t\texpectedIDs: map[string]bool{node0.ID: false, node1.ID: false},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\n\t\tactual := newResizeJob(test.existingNodes, test.node, test.action)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !reflect.DeepEqual(actual.IDs, test.expectedIDs) {\n\t\t\tt.Errorf(\"expected: %v, but got: %v\", test.expectedIDs, actual.IDs)\n\t\t}\n\t}\n}", "func TestAllocRunner_TaskMain_KillTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create four tasks in the task group\n\tprestart := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tprestart.Name = \"prestart-sidecar\"\n\tprestart.Driver = \"mock_driver\"\n\tprestart.KillTimeout = 10 * time.Millisecond\n\tprestart.Lifecycle = &structs.TaskLifecycleConfig{\n\t\tHook: structs.TaskLifecycleHookPrestart,\n\t\tSidecar: true,\n\t}\n\n\tprestart.Config = map[string]interface{}{\n\t\t\"run_for\": \"100s\",\n\t}\n\n\tpoststart := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tpoststart.Name = \"poststart-sidecar\"\n\tpoststart.Driver = \"mock_driver\"\n\tpoststart.KillTimeout = 10 * time.Millisecond\n\tpoststart.Lifecycle = &structs.TaskLifecycleConfig{\n\t\tHook: structs.TaskLifecycleHookPoststart,\n\t\tSidecar: true,\n\t}\n\n\tpoststart.Config = map[string]interface{}{\n\t\t\"run_for\": \"100s\",\n\t}\n\n\t// these two main tasks have the same name, is that ok?\n\tmain1 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tmain1.Name = \"task2\"\n\tmain1.Driver = \"mock_driver\"\n\tmain1.Config = map[string]interface{}{\n\t\t\"run_for\": \"1s\",\n\t}\n\n\tmain2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\tmain2.Name = \"task2\"\n\tmain2.Driver = \"mock_driver\"\n\tmain2.Config = map[string]interface{}{\n\t\t\"run_for\": \"2s\",\n\t}\n\n\talloc.Job.TaskGroups[0].Tasks = []*structs.Task{prestart, poststart, main1, main2}\n\talloc.AllocatedResources.Tasks = map[string]*structs.AllocatedTaskResources{\n\t\tprestart.Name: tr,\n\t\tpoststart.Name: tr,\n\t\tmain1.Name: tr,\n\t\tmain2.Name: tr,\n\t}\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\n\thasTaskMainEvent := func(state *structs.TaskState) bool {\n\t\tfor _, e := range state.Events {\n\t\t\tif e.Type == structs.TaskMainDead {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t// Wait for all tasks to be killed\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\tvar state *structs.TaskState\n\n\t\t// both sidecars should be killed because Task2 exited\n\t\tstate = last.TaskStates[prestart.Name]\n\t\tif state == nil {\n\t\t\treturn false, fmt.Errorf(\"could not find state for task %s\", prestart.Name)\n\t\t}\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif len(state.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tif !hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v: %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\tstate = last.TaskStates[poststart.Name]\n\t\tif state == nil {\n\t\t\treturn false, fmt.Errorf(\"could not find state for task %s\", poststart.Name)\n\t\t}\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif len(state.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tif !hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v: %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\t// main tasks should die naturely\n\t\tstate = last.TaskStates[main1.Name]\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"unexpected event %#+v in %v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\tstate = last.TaskStates[main2.Name]\n\t\tif state.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state.State, structs.TaskStateDead)\n\t\t}\n\t\tif state.FinishedAt.IsZero() || state.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif hasTaskMainEvent(state) {\n\t\t\treturn false, fmt.Errorf(\"unexpected event %v in %#+v\", structs.TaskMainDead, state.Events)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\tt.Fatalf(\"err: %v\", err)\n\t})\n}", "func (m *MockClusterAdmin) AlterPartitionReassignments(arg0 string, arg1 [][]int32) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AlterPartitionReassignments\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestReallocOnInit(t *testing.T) {\n\tfixture := mkTestFixture([]*cilium_api_v2alpha1.CiliumLoadBalancerIPPool{\n\t\tmkPool(poolAUID, \"pool-a\", []string{\"10.0.10.0/24\"}),\n\t}, true, true, nil)\n\n\t// Initially request only an IPv4\n\tpolicy := slim_core_v1.IPFamilyPolicySingleStack\n\tfixture.coreCS.Tracker().Add(\n\t\t&slim_core_v1.Service{\n\t\t\tObjectMeta: slim_meta_v1.ObjectMeta{\n\t\t\t\tName: \"service-a\",\n\t\t\t\tNamespace: \"default\",\n\t\t\t\tUID: serviceAUID,\n\t\t\t},\n\t\t\tSpec: slim_core_v1.ServiceSpec{\n\t\t\t\tType: slim_core_v1.ServiceTypeLoadBalancer,\n\t\t\t\tIPFamilyPolicy: &policy,\n\t\t\t\tIPFamilies: []slim_core_v1.IPFamily{\n\t\t\t\t\tslim_core_v1.IPv4Protocol,\n\t\t\t\t},\n\t\t\t},\n\t\t\tStatus: slim_core_v1.ServiceStatus{\n\t\t\t\tLoadBalancer: slim_core_v1.LoadBalancerStatus{\n\t\t\t\t\tIngress: []slim_core_v1.LoadBalancerIngress{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tIP: \"192.168.1.12\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\n\tawait := fixture.AwaitService(func(action k8s_testing.Action) bool {\n\t\tif action.GetResource() != servicesResource || action.GetVerb() != \"patch\" {\n\t\t\treturn false\n\t\t}\n\n\t\tsvc := fixture.PatchedSvc(action)\n\n\t\tif len(svc.Status.LoadBalancer.Ingress) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one ingress IP\")\n\t\t\treturn true\n\t\t}\n\n\t\tif net.ParseIP(svc.Status.LoadBalancer.Ingress[0].IP).To4() == nil {\n\t\t\tt.Error(\"Expected service to receive a IPv4 address\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.LoadBalancer.Ingress[0].IP == \"192.168.1.12\" {\n\t\t\tt.Error(\"Expected ingress IP to not be the initial, bad IP\")\n\t\t\treturn true\n\t\t}\n\n\t\tif len(svc.Status.Conditions) != 1 {\n\t\t\tt.Error(\"Expected service to receive exactly one condition\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Type != ciliumSvcRequestSatisfiedCondition {\n\t\t\tt.Error(\"Expected second condition to be svc-satisfied:true\")\n\t\t\treturn true\n\t\t}\n\n\t\tif svc.Status.Conditions[0].Status != slim_meta_v1.ConditionTrue {\n\t\t\tt.Error(\"Expected second condition to be svc-satisfied:true\")\n\t\t\treturn true\n\t\t}\n\n\t\treturn true\n\t}, time.Second)\n\n\tgo fixture.hive.Start(context.Background())\n\tdefer fixture.hive.Stop(context.Background())\n\n\tif await.Block() {\n\t\tt.Fatal(\"Expected service to be updated\")\n\t}\n}", "func (suite *ReserverTestSuite) TestReserveAgain() {\n\treserver, reserveQueue, _ := suite.getReserver()\n\t// testing the valid completed reservation\n\tvar res []*hostsvc.CompletedReservation\n\tres = append(res, suite.getCompletedReservation())\n\tres[0].HostOffer = nil\n\tsuite.hostService.EXPECT().GetCompletedReservation(gomock.Any()).Return(res, nil)\n\treserveQueue.EXPECT().Enqueue(gomock.Any()).Return(nil)\n\terr := reserver.enqueueCompletedReservation(context.Background())\n\tsuite.NoError(err)\n\n\t// Testing requeue have error\n\tsuite.hostService.EXPECT().GetCompletedReservation(gomock.Any()).Return(res, nil)\n\treserveQueue.EXPECT().Enqueue(gomock.Any()).Return(errors.New(\"error\"))\n\terr = reserver.enqueueCompletedReservation(context.Background())\n\tsuite.NoError(err)\n}", "func TestReorganize(t *testing.T) {\n\t// No values to test, but testing as a sanity test - if something does go\n\t// wrong and the program crashes, this'll let us know Reorganize() is\n\t// broken. ;)\n\tdb, _ := Open(db_filename, \"c\")\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\tdb.Reorganize()\n}", "func restartPersonGlobal() {\n\tglobalperson = nil\n}", "func (ts testState) assertRecreatePVC(ctx context.Context, client kubernetesClient) error {\n\tpvc, err := client.GetPVC(ctx, withMigrationSuffix(ts.pvc), ts.namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ann, ok := pvc.Annotations[isRenamedPVC]; !ok || ann != ts.pvc {\n\t\treturn errors.Errorf(\"annotation does not exist or is wrong: %v\", pvc.Annotations[isRenamedPVC])\n\t}\n\n\treturn makeDeletable(ctx, ts.pvc, ts.namespace, client)\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func TestMemoryTracker(ptr unsafe.Pointer, sz C.size_t, op C.rtloader_mem_ops_t) {\n\tswitch op {\n\tcase C.DATADOG_AGENT_RTLOADER_ALLOCATION:\n\t\tAllocations.Add(1)\n\tcase C.DATADOG_AGENT_RTLOADER_FREE:\n\t\tFrees.Add(1)\n\t}\n}", "func TestKeyResize(t *testing.T) {\n\t// Key will have to resize once\n\tr := io.LimitReader(ConstReader(1), int64(os.Getpagesize())+1)\n\tkey, err := NewKeyFromReader(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer key.Wipe()\n\tfor i, b := range key.data {\n\t\tif b != 1 {\n\t\t\tt.Fatalf(\"Byte %d contained invalid data %q\", i, b)\n\t\t}\n\t}\n}", "func (m *CarCheckInOutMutation) ResetPerson() {\n\tm.person = nil\n\tm.addperson = nil\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.contract.Transact(opts, \"renounceOwnership\")\n}", "func TestAllocateConnector(t *testing.T) {\n\taddr, err := allocateConnector([]string{\"http://localhost:4001\"})\n\tif err != nil {\n\t\tt.Errorf(\"allocateConnector error (%v)\", err)\n\t}\n\tfmt.Printf(\"allocated %s\\n\", addr)\n}", "func TestEmpty(t *testing.T) {\n\t_, storage, _, _, destroyFunc := newStorage(t)\n\tdefer destroyFunc()\n\tif err := storage.Allocate(31000); !strings.Contains(err.Error(), \"cannot allocate resources of type servicenodeportallocations at this time\") {\n\t\tt.Fatal(err)\n\t}\n}", "func TestIntCreateTwoPeopleAndDeleteOneByIDStr(t *testing.T) {\n\tlog.SetPrefix(\"TestIntegrationCreateTwoPeopleAndDeleteOneByIDStr\")\n\t// Create a dao containing a session\n\tdbsession, err := dbsession.MakeGorpMysqlDBSession()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tdefer dbsession.Close()\n\n\tdao := MakeRepo(dbsession)\n\n\tclearDown(dao, t)\n\n\t// Create two people\n\tp1 := personModel.MakeInitialisedPerson(0, expectedForename1, expectedSurname1)\n\tperson1, err := dao.Create(p1)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tp2 := personModel.MakeInitialisedPerson(0, expectedForename2, expectedSurname2)\n\tperson2, err := dao.Create(p2)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tvar IDStr = fmt.Sprintf(\"%d\", person1.ID())\n\trows, err := dao.DeleteByIDStr(IDStr)\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif rows != 1 {\n\t\tt.Errorf(\"expected one record to be deleted, actually %d\", rows)\n\t}\n\n\t// We should have one record in the DB and it should match person2\n\tpeople, err := dao.FindAll()\n\tif err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tif len(people) != 1 {\n\t\tt.Errorf(\"expected one record, actual %d\", len(people))\n\t}\n\n\tfor _, person := range people {\n\t\tif person.ID() != person2.ID() {\n\t\t\tt.Errorf(\"expected id to be %d actually %d\",\n\t\t\t\tperson2.ID(), person.ID())\n\t\t}\n\t\tif person.Forename() != expectedForename2 {\n\t\t\tt.Errorf(\"expected forename to be %s actually %s\",\n\t\t\t\texpectedForename2, person.Forename())\n\t\t}\n\t\tif person.Surname() != expectedSurname2 {\n\t\t\tt.Errorf(\"TestCreateTwoPeopleAndDeleteOneByIDStr(): expected surname to be %s actually %s\",\n\t\t\t\texpectedSurname2, person.Surname())\n\t\t}\n\t}\n\n\tclearDown(dao, t)\n}", "func (s *System) allocate() {\n\ts.Vertexes.Resize(s.vertex)\n\ts.Indices.Resize(s.indice)\n}", "func TestFreelist_allocate(t *testing.T) {\n\tf := &freelist{ids: []pgid{3, 4, 5, 6, 7, 9, 12, 13, 18}}\n\tif id := int(f.allocate(3)); id != 3 {\n\t\tt.Fatalf(\"exp=3; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 6 {\n\t\tt.Fatalf(\"exp=6; got=%v\", id)\n\t}\n\tif id := int(f.allocate(3)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif id := int(f.allocate(2)); id != 12 {\n\t\tt.Fatalf(\"exp=12; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 7 {\n\t\tt.Fatalf(\"exp=7; got=%v\", id)\n\t}\n\tif id := int(f.allocate(0)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif id := int(f.allocate(0)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif exp := []pgid{9, 18}; !reflect.DeepEqual(exp, f.ids) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.ids)\n\t}\n\n\tif id := int(f.allocate(1)); id != 9 {\n\t\tt.Fatalf(\"exp=9; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 18 {\n\t\tt.Fatalf(\"exp=18; got=%v\", id)\n\t}\n\tif id := int(f.allocate(1)); id != 0 {\n\t\tt.Fatalf(\"exp=0; got=%v\", id)\n\t}\n\tif exp := []pgid{}; !reflect.DeepEqual(exp, f.ids) {\n\t\tt.Fatalf(\"exp=%v; got=%v\", exp, f.ids)\n\t}\n}", "func Regrealloc(n *Node)", "func (a *Allocator) ResetMaybeReallocate(\n\ttyps []*types.T, oldBatch coldata.Batch, minCapacity int, maxBatchMemSize int64,\n) (newBatch coldata.Batch, reallocated bool) {\n\tif minCapacity < 0 {\n\t\tcolexecerror.InternalError(errors.AssertionFailedf(\"invalid minCapacity %d\", minCapacity))\n\t} else if minCapacity == 0 {\n\t\tminCapacity = 1\n\t} else if minCapacity > coldata.BatchSize() {\n\t\tminCapacity = coldata.BatchSize()\n\t}\n\treallocated = true\n\tif oldBatch == nil {\n\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, minCapacity)\n\t} else {\n\t\t// If old batch is already of the largest capacity, we will reuse it.\n\t\tuseOldBatch := oldBatch.Capacity() == coldata.BatchSize()\n\t\t// Avoid calculating the memory footprint if possible.\n\t\tvar oldBatchMemSize int64\n\t\tif !useOldBatch {\n\t\t\t// Check if the old batch already reached the maximum memory size,\n\t\t\t// and use it if so. Note that we must check that the old batch has\n\t\t\t// enough capacity too.\n\t\t\toldBatchMemSize = GetBatchMemSize(oldBatch)\n\t\t\tuseOldBatch = oldBatchMemSize >= maxBatchMemSize && oldBatch.Capacity() >= minCapacity\n\t\t}\n\t\tif useOldBatch {\n\t\t\treallocated = false\n\t\t\toldBatch.ResetInternalBatch()\n\t\t\tnewBatch = oldBatch\n\t\t} else {\n\t\t\ta.ReleaseMemory(oldBatchMemSize)\n\t\t\tnewCapacity := oldBatch.Capacity() * 2\n\t\t\tif newCapacity < minCapacity {\n\t\t\t\tnewCapacity = minCapacity\n\t\t\t}\n\t\t\tif newCapacity > coldata.BatchSize() {\n\t\t\t\tnewCapacity = coldata.BatchSize()\n\t\t\t}\n\t\t\tnewBatch = a.NewMemBatchWithFixedCapacity(typs, newCapacity)\n\t\t}\n\t}\n\treturn newBatch, reallocated\n}", "func testResMgrObject(testResMgr *fields) *OpenOltResourceMgr {\n\tvar rsrMgr = OpenOltResourceMgr{\n\t\tDeviceID: testResMgr.DeviceID,\n\t\tArgs: testResMgr.Args,\n\t\tKVStore: testResMgr.KVStore,\n\t\tDeviceType: testResMgr.DeviceType,\n\t\tAddress: testResMgr.Address,\n\t\tDevInfo: testResMgr.DevInfo,\n\t\tPonRsrMgr: testResMgr.PonRsrMgr,\n\t\tTechprofileRef: testResMgr.TechProfileRef,\n\t}\n\trsrMgr.InitLocalCache()\n\n\treturn &rsrMgr\n}", "func TestAppRecovery(t *testing.T) {\n\tserviceContext := entrypoint.StartAllServicesWithManualScheduler()\n\tproxy := serviceContext.RMProxy\n\n\t// Register RM\n\tconfigData := `\npartitions:\n - name: default\n queues:\n - name: root\n submitacl: \"*\"\n queues:\n - name: a\n resources:\n guaranteed:\n memory: 100\n vcore: 10\n max:\n memory: 150\n vcore: 20\n`\n\tconfigs.MockSchedulerConfigByData([]byte(configData))\n\tmockRM := NewMockRMCallbackHandler()\n\n\t_, err := proxy.RegisterResourceManager(\n\t\t&si.RegisterResourceManagerRequest{\n\t\t\tRmID: \"rm:123\",\n\t\t\tPolicyGroup: \"policygroup\",\n\t\t\tVersion: \"0.0.2\",\n\t\t}, mockRM)\n\n\tassert.NilError(t, err, \"RegisterResourceManager failed\")\n\n\tappID := \"app-1\"\n\t// Register nodes, and add apps\n\terr = proxy.Update(&si.UpdateRequest{\n\t\tNewSchedulableNodes: []*si.NewNodeInfo{\n\t\t\t{\n\t\t\t\tNodeID: \"node-1:1234\",\n\t\t\t\tAttributes: map[string]string{},\n\t\t\t\tSchedulableResource: &si.Resource{\n\t\t\t\t\tResources: map[string]*si.Quantity{\n\t\t\t\t\t\t\"memory\": {Value: 100},\n\t\t\t\t\t\t\"vcore\": {Value: 20},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tNodeID: \"node-2:1234\",\n\t\t\t\tAttributes: map[string]string{},\n\t\t\t\tSchedulableResource: &si.Resource{\n\t\t\t\t\tResources: map[string]*si.Quantity{\n\t\t\t\t\t\t\"memory\": {Value: 100},\n\t\t\t\t\t\t\"vcore\": {Value: 20},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tNewApplications: newAddAppRequest(map[string]string{appID: \"root.a\"}),\n\t\tRmID: \"rm:123\",\n\t})\n\n\tassert.NilError(t, err, \"UpdateRequest nodes and apps failed\")\n\n\t// waiting for recovery\n\tmockRM.waitForAcceptedNode(t, \"node-1:1234\", 1000)\n\tmockRM.waitForAcceptedNode(t, \"node-2:1234\", 1000)\n\n\tapp01 := serviceContext.Scheduler.GetClusterSchedulingContext().\n\t\tGetSchedulingApplication(appID, \"[rm:123]default\")\n\tassert.Assert(t, app01 != nil)\n\tassert.Equal(t, app01.ApplicationInfo.ApplicationID, appID)\n\tassert.Equal(t, app01.ApplicationInfo.QueueName, \"root.a\")\n}", "func (suite *ReserverTestSuite) TestTaskLen() {\n\thost := &models_v0.Host{\n\t\tHost: creareHostInfo(),\n\t\tTasks: []*resmgr.Task{\n\t\t\tcreateResMgrTask(),\n\t\t},\n\t}\n\tsuite.Equal(taskLen(host), 1)\n}", "func testReorg(t *testing.T, miner1, miner2 *rpctest.Harness,\n\tclient *BitcoindClient) {\n\n\tminer1Hash, commonHeight, err := miner1.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\n\tminer2Hash, miner2Height, err := miner2.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, commonHeight, miner2Height)\n\trequire.Equal(t, miner1Hash, miner2Hash)\n\n\t// Let miner2 generate a few blocks and ensure that our bitcoind client\n\t// is notified of this block.\n\thashes, err := miner2.Client.Generate(5)\n\trequire.NoError(t, err)\n\trequire.Len(t, hashes, 5)\n\n\tntfns := client.Notifications()\n\n\tfor i := 0; i < 5; i++ {\n\t\tcommonHeight++\n\t\tntfnHash := waitForBlockNtfn(t, ntfns, commonHeight, true)\n\t\trequire.True(t, ntfnHash.IsEqual(hashes[i]))\n\t}\n\n\t// Now disconnect the two miners.\n\terr = miner1.Client.AddNode(miner2.P2PAddress(), rpcclient.ANRemove)\n\trequire.NoError(t, err)\n\n\t// Generate 5 blocks on miner2.\n\t_, err = miner2.Client.Generate(5)\n\trequire.NoError(t, err)\n\n\t// Since the miners have been disconnected, we expect not to get any\n\t// notifications from our client since our client is connected to\n\t// miner1.\n\tselect {\n\tcase ntfn := <-ntfns:\n\t\tt.Fatalf(\"received a notification of type %T but expected, \"+\n\t\t\t\"none\", ntfn)\n\n\tcase <-time.After(time.Millisecond * 500):\n\t}\n\n\t// Now generate 3 blocks on miner1. Note that to force our client to\n\t// experience a re-org, miner1 must generate fewer blocks here than\n\t// miner2 so that when they reconnect, miner1 does a re-org to switch\n\t// to the longer chain.\n\t_, err = miner1.Client.Generate(3)\n\trequire.NoError(t, err)\n\n\t// Read the notifications for the new blocks\n\tfor i := 0; i < 3; i++ {\n\t\t_ = waitForBlockNtfn(t, ntfns, commonHeight+int32(i+1), true)\n\t}\n\n\t// Ensure that the two miners have different ideas of what the best\n\t// block is.\n\thash1, height1, err := miner1.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\trequire.Equal(t, commonHeight+3, height1)\n\n\thash2, height2, err := miner2.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\trequire.Equal(t, commonHeight+5, height2)\n\n\trequire.False(t, hash1.IsEqual(hash2))\n\n\t// Reconnect the miners. This should result in miner1 reorging to match\n\t// miner2. Since our client is connected to a node connected to miner1,\n\t// we should get the expected disconnected and connected notifications.\n\terr = rpctest.ConnectNode(miner1, miner2)\n\trequire.NoError(t, err)\n\n\terr = rpctest.JoinNodes(\n\t\t[]*rpctest.Harness{miner1, miner2}, rpctest.Blocks,\n\t)\n\trequire.NoError(t, err)\n\n\t// Check that the miners are now on the same page.\n\thash1, height1, err = miner1.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\n\thash2, height2, err = miner2.Client.GetBestBlock()\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, commonHeight+5, height2)\n\trequire.Equal(t, commonHeight+5, height1)\n\trequire.True(t, hash1.IsEqual(hash2))\n\n\t// We expect our client to get 3 BlockDisconnected notifications first\n\t// signaling the unwinding of its top 3 blocks.\n\tfor i := 0; i < 3; i++ {\n\t\t_ = waitForBlockNtfn(t, ntfns, commonHeight+int32(3-i), false)\n\t}\n\n\t// Now we expect 5 BlockConnected notifications.\n\tfor i := 0; i < 5; i++ {\n\t\t_ = waitForBlockNtfn(t, ntfns, commonHeight+int32(i+1), true)\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"renounceOwnership\")\n}", "func TestAllocRunner_MoveAllocDir(t *testing.T) {\n\tci.Parallel(t)\n\n\t// Step 1: start and run a task\n\talloc := mock.BatchAlloc()\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tar.Run()\n\tdefer destroy(ar)\n\n\tWaitForClientState(t, ar, structs.AllocClientStatusComplete)\n\n\t// Step 2. Modify its directory\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\tdataFile := filepath.Join(ar.allocDir.SharedDir, \"data\", \"data_file\")\n\tioutil.WriteFile(dataFile, []byte(\"hello world\"), os.ModePerm)\n\ttaskDir := ar.allocDir.TaskDirs[task.Name]\n\ttaskLocalFile := filepath.Join(taskDir.LocalDir, \"local_file\")\n\tioutil.WriteFile(taskLocalFile, []byte(\"good bye world\"), os.ModePerm)\n\n\t// Step 3. Start a new alloc\n\talloc2 := mock.BatchAlloc()\n\talloc2.PreviousAllocation = alloc.ID\n\talloc2.Job.TaskGroups[0].EphemeralDisk.Sticky = true\n\n\tconf2, cleanup := testAllocRunnerConfig(t, alloc2)\n\tconf2.PrevAllocWatcher, conf2.PrevAllocMigrator = allocwatcher.NewAllocWatcher(allocwatcher.Config{\n\t\tAlloc: alloc2,\n\t\tPreviousRunner: ar,\n\t\tLogger: conf2.Logger,\n\t})\n\tdefer cleanup()\n\tar2, err := NewAllocRunner(conf2)\n\trequire.NoError(t, err)\n\n\tar2.Run()\n\tdefer destroy(ar2)\n\n\tWaitForClientState(t, ar, structs.AllocClientStatusComplete)\n\n\t// Ensure that data from ar was moved to ar2\n\tdataFile = filepath.Join(ar2.allocDir.SharedDir, \"data\", \"data_file\")\n\tfileInfo, _ := os.Stat(dataFile)\n\trequire.NotNilf(t, fileInfo, \"file %q not found\", dataFile)\n\n\ttaskDir = ar2.allocDir.TaskDirs[task.Name]\n\ttaskLocalFile = filepath.Join(taskDir.LocalDir, \"local_file\")\n\tfileInfo, _ = os.Stat(taskLocalFile)\n\trequire.NotNilf(t, fileInfo, \"file %q not found\", dataFile)\n\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar personInterface interface{}\n\tif err := json.Unmarshal(body, &personInterface); err != nil {\n\t\tutils.SendJSONResponse(w, 422, \"Not Processing\", nil)\n\t}\n\n\tperson := personInterface.(map[string]interface{})\n\n\tsession := utils.GetMongoSession()\n\tdefer session.Close()\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tupdateInfo, errDB := session.DB(\"test_db\").C(\"persons\").Upsert(\n\t\tbson.M{\"email\": person[\"email\"]},\n\t\tbson.M{\"$set\": person},\n\t)\n\n\tif errDB != nil {\n\t\tpanic(errDB)\n\t}\n\n\tutils.SendJSONResponse(w, 0, \"Success\", updateInfo)\n}", "func TestRTCPLifecyclePartialAllocation(t *testing.T) {\n\tassert := assert.New(t)\n\n\tencryptHeader := &rtcp.Header{}\n\tencryptContext, err := CreateContext(rtcpTestMasterKey, rtcpTestMasterSalt, cipherContextAlgo)\n\tif err != nil {\n\t\tt.Errorf(\"CreateContext failed: %v\", err)\n\t}\n\n\tdecryptHeader := &rtcp.Header{}\n\tdecryptContext, err := CreateContext(rtcpTestMasterKey, rtcpTestMasterSalt, cipherContextAlgo)\n\tif err != nil {\n\t\tt.Errorf(\"CreateContext failed: %v\", err)\n\t}\n\n\t// Copy packet, asserts that partial buffers can be used\n\tdecryptDst := make([]byte, len(rtcpTestDecrypted)*2)\n\n\tactualDecrypted, err := decryptContext.DecryptRTCP(decryptDst, rtcpTestEncrypted, decryptHeader)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if decryptHeader.Type != rtcp.TypeSenderReport {\n\t\tt.Fatal(\"DecryptRTCP failed to populate input rtcp.Header\")\n\t}\n\tassert.Equal(actualDecrypted, rtcpTestDecrypted, \"RTCP failed to decrypt\")\n\n\t// Copy packet, asserts that partial buffers can be used\n\tencryptDst := make([]byte, len(rtcpTestEncrypted)/2)\n\n\tactualEncrypted, err := encryptContext.EncryptRTCP(encryptDst, rtcpTestDecrypted, encryptHeader)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if encryptHeader.Type != rtcp.TypeSenderReport {\n\t\tt.Fatal(\"EncryptRTCP failed to populate input rtcp.Header\")\n\t}\n\tassert.Equal(actualEncrypted, rtcpTestEncrypted, \"RTCP failed to encrypt\")\n}", "func TestAllocRunner_PersistState_Destroyed(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.BatchAlloc()\n\ttaskName := alloc.Job.LookupTaskGroup(alloc.TaskGroup).Tasks[0].Name\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tconf.StateDB = state.NewMemDB(conf.Logger)\n\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\n\tgo ar.Run()\n\n\tselect {\n\tcase <-ar.WaitCh():\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(t, \"timed out waiting for alloc to complete\")\n\t}\n\n\t// test final persisted state upon completion\n\trequire.NoError(t, ar.PersistState())\n\tallocs, _, err := conf.StateDB.GetAllAllocations()\n\trequire.NoError(t, err)\n\trequire.Len(t, allocs, 1)\n\trequire.Equal(t, alloc.ID, allocs[0].ID)\n\t_, ts, err := conf.StateDB.GetTaskRunnerState(alloc.ID, taskName)\n\trequire.NoError(t, err)\n\trequire.Equal(t, structs.TaskStateDead, ts.State)\n\n\t// check that DB alloc is empty after destroying AR\n\tar.Destroy()\n\tselect {\n\tcase <-ar.DestroyCh():\n\tcase <-time.After(10 * time.Second):\n\t\trequire.Fail(t, \"timedout waiting for destruction\")\n\t}\n\n\tallocs, _, err = conf.StateDB.GetAllAllocations()\n\trequire.NoError(t, err)\n\trequire.Empty(t, allocs)\n\t_, ts, err = conf.StateDB.GetTaskRunnerState(alloc.ID, taskName)\n\trequire.NoError(t, err)\n\trequire.Nil(t, ts)\n\n\t// check that DB alloc is empty after persisting state of destroyed AR\n\tar.PersistState()\n\tallocs, _, err = conf.StateDB.GetAllAllocations()\n\trequire.NoError(t, err)\n\trequire.Empty(t, allocs)\n\t_, ts, err = conf.StateDB.GetTaskRunnerState(alloc.ID, taskName)\n\trequire.NoError(t, err)\n\trequire.Nil(t, ts)\n}", "func TestDryRunAllocateNext(t *testing.T) {\n\tpr, err := net.ParsePortRange(\"10000-10200\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Allocate some ports before calling\n\tpreviouslyAllocated := []int{10000, 10010, 10020}\n\tr, err := NewInMemory(*pr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, port := range previouslyAllocated {\n\t\t_ = r.Allocate(port)\n\t}\n\tfreeAtStart := r.Free()\n\n\t// AllocateNext without a previously unused dry run operation\n\top := StartOperation(r, true)\n\tport, err := op.AllocateNext()\n\tif port == 0 {\n\t\tt.Errorf(\"expected non zero port but got: %v\", port)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error but got: %v\", err)\n\t}\n\n\t// Try to allocate the returned port using the same operation\n\tif e, a := ErrAllocated, op.Allocate(port); e != a {\n\t\tt.Errorf(\"expected %v but got: %v\", e, a)\n\t}\n\n\t// AllocateNext with a previously used dry run operation\n\top = StartOperation(r, true)\n\t_ = op.Allocate(12345)\n\tport, err = op.AllocateNext()\n\tif port == 0 {\n\t\tt.Errorf(\"expected non zero port but got: %v\", port)\n\t}\n\tif port == 12345 {\n\t\tt.Errorf(\"expected port not to be 12345 but got %v\", port)\n\t}\n\tif err != nil {\n\t\tt.Errorf(\"expected no error but got: %v\", err)\n\t}\n\n\t// Make sure no port allocations were actually made by the dry run\n\tfreeAtEnd := r.Free()\n\tif freeAtStart != freeAtEnd {\n\t\tt.Errorf(\"expected %v free ports but got %v\", freeAtStart, freeAtEnd)\n\t}\n}", "func (m *MockTChanNode) Repair(ctx thrift.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Repair\", ctx)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAccountCorrupted(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\n\t// create a renter\n\trt, err := newRenterTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr := rt.Close()\n\t\tif err != nil {\n\t\t\tt.Log(err)\n\t\t}\n\t}()\n\tr := rt.renter\n\n\t// create a number accounts\n\taccounts, err := openRandomTestAccountsOnRenter(r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// select a random account of which we'll corrupt data on disk\n\tvar corrupted *account\n\tfor _, account := range accounts {\n\t\tcorrupted = account\n\t\tbreak\n\t}\n\n\t// manually close the renter and corrupt the data at that offset\n\terr = r.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfile, err := r.deps.OpenFile(filepath.Join(r.persistDir, accountsFilename), os.O_RDWR, defaultFilePerm)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trN := fastrand.Intn(5) + 1\n\trOffset := corrupted.staticOffset + int64(fastrand.Intn(accountSize-rN))\n\tn, err := file.WriteAt(fastrand.Bytes(rN), rOffset)\n\tif n != rN {\n\t\tt.Fatalf(\"Unexpected amount of bytes written, %v != %v\", n, rN)\n\t}\n\tif err != nil {\n\t\tt.Fatal(\"Could not write corrupted account data\")\n\t}\n\n\t// reopen the renter\n\tpersistDir := filepath.Join(rt.dir, modules.RenterDir)\n\trl := ratelimit.NewRateLimit(0, 0, 0)\n\tr, errChan := New(rt.gateway, rt.cs, rt.wallet, rt.tpool, rt.mux, rl, persistDir)\n\tif err := <-errChan; err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = rt.addRenter(r)\n\n\t// verify only the non corrupted accounts got reloaded properly\n\tam := r.staticAccountManager\n\tam.mu.Lock()\n\t// verify the amount of accounts reloaded is one less\n\texpected := len(accounts) - 1\n\tif len(am.accounts) != expected {\n\t\tt.Errorf(\"Unexpected amount of accounts, %v != %v\", len(am.accounts), expected)\n\t}\n\tfor _, account := range am.accounts {\n\t\tif account.staticID.SPK().Equals(corrupted.staticID.SPK()) {\n\t\t\tt.Error(\"Corrupted account was not properly skipped\")\n\t\t}\n\t}\n\tam.mu.Unlock()\n}", "func TestNewResizeService(t *testing.T) {\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\tmockResizeStorage := mocks.NewMockResizeStorage(mockCtrl)\n\tmockConverter := mocks.NewMockConverter(mockCtrl)\n\tmockPubSub := mocks.NewMockPublisherConsumer(mockCtrl)\n\n\trs := NewResizeService(mockResizeStorage, mockConverter, mockPubSub)\n\tassert.Equal(t, mockConverter, rs.Converter)\n\tassert.Equal(t, mockResizeStorage, rs.Storage)\n}", "func (s *flowControlSuite) TestMemoryQuotaReleaseZero(c *check.C) {\n\tdefer testleak.AfterTest(c)()\n\n\tcontroller := NewTableMemoryQuota(1024)\n\tcontroller.Release(0)\n}", "func TestAddPerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser, testUser User\n\n\t\taddPerson = func(fname, lname, jobType, officeName, livingspaceName string) {\n\t\t\tif livingspaceName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, livingspaceName, \"livingspace\")\n\t\t\t}\n\n\t\t\tif officeName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, officeName, \"office\")\n\t\t\t}\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, jobType, officeName, livingspaceName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for AddPerson\", t, func() {\n\t\tConvey(\"AddPerson should return a User with all correct values present and an error\", func() {\n\t\t\tvar runValuesTests = func(rm models.Room) {\n\t\t\t\tSo(rm.Capacity, ShouldNotEqual, 0)\n\t\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Name, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Type, ShouldNotBeBlank)\n\t\t\t}\n\n\t\t\taddPerson(\"Jade\", \"Flora\", \"fellow\", \"Narnia\", \"PHP\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user.FirstName, ShouldNotBeBlank)\n\t\t\tSo(user.ID, ShouldNotBeBlank)\n\t\t\tSo(user.LastName, ShouldNotBeBlank)\n\t\t\tSo(user.Type, ShouldNotBeBlank)\n\t\t\tSo(user.User, ShouldNotResemble, testUser.User)\n\n\t\t\trunValuesTests(user.LivingSpace)\n\t\t\trunValuesTests(user.Office)\n\t\t})\n\n\t\tConvey(\"Print the successfully created User and Room \", func() {\n\t\t\taddPerson(\"Jackson\", \"Davids\", \"fellow\", \"\", \"Mogadishu\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (alloc *inMemoryAllocator) ForceRebase(requiredBase int64) error {\n\talloc.base = requiredBase\n\treturn nil\n}", "func TestAllocRunner_TaskLeader_KillTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create two tasks in the task group\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Name = \"task1\"\n\ttask.Driver = \"mock_driver\"\n\ttask.KillTimeout = 10 * time.Millisecond\n\ttask.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\n\ttask2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\ttask2.Name = \"task2\"\n\ttask2.Driver = \"mock_driver\"\n\ttask2.Leader = true\n\ttask2.Config = map[string]interface{}{\n\t\t\"run_for\": \"1s\",\n\t}\n\talloc.Job.TaskGroups[0].Tasks = append(alloc.Job.TaskGroups[0].Tasks, task2)\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\talloc.AllocatedResources.Tasks[task2.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\n\t// Wait for all tasks to be killed\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Task1 should be killed because Task2 exited\n\t\tstate1 := last.TaskStates[task.Name]\n\t\tif state1.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state1.State, structs.TaskStateDead)\n\t\t}\n\t\tif state1.FinishedAt.IsZero() || state1.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\t\tif len(state1.Events) < 2 {\n\t\t\t// At least have a received and destroyed\n\t\t\treturn false, fmt.Errorf(\"Unexpected number of events\")\n\t\t}\n\n\t\tfound := false\n\t\tkillingMsg := \"\"\n\t\tfor _, e := range state1.Events {\n\t\t\tif e.Type == structs.TaskLeaderDead {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t\tif e.Type == structs.TaskKilling {\n\t\t\t\tkillingMsg = e.DisplayMessage\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false, fmt.Errorf(\"Did not find event %v\", structs.TaskLeaderDead)\n\t\t}\n\n\t\texpectedKillingMsg := \"Sent interrupt. Waiting 10ms before force killing\"\n\t\tif killingMsg != expectedKillingMsg {\n\t\t\treturn false, fmt.Errorf(\"Unexpected task event message - wanted %q. got %q\", expectedKillingMsg, killingMsg)\n\t\t}\n\n\t\t// Task Two should be dead\n\t\tstate2 := last.TaskStates[task2.Name]\n\t\tif state2.State != structs.TaskStateDead {\n\t\t\treturn false, fmt.Errorf(\"got state %v; want %v\", state2.State, structs.TaskStateDead)\n\t\t}\n\t\tif state2.FinishedAt.IsZero() || state2.StartedAt.IsZero() {\n\t\t\treturn false, fmt.Errorf(\"expected to have a start and finish time\")\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\tt.Fatalf(\"err: %v\", err)\n\t})\n}", "func TestRetainBySize(t *testing.T) {\n\ttemp, err := os.MkdirTemp(\"\", \"TestRetainBySize\")\n\tt.Cleanup(func() {\n\t\t_ = os.RemoveAll(temp)\n\t})\n\trequire.NoError(t, err)\n\tBasePath = temp\n\texpectedFolders := []string{\"backup-1\", \"backup-2\", \"backup-3\", \"backup-4\", \"backup-5\"}\n\t// using a zeroed slice here, being much faster than generating a random gigabyte of bytes\n\tzeroGig := make([]byte, 1024*1024*1024*1)\n\tfor _, folder := range expectedFolders {\n\t\trequire.NoError(t, os.MkdirAll(path.Join(temp, folder), 0750))\n\t\trequire.NoError(t, os.WriteFile(path.Join(temp, folder, \"snapshot.snap\"), zeroGig, 0600))\n\t}\n\n\trequire.NoError(t, retainBySizeGb(10))\n\trequireFoldersExist(t, temp, expectedFolders)\n\n\tfor i := 4; i >= 0; i-- {\n\t\trequire.NoError(t, retainBySizeGb(i))\n\t\trequireFoldersExist(t, temp, expectedFolders[len(expectedFolders)-i:])\n\t}\n\n\t// in the end we should arrive at the empty list, which would be a no-op when retaining with 0.\n\trequireFoldersExist(t, temp, []string{})\n\trequire.NoError(t, retainBySizeGb(0))\n\trequireFoldersExist(t, temp, []string{})\n}", "func (s *CassandraBackendSuite) TestReentrable(c *C) {\n\tif s.shouldSkip {\n\t\tc.Skip(\"Cassandra backend is not activated\")\n\t}\n\n\t_, err := NewCassandraBackend(s.GetConfig(), s.timeProvider)\n\tc.Assert(err, IsNil)\n\n\t_, err = NewCassandraBackend(s.GetConfig(), s.timeProvider)\n\tc.Assert(err, IsNil)\n}", "func (s *StorageMemory) SavePerson(p Person) error {\n\ts.People = append(s.People, p)\n\n\treturn nil\n}", "func (env *DisconnectEnv) ReplicaReassignTest() {\n\t// This test needs at least 4 nodes, a refuge node, a mayastor node to isolate, and 2 other mayastor nodes\n\tExpect(len(env.otherNodes)).To(BeNumerically(\">=\", 3))\n\n\tfmt.Printf(\"disconnecting \\\"%s\\\"\\n\", env.nodeToIsolate)\n\tDisconnectNode(env.nodeToIsolate, env.otherNodes, env.disconnectMethod)\n\n\tfmt.Printf(\"running fio against the volume\\n\")\n\tcommon.RunFio(env.fioPodName, 20)\n\n\tfmt.Printf(\"waiting up to %s for disconnection to affect the nexus\\n\", disconnectionTimeoutSecs)\n\tEventually(func() string {\n\t\treturn common.GetMsvState(env.uuid)\n\t},\n\t\tdisconnectionTimeoutSecs, // timeout\n\t\t\"1s\", // polling interval\n\t).Should(Equal(\"degraded\"))\n\n\tfmt.Printf(\"volume is in state \\\"%s\\\"\\n\", common.GetMsvState(env.uuid))\n\n\tfmt.Printf(\"waiting up to %s for the volume to be repaired\\n\", repairTimeoutSecs)\n\tEventually(func() string {\n\t\treturn common.GetMsvState(env.uuid)\n\t},\n\t\trepairTimeoutSecs, // timeout\n\t\t\"1s\", // polling interval\n\t).Should(Equal(\"healthy\"))\n\n\tfmt.Printf(\"volume is in state \\\"%s\\\"\\n\", common.GetMsvState(env.uuid))\n\n\tfmt.Printf(\"running fio while node is disconnected\\n\")\n\tcommon.RunFio(env.fioPodName, 20)\n\n\tfmt.Printf(\"reconnecting \\\"%s\\\"\\n\", env.nodeToIsolate)\n\tenv.ReconnectNode(true)\n\n\tfmt.Printf(\"running fio when node is reconnected\\n\")\n\tcommon.RunFio(env.fioPodName, 20)\n}", "func TestRecreate(t *testing.T) {\n\tdb, err := Open(db_filename, \"c\")\n\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\n\tdb.Close()\n\n\tf, err := Open(db_filename, \"r\")\n\n\tdefer f.Close()\n\tdefer os.Remove(db_filename)\n\tif err != nil {\n\t\tt.Error(\"Couldn't open new database\")\n\t}\n\n\tif os.IsExist(err) {\n\t\tt.Error(\"Database wasn't actually created\")\n\t}\n\n\t// Validate that there are no keys in the DB\n\t// If err was not found, a key was returned\n\t_, err = f.FirstKey()\n\tif err == nil {\n\t\tt.Error(\"Database was not emptied of keys\")\n\t}\n}", "func (m *MockClient) ReopenPR(org, repo string, number int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ReopenPR\", org, repo, number)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPoolRegistry) HardDeleteAllocations(allocations []registry.BrickAllocation) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HardDeleteAllocations\", allocations)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCollectGarbage(t *testing.T) {\n\tCollectGarbage()\n}", "func Realloc(b []byte, n int) []byte {\n\tnewSize := len(b) + n\n\tif cap(b) < newSize {\n\t\tbs := make([]byte, len(b), newSize)\n\t\tcopy(bs, b)\n\t\treturn bs\n\t}\n\n\t// slice b has capability to store n bytes\n\treturn b\n}", "func TestAppRecoveryAlone(t *testing.T) {\n\tserviceContext := entrypoint.StartAllServicesWithManualScheduler()\n\tproxy := serviceContext.RMProxy\n\n\t// Register RM\n\tconfigData := `\npartitions:\n - name: default\n queues:\n - name: root\n submitacl: \"*\"\n queues:\n - name: a\n resources:\n guaranteed:\n memory: 100\n vcore: 10\n max:\n memory: 150\n vcore: 20\n`\n\tconfigs.MockSchedulerConfigByData([]byte(configData))\n\tmockRM := NewMockRMCallbackHandler()\n\n\t_, err := proxy.RegisterResourceManager(\n\t\t&si.RegisterResourceManagerRequest{\n\t\t\tRmID: \"rm:123\",\n\t\t\tPolicyGroup: \"policygroup\",\n\t\t\tVersion: \"0.0.2\",\n\t\t}, mockRM)\n\n\tassert.NilError(t, err, \"RegisterResourceManager failed\")\n\n\t// Register apps alone\n\tappID := \"app-1\"\n\terr = proxy.Update(&si.UpdateRequest{\n\t\tNewApplications: newAddAppRequest(map[string]string{appID: \"root.a\", \"app-2\": \"root.a\"}),\n\t\tRmID: \"rm:123\",\n\t})\n\n\tassert.NilError(t, err, \"UpdateRequest app failed\")\n\n\tmockRM.waitForAcceptedApplication(t, appID, 1000)\n\tmockRM.waitForAcceptedApplication(t, \"app-2\", 1000)\n\n\t// verify app state\n\tapps := serviceContext.Cache.GetPartition(\"[rm:123]default\").GetApplications()\n\tfound := 0\n\tfor _, app := range apps {\n\t\tif app.ApplicationID == appID || app.ApplicationID == \"app-2\" {\n\t\t\tassert.Equal(t, app.GetApplicationState(), cache.New.String())\n\t\t\tfound++\n\t\t}\n\t}\n\n\tassert.Equal(t, found, 2, \"did not find expected number of apps after recovery\")\n}", "func TestAllocRunner_TerminalUpdate_Destroy(t *testing.T) {\n\tci.Parallel(t)\n\talloc := mock.BatchAlloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\t// Ensure task takes some time\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Driver = \"mock_driver\"\n\ttask.Config[\"run_for\"] = \"10s\"\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar)\n\tgo ar.Run()\n\tupd := conf.StateUpdater.(*MockStateUpdater)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\t\tif last.ClientStatus != structs.AllocClientStatusRunning {\n\t\t\treturn false, fmt.Errorf(\"got status %v; want %v\", last.ClientStatus, structs.AllocClientStatusRunning)\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Update the alloc to be terminal which should cause the alloc runner to\n\t// stop the tasks and wait for a destroy.\n\tupdate := ar.alloc.Copy()\n\tupdate.DesiredStatus = structs.AllocDesiredStatusStop\n\tar.Update(update)\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory still exists\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err != nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir destroyed: %v\", ar.allocDir.AllocDir)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n\n\t// Send the destroy signal and ensure the AllocRunner cleans up.\n\tar.Destroy()\n\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\tlast := upd.Last()\n\t\tif last == nil {\n\t\t\treturn false, fmt.Errorf(\"No updates\")\n\t\t}\n\n\t\t// Check the status has changed.\n\t\tif last.ClientStatus != structs.AllocClientStatusComplete {\n\t\t\treturn false, fmt.Errorf(\"got client status %v; want %v\", last.ClientStatus, structs.AllocClientStatusComplete)\n\t\t}\n\n\t\t// Check the alloc directory was cleaned\n\t\tif _, err := os.Stat(ar.allocDir.AllocDir); err == nil {\n\t\t\treturn false, fmt.Errorf(\"alloc dir still exists: %v\", ar.allocDir.AllocDir)\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn false, fmt.Errorf(\"stat err: %v\", err)\n\t\t}\n\n\t\treturn true, nil\n\t}, func(err error) {\n\t\trequire.Fail(t, \"err: %v\", err)\n\t})\n}", "func TestReorg(t *testing.T) {\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// Clear the blockchain and set the provided chain to build on the ancestor\n\t// block.\n\treset := func() {\n\t\tbtc.blockCache.mtx.Lock()\n\t\tdefer btc.blockCache.mtx.Unlock()\n\t\tcleanTestChain()\n\t\tnewBC := newBlockCache()\n\t\tbtc.blockCache.blocks = newBC.blocks\n\t\tbtc.blockCache.mainchain = newBC.mainchain\n\t\tbtc.blockCache.best = newBC.best\n\t}\n\treset()\n\n\tancestorHeight := uint32(50)\n\tancestorHash := testAddBlockVerbose(nil, nil, 0, ancestorHeight)\n\n\tmakeChain := func() []*chainhash.Hash {\n\t\tchain := make([]*chainhash.Hash, 0, 3)\n\t\tfor i := 0; i < 3; i++ {\n\t\t\th := testAddBlockVerbose(nil, nil, 0, ancestorHeight+1+uint32(i))\n\t\t\tchain = append(chain, h)\n\t\t}\n\t\treturn chain\n\t}\n\tchainA := makeChain()\n\tchainB := makeChain()\n\n\tsetChain := func(hashes []*chainhash.Hash) {\n\t\ttestClearBestBlock()\n\t\trootConfs := int64(len(hashes)) + 1\n\t\t// Add the ancestor block\n\t\ttestAddBlockVerbose(ancestorHash, nil, rootConfs, ancestorHeight)\n\t\tprevHash := ancestorHash\n\t\tfor i, hash := range hashes {\n\t\t\tprevHash = testAddBlockVerbose(hash, prevHash, rootConfs-int64(i), ancestorHeight+uint32(i))\n\n\t\t}\n\t\ttime.Sleep(blockPollDelay)\n\t}\n\n\tsetSidechainConfs := func(hashes []*chainhash.Hash) {\n\t\tfor _, hash := range hashes {\n\t\t\tblk, err := btc.node.GetBlockVerbose(hash)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error retrieving sidechain block to set confirmations: %v\", err)\n\t\t\t}\n\t\t\t// Set Confirmations\n\t\t\tbtc.blockCache.mtx.Lock() // read from (*blockCache).add in cache.go\n\t\t\ttestChainMtx.Lock() // field of testChain\n\t\t\tblk.Confirmations = -1\n\t\t\ttestChainMtx.Unlock()\n\t\t\tbtc.blockCache.mtx.Unlock()\n\t\t}\n\t}\n\n\tcheckOrphanState := func(hashes []*chainhash.Hash, orphanState bool) bool {\n\t\tfor _, hash := range hashes {\n\t\t\tblk, err := btc.getBtcBlock(hash)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"error retrieving block after reorg: %v\\n\", err)\n\t\t\t}\n\t\t\tif blk.orphaned != orphanState {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// The test will start with chain A at length lenA above the ancestor. A reorg\n\t// of length lenB will fully replace chain A. Chain A should be fully\n\t// orphaned and chain B should be fully mainchain afterwards.\n\ttest := func(lenA, lenB int) {\n\t\treset()\n\t\tsetChain(chainA[:lenA])\n\t\t// Check that chain A is all mainchain.\n\t\tif !checkOrphanState(chainA[:lenA], false) {\n\t\t\tt.Fatalf(\"chain A block not mainchain for test %d:%d before reorg\", lenA, lenB)\n\t\t}\n\t\t// Reorg the chain.\n\t\tsetSidechainConfs(chainA[:lenA])\n\t\tsetChain(chainB[:lenB])\n\t\t// Chain A should all be orphaned.\n\t\tif !checkOrphanState(chainA[:lenA], true) {\n\t\t\tt.Fatalf(\"chain A block still mainchain for test %d:%d after reorg\", lenA, lenB)\n\t\t}\n\t\t// Chain B should all be mainchain.\n\t\tif !checkOrphanState(chainB[:lenB], false) {\n\t\t\tt.Fatalf(\"chain B block not mainchain for test %d:%d after reorg\", lenA, lenB)\n\t\t}\n\t}\n\n\t// Now run 9 tests.\n\tfor a := 1; a <= 3; a++ {\n\t\tfor b := 1; b <= 3; b++ {\n\t\t\ttest(a, b)\n\t\t}\n\t}\n\n\t// Create a transaction at the tip, then orphan the block and move the\n\t// transaction to mempool.\n\treset()\n\tsetChain(chainA)\n\ttipHeight := btc.blockCache.tipHeight()\n\ttxHash := randomHash()\n\ttip, _ := btc.blockCache.atHeight(tipHeight)\n\tmsg := testMakeMsgTx(false)\n\ttestAddBlockVerbose(&tip.hash, nil, 1, tipHeight)\n\ttestAddTxOut(msg.tx, 0, txHash, &tip.hash, int64(tipHeight), 1)\n\tutxo, err := btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"utxo error 1: %v\", err)\n\t}\n\tconfs, err := utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"wrong number of confirmations. expected 1, got %d\", confs)\n\t}\n\n\t// Orphan the block and move the transaction to mempool.\n\tbtc.blockCache.reorg(int64(ancestorHeight))\n\ttestAddTxOut(msg.tx, 0, txHash, nil, 0, 0)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error after reorg: %v\", err)\n\t}\n\tif confs != 0 {\n\t\tt.Fatalf(\"Expected zero confirmations after reorg, found %d\", confs)\n\t}\n\n\t// Start over, but put it in a lower block instead.\n\treset()\n\tsetChain(chainA)\n\ttip, _ = btc.blockCache.atHeight(tipHeight)\n\ttestAddBlockVerbose(&tip.hash, nil, 1, tipHeight)\n\ttestAddTxOut(msg.tx, 0, txHash, &tip.hash, int64(tipHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"utxo error 2: %v\", err)\n\t}\n\n\t// Reorg and add a single block with the transaction.\n\tbtc.blockCache.reorg(int64(ancestorHeight))\n\tnewBlockHash := randomHash()\n\ttestAddTxOut(msg.tx, 0, txHash, newBlockHash, int64(ancestorHeight+1), 1)\n\ttestAddBlockVerbose(newBlockHash, ancestorHash, 1, ancestorHeight+1)\n\ttime.Sleep(blockPollDelay)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"Confirmations error after reorg to lower block: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"Expected zero confirmations after reorg to lower block, found %d\", confs)\n\t}\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.RenounceOwnership(&_VorRandomnessRequestMock.TransactOpts)\n}", "func (m *MockSessionRunner) Retire(arg0 protocol.ConnectionID) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Retire\", arg0)\n}", "func (alloc *RuntimePortAllocator) createAndRestorePortAllocator() (err error) {\n\talloc.pa, err = portallocator.NewPortAllocatorCustom(*alloc.pr, func(max int, rangeSpec string) (allocator.Interface, error) {\n\t\treturn allocator.NewAllocationMap(max, rangeSpec), nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tports, err := alloc.getReservedPorts(alloc.client)\n\tif err != nil {\n\t\treturn err\n\t}\n\talloc.log.Info(\"Found reserved ports\", \"ports\", ports)\n\n\tfor _, port := range ports {\n\t\tif err = alloc.pa.Allocate(port); err != nil {\n\t\t\talloc.log.Error(err, \"can't allocate reserved ports\", \"port\", port)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestServiceRegistryExternalTrafficHealthCheckNodePortUserAllocation(t *testing.T) {\n\trandomNodePort := generateRandomNodePort()\n\tctx := genericapirequest.NewDefaultContext()\n\tstorage, _, server := NewTestREST(t, nil)\n\tdefer server.Terminate(t)\n\tsvc := &api.Service{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"external-lb-esipp\"},\n\t\tSpec: api.ServiceSpec{\n\t\t\tSelector: map[string]string{\"bar\": \"baz\"},\n\t\t\tSessionAffinity: api.ServiceAffinityNone,\n\t\t\tType: api.ServiceTypeLoadBalancer,\n\t\t\tPorts: []api.ServicePort{{\n\t\t\t\tPort: 6502,\n\t\t\t\tProtocol: api.ProtocolTCP,\n\t\t\t\tTargetPort: intstr.FromInt(6502),\n\t\t\t}},\n\t\t\tExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeLocal,\n\t\t\tHealthCheckNodePort: randomNodePort,\n\t\t},\n\t}\n\tcreated_svc, err := storage.Create(ctx, svc, false)\n\tif created_svc == nil || err != nil {\n\t\tt.Fatalf(\"Unexpected failure creating service :%v\", err)\n\t}\n\tcreated_service := created_svc.(*api.Service)\n\tif !service.NeedsHealthCheck(created_service) {\n\t\tt.Errorf(\"Expecting health check needed, returned health check not needed instead\")\n\t}\n\tport := service.GetServiceHealthCheckNodePort(created_service)\n\tif port == 0 {\n\t\tt.Errorf(\"Failed to allocate health check node port and set the HealthCheckNodePort\")\n\t}\n\tif port != randomNodePort {\n\t\tt.Errorf(\"Failed to allocate requested nodePort expected %d, got %d\", randomNodePort, port)\n\t}\n}", "func (_Erc20Mock *Erc20MockTransactor) RenounceOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Erc20Mock.contract.Transact(opts, \"renounceOwnership\")\n}", "func (m *MockPackClient) Rebase(arg0 context.Context, arg1 client.RebaseOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Rebase\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCanAllocate(t *testing.T) {\n\tvar cases = []struct {\n\t\ta Money\n\t\tratios []uint\n\t\twant []Money\n\t}{\n\t\t{0, []uint{1, 1, 1}, []Money{0, 0, 0}},\n\t\t{1, []uint{1, 1, 1}, []Money{1, 0, 0}},\n\t\t{2, []uint{1, 1, 1}, []Money{1, 1, 0}},\n\t\t{3, []uint{1, 1, 1}, []Money{1, 1, 1}},\n\t\t{4, []uint{1, 1, 1}, []Money{2, 1, 1}},\n\t\t{5, []uint{1, 1, 1}, []Money{2, 2, 1}},\n\t\t{100, []uint{0, 1, 0}, []Money{0, 100, 0}},\n\t\t{3, []uint{0, 5, 0}, []Money{0, 3, 0}},\n\t\t{300, []uint{1, 1, 1}, []Money{100, 100, 100}},\n\t\t{100, []uint{1, 1, 1}, []Money{34, 33, 33}},\n\t\t{3, []uint{0, 5, 0}, []Money{0, 3, 0}},\n\t\t{3, []uint{0, 4, 2}, []Money{0, 2, 1}},\n\n\t\t// Allocate spare pennies and skip zero weighting.\n\t\t{7, []uint{0, 1, 1}, []Money{0, 4, 3}},\n\n\t\t// Copied from MoneyTest.php\n\t\t{105, []uint{3, 7}, []Money{32, 73}},\n\t\t{5, []uint{1, 1}, []Money{3, 2}},\n\t\t{30000, []uint{122, 878}, []Money{3660, 26340}},\n\t\t{30000, []uint{122, 0, 878}, []Money{3660, 0, 26340}},\n\t\t{12000, []uint{20, 100}, []Money{2000, 10000}},\n\n\t\t// If weightings are equal, the amount will be shared.\n\t\t{30000, []uint{0}, []Money{30000}},\n\t\t{30000, []uint{0, 0, 0}, []Money{10000, 10000, 10000}},\n\n\t\t// Repeat all of the above with negatives.\n\t\t{-0, []uint{1, 1, 1}, []Money{0, 0, 0}},\n\t\t{-1, []uint{1, 1, 1}, []Money{-1, 0, 0}},\n\t\t{-2, []uint{1, 1, 1}, []Money{-1, -1, 0}},\n\t\t{-3, []uint{1, 1, 1}, []Money{-1, -1, -1}},\n\t\t{-4, []uint{1, 1, 1}, []Money{-2, -1, -1}},\n\t\t{-5, []uint{1, 1, 1}, []Money{-2, -2, -1}},\n\t\t{-100, []uint{0, 1, 0}, []Money{0, -100, 0}},\n\t\t{-3, []uint{0, 5, 0}, []Money{0, -3, 0}},\n\t\t{-300, []uint{1, 1, 1}, []Money{-100, -100, -100}},\n\t\t{-100, []uint{1, 1, 1}, []Money{-34, -33, -33}},\n\t\t{-3, []uint{0, 5, 0}, []Money{0, -3, 0}},\n\t\t{-3, []uint{0, 4, 2}, []Money{0, -2, -1}},\n\t\t{-105, []uint{3, 7}, []Money{-32, -73}},\n\t\t{-5, []uint{1, 1}, []Money{-3, -2}},\n\t\t{-30000, []uint{122, 878}, []Money{-3660, -26340}},\n\t\t{-30000, []uint{122, 0, 878}, []Money{-3660, 0, -26340}},\n\t\t{-12000, []uint{20, 100}, []Money{-2000, -10000}},\n\t\t{-30000, []uint{0}, []Money{-30000}},\n\t\t{-30000, []uint{0, 0, 0}, []Money{-10000, -10000, -10000}},\n\t}\n\tfor ci, c := range cases {\n\t\tres := c.a.Share(c.ratios)\n\t\tif len(c.ratios) != len(res) {\n\t\t\tt.Errorf(\"Case %d. Incorrect number of allocations returned. Expected %d, got %d: %v\", ci, len(c.ratios), len(res), res)\n\t\t\treturn\n\t\t}\n\t\tfor i := range c.want {\n\t\t\tif c.want[i] != res[i] {\n\t\t\t\tt.Errorf(\"Case %d: Sharing %d into (%v), portion %d: Expected %d, got %d\", ci, c, c.ratios, i, c.want[i], res[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func (_VorRandomnessRequestMock *VorRandomnessRequestMockTransactorSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _VorRandomnessRequestMock.Contract.RenounceOwnership(&_VorRandomnessRequestMock.TransactOpts)\n}", "func (p *Person) Reset() {\n\t(*p).name = \"\"\n\t(*p).age = 0\n}", "func TestManagerRestart(t *testing.T) {\n\tts := memorytopo.NewServer(\"cell1\")\n\tm := NewManager(ts)\n\n\t// Run the manager in the background.\n\twg, _, cancel := StartManager(m)\n\n\t// Create a Sleep job.\n\tuuid, err := m.Create(context.Background(), sleepFactoryName, []string{\"--duration\", \"60\"})\n\tif err != nil {\n\t\tt.Fatalf(\"cannot create sleep workflow: %v\", err)\n\t}\n\n\t// Start the job.\n\tif err := m.Start(context.Background(), uuid); err != nil {\n\t\tt.Fatalf(\"cannot start sleep workflow: %v\", err)\n\t}\n\n\t// Stop the manager.\n\tcancel()\n\twg.Wait()\n\t// Recreate the manager imitating restart.\n\tm = NewManager(ts)\n\n\t// Make sure the workflow is still in the topo server. This\n\t// validates that interrupting the Manager leaves the jobs in\n\t// the right state in the topo server.\n\twi, err := ts.GetWorkflow(context.Background(), uuid)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read workflow %v: %v\", uuid, err)\n\t}\n\tif wi.State != workflowpb.WorkflowState_Running {\n\t\tt.Fatalf(\"unexpected workflow state %v was expecting %v\", wi.State, workflowpb.WorkflowState_Running)\n\t}\n\n\t// Restart the manager.\n\twg, _, cancel = StartManager(m)\n\n\t// Make sure the job is in there shortly.\n\ttimeout := 0\n\tfor {\n\t\ttree, err := m.NodeManager().GetFullTree()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"cannot get full node tree: %v\", err)\n\t\t}\n\t\tif strings.Contains(string(tree), uuid) {\n\t\t\tbreak\n\t\t}\n\t\ttimeout++\n\t\tif timeout == 1000 {\n\t\t\tt.Fatalf(\"failed to wait for full node tree to appear: %v\", string(tree))\n\t\t}\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\t// Stop the job. Note Stop() waits until the background go\n\t// routine that saves the job is done, so when we return from\n\t// this call, the job is saved with the right updated State\n\t// inside the topo server.\n\tif err := m.Stop(context.Background(), uuid); err != nil {\n\t\tt.Fatalf(\"cannot stop sleep workflow: %v\", err)\n\t}\n\n\t// And stop the manager.\n\tcancel()\n\twg.Wait()\n\n\t// Make sure the workflow is stopped in the topo server.\n\twi, err = ts.GetWorkflow(context.Background(), uuid)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read workflow %v: %v\", uuid, err)\n\t}\n\tif wi.State != workflowpb.WorkflowState_Done {\n\t\tt.Fatalf(\"unexpected workflow state %v was expecting %v\", wi.State, workflowpb.WorkflowState_Running)\n\t}\n\tif !strings.Contains(wi.Error, \"canceled\") {\n\t\tt.Errorf(\"invalid workflow error: %v\", wi.Error)\n\t}\n}", "func deletePerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfmt.Println(\"DELETE HIT\")\n\tparams := mux.Vars(r)\n\tresult, err := db.Query(\"SELECT * FROM Persons WHERE pName = ?\", params[\"name\"])\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tvar per Person\n\tfor result.Next() {\n\t\terrs := result.Scan(&per.Age, &per.Name)\n\t\tif errs != nil {\n\t\t\tpanic(errs.Error())\n\t\t}\n\t}\n\tcache.Set(strconv.Itoa(per.Age), []byte(per.Name))\n\n\tstmt, err := db.Prepare(\"DELETE FROM Persons WHERE pName = ?\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t_, err = stmt.Exec(params[\"name\"])\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Fprintf(w, \"Person with name = %s was deleted\", params[\"name\"])\n}", "func ChangePersonPhone(aPerson *Person, newPhone int64) {\n\taPerson.Phone = newPhone\n}", "func (m *MockKubernetesService) RecycleNodePoolNodes(clusterID, poolID string, req *godo.KubernetesNodePoolRecycleNodesRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RecycleNodePoolNodes\", clusterID, poolID, req)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (self *rsaKeyHolder) recreate(obj runtime.Object) {\n\tsecret := obj.(*v1.Secret)\n\tlog.Printf(\"Synchronized secret %s has been deleted. Recreating.\", secret.Name)\n\tif err := self.synchronizer.Create(self.getEncryptionKeyHolder()); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *MockCAClient) Reenroll(arg0 *api.ReenrollmentRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reenroll\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestAllocRunner_TaskLeader_StopRestoredTG(t *testing.T) {\n\tci.Parallel(t)\n\n\talloc := mock.Alloc()\n\ttr := alloc.AllocatedResources.Tasks[alloc.Job.TaskGroups[0].Tasks[0].Name]\n\talloc.Job.TaskGroups[0].RestartPolicy.Attempts = 0\n\talloc.Job.TaskGroups[0].Tasks[0].RestartPolicy.Attempts = 0\n\n\t// Create a leader and follower task in the task group\n\ttask := alloc.Job.TaskGroups[0].Tasks[0]\n\ttask.Name = \"follower1\"\n\ttask.Driver = \"mock_driver\"\n\ttask.KillTimeout = 10 * time.Second\n\ttask.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\n\ttask2 := alloc.Job.TaskGroups[0].Tasks[0].Copy()\n\ttask2.Name = \"leader\"\n\ttask2.Driver = \"mock_driver\"\n\ttask2.Leader = true\n\ttask2.KillTimeout = 10 * time.Millisecond\n\ttask2.Config = map[string]interface{}{\n\t\t\"run_for\": \"10s\",\n\t}\n\n\talloc.Job.TaskGroups[0].Tasks = append(alloc.Job.TaskGroups[0].Tasks, task2)\n\talloc.AllocatedResources.Tasks[task.Name] = tr\n\talloc.AllocatedResources.Tasks[task2.Name] = tr\n\n\tconf, cleanup := testAllocRunnerConfig(t, alloc)\n\tdefer cleanup()\n\n\t// Use a memory backed statedb\n\tconf.StateDB = state.NewMemDB(conf.Logger)\n\n\tar, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\n\t// Mimic Nomad exiting before the leader stopping is able to stop other tasks.\n\tar.tasks[\"leader\"].UpdateState(structs.TaskStateDead, structs.NewTaskEvent(structs.TaskKilled))\n\tar.tasks[\"follower1\"].UpdateState(structs.TaskStateRunning, structs.NewTaskEvent(structs.TaskStarted))\n\n\t// Create a new AllocRunner to test RestoreState and Run\n\tar2, err := NewAllocRunner(conf)\n\trequire.NoError(t, err)\n\tdefer destroy(ar2)\n\n\tif err := ar2.Restore(); err != nil {\n\t\tt.Fatalf(\"error restoring state: %v\", err)\n\t}\n\tar2.Run()\n\n\t// Wait for tasks to be stopped because leader is dead\n\ttestutil.WaitForResult(func() (bool, error) {\n\t\talloc := ar2.Alloc()\n\t\t// TODO: this test does not test anything!!! alloc.TaskStates is an empty map\n\t\tfor task, state := range alloc.TaskStates {\n\t\t\tif state.State != structs.TaskStateDead {\n\t\t\t\treturn false, fmt.Errorf(\"Task %q should be dead: %v\", task, state.State)\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t}, func(err error) {\n\t\tt.Fatalf(\"err: %v\", err)\n\t})\n\n\t// Make sure it GCs properly\n\tar2.Destroy()\n\n\tselect {\n\tcase <-ar2.DestroyCh():\n\t\t// exited as expected\n\tcase <-time.After(10 * time.Second):\n\t\tt.Fatalf(\"timed out waiting for AR to GC\")\n\t}\n}", "func TestCreateInstitutionLocation2(t *testing.T) {\n\tinstitutionsCourse, err := excelize.OpenFile(\"C:/Users/Nicole Abrahams/go/src/obas/util/files/institution_course.xlsx\")\n\tvar newInstitution domain.InstitutionCourse\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tcellVal, err := institutionsCourse.GetRows(\"Sheet1\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\t/***Looping through all the rows that contains Data***/\n\tfor _, value := range cellVal {\n\t\t/***reading the first value in the first row***/\n\t\tnewInstitution = domain.InstitutionCourse{value[0], value[1]}\n\t\t/***Now sending the object to the api***/\n\t\tCreateInstitutionCourse(newInstitution)\n\t\t/**Now clearing the object**/\n\t\tnewInstitution = domain.InstitutionCourse{}\n\t}\n}", "func TestReAttachTCP(t *testing.T) {\n\ttestAttachNTimes(t, 3)\n}", "func resize(p interface{}) (gravity.TestFunc, error) {\n\tparam := p.(resizeParam)\n\n\treturn func(g *gravity.TestContext, cfg gravity.ProvisionerConfig) {\n\t\tcluster, err := g.Provision(cfg.WithOS(param.OSFlavor).\n\t\t\tWithStorageDriver(param.DockerStorageDriver).\n\t\t\tWithNodes(param.ToNodes))\n\t\tg.OK(\"provision nodes\", err)\n\t\tdefer func() {\n\t\t\tg.Maybe(\"destroy\", cluster.Destroy())\n\t\t}()\n\n\t\tg.OK(\"download installer\", g.SetInstaller(cluster.Nodes, cfg.InstallerURL, \"install\"))\n\t\tg.OK(fmt.Sprintf(\"install on %d node\", param.NodeCount),\n\t\t\tg.OfflineInstall(cluster.Nodes[0:param.NodeCount], param.InstallParam))\n\t\tg.OK(\"status\", g.Status(cluster.Nodes[0:param.NodeCount]))\n\t\tg.OK(\"time sync\", g.CheckTimeSync(cluster.Nodes))\n\t\tg.OK(fmt.Sprintf(\"expand to %d nodes\", param.ToNodes),\n\t\t\tg.Expand(cluster.Nodes[0:param.NodeCount], cluster.Nodes[param.NodeCount:param.ToNodes],\n\t\t\t\tparam.InstallParam))\n\t\tg.OK(\"status\", g.Status(cluster.Nodes[0:param.ToNodes]))\n\t}, nil\n}", "func (_DetailedTestToken *DetailedTestTokenSession) RenounceOwnership() (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.RenounceOwnership(&_DetailedTestToken.TransactOpts)\n}", "func TestShrinkStorageFolderIncompleteWriteForce(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\td := new(dependencyIncompleteGrow)\n\tcmt, err := newMockedContractManagerTester(d, \"TestShrinkStorageFolderIncompleteWriteForce\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cmt.panicClose()\n\n\t// Add a storage folder.\n\tstorageFolderOne := filepath.Join(cmt.persistDir, \"storageFolderOne\")\n\t// Create the storage folder dir.\n\terr = os.MkdirAll(storageFolderOne, 0700)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = cmt.cm.AddStorageFolder(storageFolderOne, modules.SectorSize*storageFolderGranularity*8)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Get the index of the storage folder.\n\tsfs := cmt.cm.StorageFolders()\n\tif len(sfs) != 1 {\n\t\tt.Fatal(\"there should only be one storage folder\")\n\t}\n\tsfIndex := sfs[0].Index\n\n\t// Create some sectors and add them to the storage folder.\n\troots := make([]crypto.Hash, 6)\n\tdatas := make([][]byte, 6)\n\tfor i := 0; i < len(roots); i++ {\n\t\troot, data := randSector()\n\t\troots[i] = root\n\t\tdatas[i] = data\n\t}\n\t// Add all of the sectors.\n\tvar wg sync.WaitGroup\n\twg.Add(len(roots))\n\tfor i := 0; i < len(roots); i++ {\n\t\tgo func(i int) {\n\t\t\terr := cmt.cm.AddSector(roots[i], datas[i])\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\t// Add a second storage folder so that the displaced sectors have somewhere\n\t// to go.\n\tstorageFolderTwo := filepath.Join(cmt.persistDir, \"storageFolderTwo\")\n\t// Create the storage folder dir.\n\terr = os.MkdirAll(storageFolderTwo, 0700)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = cmt.cm.AddStorageFolder(storageFolderTwo, modules.SectorSize*storageFolderGranularity*3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Trigger some failures.\n\td.mu.Lock()\n\td.threshold = 1 << 11\n\td.triggered = true\n\td.mu.Unlock()\n\n\t// Decrease the size of the storage folder.\n\terr = cmt.cm.ResizeStorageFolder(sfIndex, modules.SectorSize*storageFolderGranularity*2, true)\n\tif err != nil {\n\t\tt.Fatal(\"expected a failure\")\n\t}\n\t// Verify that the capacity and file sizes are correct.\n\tsfs = cmt.cm.StorageFolders()\n\tcapacity := sfs[0].Capacity + sfs[1].Capacity\n\tcapacityRemaining := sfs[0].CapacityRemaining + sfs[1].CapacityRemaining\n\tif capacity != modules.SectorSize*storageFolderGranularity*5 {\n\t\tt.Error(\"new storage folder is reporting the wrong capacity\")\n\t}\n\tmfn := filepath.Join(storageFolderOne, metadataFile)\n\tsfn := filepath.Join(storageFolderOne, sectorFile)\n\tmfi, err := os.Stat(mfn)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsfi, err := os.Stat(sfn)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif uint64(mfi.Size()) != sectorMetadataDiskSize*storageFolderGranularity*2 {\n\t\tt.Error(\"metadata file is the wrong size\")\n\t}\n\tif uint64(sfi.Size()) != modules.SectorSize*storageFolderGranularity*2 {\n\t\tt.Error(\"sector file is the wrong size\")\n\t}\n\n\t// Data was lost. Count the number of sectors that are still available.\n\twg.Add(len(roots))\n\tvar remainingSectors uint64\n\tfor i := 0; i < len(roots); i++ {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\n\t\t\tdata, err := cmt.cm.ReadSector(roots[i])\n\t\t\tif err != nil {\n\t\t\t\t// Sector probably destroyed.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !bytes.Equal(data, datas[i]) {\n\t\t\t\tt.Error(\"ReadSector has returned the wrong data\")\n\t\t\t}\n\n\t\t\tatomic.AddUint64(&remainingSectors, 1)\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\t// Check that the capacity remaining matches the number of reachable\n\t// sectors.\n\tif capacityRemaining != capacity-remainingSectors*modules.SectorSize {\n\t\tt.Error(capacityRemaining/modules.SectorSize, capacity/modules.SectorSize, remainingSectors)\n\t}\n\n\t// Restart the contract manager to see that the change is persistent.\n\terr = cmt.cm.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcmt.cm, err = New(filepath.Join(cmt.persistDir, modules.ContractManagerDir))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify that the capacity and file sizes are correct.\n\tsfs = cmt.cm.StorageFolders()\n\tcapacity = sfs[0].Capacity + sfs[1].Capacity\n\tcapacityRemaining = sfs[0].CapacityRemaining + sfs[1].CapacityRemaining\n\tif capacity != modules.SectorSize*storageFolderGranularity*5 {\n\t\tt.Error(\"new storage folder is reporting the wrong capacity\")\n\t}\n\tmfi, err = os.Stat(mfn)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsfi, err = os.Stat(sfn)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif uint64(mfi.Size()) != sectorMetadataDiskSize*storageFolderGranularity*2 {\n\t\tt.Error(\"metadata file is the wrong size\")\n\t}\n\tif uint64(sfi.Size()) != modules.SectorSize*storageFolderGranularity*2 {\n\t\tt.Error(\"sector file is the wrong size\")\n\t}\n\n\t// Check that the same number of sectors are still available.\n\twg.Add(len(roots))\n\tvar nowRemainingSectors uint64\n\tfor i := 0; i < len(roots); i++ {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\n\t\t\tdata, err := cmt.cm.ReadSector(roots[i])\n\t\t\tif err != nil {\n\t\t\t\t// Sector probably destroyed.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !bytes.Equal(data, datas[i]) {\n\t\t\t\tt.Error(\"ReadSector has returned the wrong data\")\n\t\t\t}\n\n\t\t\tatomic.AddUint64(&nowRemainingSectors, 1)\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\t// Check that the capacity remaining matches the number of reachable\n\t// sectors.\n\tif capacityRemaining != capacity-remainingSectors*modules.SectorSize {\n\t\tt.Error(capacityRemaining/modules.SectorSize, capacity/modules.SectorSize, remainingSectors)\n\t}\n\tif remainingSectors != nowRemainingSectors {\n\t\tt.Error(\"available sector set changed after restart\", remainingSectors, nowRemainingSectors)\n\t}\n}", "func ExampleNewPerson() {\n\tperson := NewPerson(\"bob\")\n\t_ = person\n}", "func TestDeleteMembers(t *testing.T) {\n\tcalls := []testutils.TestCmd{\n\t\tfakeRestoreSuccessCommand,\n\t}\n\tioshim := common.NewMockIOShim(calls)\n\tdefer ioshim.VerifyCalls(t, calls)\n\tiMgr := NewIPSetManager(applyAlwaysCfg, ioshim)\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"1.1.1.1\", \"a\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"3.3.3.3\", \"c\"))\n\t// create to destroy later\n\tiMgr.CreateIPSets([]*IPSetMetadata{TestCIDRSet.Metadata})\n\t// clear dirty cache, otherwise a set deletion will be a no-op\n\tiMgr.clearDirtyCache()\n\n\t// will remove this member\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"1.1.1.1\", \"a\"))\n\t// will add this member\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"5.5.5.5\", \"e\"))\n\t// won't add/remove this member since the next two calls cancel each other out\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"4.4.4.4\", \"d\"))\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"4.4.4.4\", \"d\"))\n\t// won't add/remove this member since the next two calls cancel each other out\n\trequire.NoError(t, iMgr.RemoveFromSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\trequire.NoError(t, iMgr.AddToSets([]*IPSetMetadata{TestNSSet.Metadata}, \"2.2.2.2\", \"b\"))\n\t// destroy extra set\n\tiMgr.DeleteIPSet(TestCIDRSet.PrefixName, util.SoftDelete)\n\n\texpectedLines := []string{\n\t\tfmt.Sprintf(\"-N %s --exist nethash\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-D %s 1.1.1.1\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-A %s 5.5.5.5\", TestNSSet.HashedName),\n\t\tfmt.Sprintf(\"-F %s\", TestCIDRSet.HashedName),\n\t\tfmt.Sprintf(\"-X %s\", TestCIDRSet.HashedName),\n\t\t\"\",\n\t}\n\tsortedExpectedLines := testAndSortRestoreFileLines(t, expectedLines)\n\tcreator := iMgr.fileCreatorForApply(len(calls))\n\tactualLines := testAndSortRestoreFileString(t, creator.ToString())\n\tdptestutils.AssertEqualLines(t, sortedExpectedLines, actualLines)\n\twasFileAltered, err := creator.RunCommandOnceWithFile(\"ipset\", \"restore\")\n\trequire.NoError(t, err, \"ipset restore should be successful\")\n\trequire.False(t, wasFileAltered, \"file should not be altered\")\n}", "func TestReloadWithReadLock_PartialRegisterFailure(t *testing.T) {\n\trequire := require.New(t)\n\n\tresources := initVMRegistryTest(t)\n\n\tfactory1 := vms.NewMockFactory(resources.ctrl)\n\tfactory2 := vms.NewMockFactory(resources.ctrl)\n\tfactory3 := vms.NewMockFactory(resources.ctrl)\n\tfactory4 := vms.NewMockFactory(resources.ctrl)\n\n\tregisteredVms := map[ids.ID]vms.Factory{\n\t\tid1: factory1,\n\t\tid2: factory2,\n\t}\n\n\tunregisteredVms := map[ids.ID]vms.Factory{\n\t\tid3: factory3,\n\t\tid4: factory4,\n\t}\n\n\tresources.mockVMGetter.EXPECT().\n\t\tGet().\n\t\tTimes(1).\n\t\tReturn(registeredVms, unregisteredVms, nil)\n\tresources.mockVMRegisterer.EXPECT().\n\t\tRegisterWithReadLock(gomock.Any(), id3, factory3).\n\t\tTimes(1).\n\t\tReturn(errTest)\n\tresources.mockVMRegisterer.EXPECT().\n\t\tRegisterWithReadLock(gomock.Any(), id4, factory4).\n\t\tTimes(1).\n\t\tReturn(nil)\n\n\tinstalledVMs, failedVMs, err := resources.vmRegistry.ReloadWithReadLock(context.Background())\n\trequire.NoError(err)\n\trequire.Len(failedVMs, 1)\n\trequire.ErrorIs(failedVMs[id3], errTest)\n\trequire.Len(installedVMs, 1)\n\trequire.Equal(id4, installedVMs[0])\n}", "func (view *ViewPodDemo) DemoRecreate() {\n\n\tpod := view.randomPod()\n\tlog.Printf(\"Random pod: %v\", pod)\n\n\tnpart := strings.Split(pod.Name, \"-\")\n\tnewPrefix := fmt.Sprintf(\"%v-%x\", npart[0], rand.Intn(1<<16))\n\toldPrefix := fmt.Sprintf(\"%v-%v\", npart[0], npart[1])\n\treplicas := 0\n\tvar srcPod *PodDetails\n\n\t// down\n\tfor _, status := range PodStatusSequenceStop {\n\t\tseq := 0\n\t\tfor {\n\t\t\tpodName := fmt.Sprintf(\"%v-%x\", oldPrefix, seq)\n\t\t\toldPod, ok := view.Pods[pod.Namespace+\"/\"+podName]\n\t\t\tif !ok {\n\t\t\t\treplicas = seq\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tsrcPod = oldPod\n\t\t\tview.updateStatus(oldPod, []int{status})\n\t\t\tseq++\n\t\t}\n\t}\n\n\t// up\n\tfor _, status := range PodStatusSequenceStart {\n\t\tfor seq := 0; seq < replicas; seq++ {\n\t\t\tpodName := fmt.Sprintf(\"%v-%x\", newPrefix, seq)\n\t\t\tnewPod, ok := view.Pods[pod.Namespace+\"/\"+podName]\n\t\t\tif !ok {\n\t\t\t\tnewPod = view.RecreatePod(newPrefix, seq, srcPod)\n\t\t\t}\n\t\t\tview.updateStatus(newPod, []int{status})\n\t\t}\n\t}\n\n}", "func Test_VerifyTaxonomyTermPerson_Person1(t *testing.T) {\n\tverifyTaxonomyTermPerson(t, \"taxonomy-person-01.json\", \"Ansel Easton\")\n}", "func (this *PoolTestSuite) TestMutable() {\n\tpool := NewObjectPoolWithDefaultConfig(NewPooledObjectFactorySimple(func() (interface{}, error) {\n\t\treturn make(map[string]string), nil\n\t}))\n\tm1 := this.NoErrorWithResult(pool.BorrowObject()).(map[string]string)\n\tm2 := this.NoErrorWithResult(pool.BorrowObject()).(map[string]string)\n\tm1[\"k1\"] = \"v1\"\n\tm2[\"k2\"] = \"v2\"\n\tthis.NoError(pool.ReturnObject(m1))\n\tthis.NoError(pool.ReturnObject(m2))\n\tthis.Equal(2, pool.GetNumIdle())\n\tpool.Close()\n}" ]
[ "0.75344723", "0.7293638", "0.5497227", "0.54245895", "0.537147", "0.5344091", "0.52745414", "0.5247119", "0.52379155", "0.52360934", "0.5227818", "0.5224537", "0.5212781", "0.51782423", "0.51579493", "0.50936186", "0.5076821", "0.50664246", "0.5051069", "0.50355583", "0.49059185", "0.48629123", "0.4859488", "0.48590544", "0.48514104", "0.48410788", "0.48287198", "0.4808502", "0.47860038", "0.4782645", "0.47811997", "0.47584638", "0.47524208", "0.47524208", "0.4747055", "0.47366354", "0.47293106", "0.4728163", "0.47132385", "0.47126397", "0.47091678", "0.47010708", "0.46888316", "0.46873003", "0.46871802", "0.46857056", "0.46741462", "0.4671925", "0.46694797", "0.46536323", "0.46463603", "0.4645938", "0.46392104", "0.46368903", "0.4633574", "0.4630073", "0.462811", "0.46278188", "0.46230707", "0.462189", "0.46178174", "0.4616933", "0.46106037", "0.459402", "0.45868653", "0.4547455", "0.45434162", "0.45381647", "0.45355797", "0.4521837", "0.4515001", "0.45119348", "0.45100212", "0.45097494", "0.4505038", "0.44951123", "0.44939384", "0.4492728", "0.44864905", "0.44798225", "0.44744536", "0.44660285", "0.4452927", "0.4450353", "0.44417357", "0.44363862", "0.44344518", "0.4432926", "0.44227764", "0.44084796", "0.44067344", "0.44001064", "0.43997273", "0.43848953", "0.4384824", "0.4383175", "0.43816543", "0.43797994", "0.43751615", "0.43749017" ]
0.78842765
0
TestGetRoomDetails tests the functionality of getRoomDetails
func TestGetRoomDetails(t *testing.T) { var ( err error users []models.User rm models.Room room Room getRoomDetails = func(fname, lname, userType, rmName, rmType string) { room, err = CreateRoom(con, rmName, rmType) So(err, ShouldBeNil) So(room.ID, ShouldNotBeBlank) _, err = AddPerson(con, fname, lname, userType, room.Name, "") So(err, ShouldBeNil) rm, users, err = getRoomDetails(con, rmName, rmType) } ) Convey("Tests for getRoomDetails ", t, func() { Convey("getRoomDetaiils should return the room, a slice of user and an error ", func() { getRoomDetails("Daniel", "Ikigai", "fellow", "Tsavoo", "office") So(err, ShouldBeNil) So(rm.Capacity, ShouldEqual, 6) So(rm.ID, ShouldNotBeBlank) So(rm.Name, ShouldEqual, "Tsavoo") So(rm.Type, ShouldEqual, "office") So(users[0].FirstName, ShouldEqual, "Daniel") So(users[0].ID, ShouldNotBeBlank) So(users[0].LastName, ShouldEqual, "Ikigai") So(users[0].Type, ShouldEqual, "fellow") }) Convey("Print the successfully created Room and User", func() { getRoomDetails("Christine", "J", "fellow", "Tsavoo", "office") So(err, ShouldBeNil) printRooms() printUsers() So(con.DestroyData(), ShouldBeNil) }) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestGetRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\troom = Room{}\n\n\t\t\troom, err = GetRoom(con, rmName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoom \", t, func() {\n\t\tConvey(\"GetRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Joshua\", \"Mwaniki\", \"staff\", \"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldEqual, \"Valhalla\")\n\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Joshua\")\n\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Mwaniki\")\n\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"staff\")\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"James\", \"Kaberia\", \"staff\", \"Pretoria\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestGetRoomAllocations(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser User\n\t\troom Room\n\t\trooms []Room\n\n\t\tfetchRoom = func(fname, lname, userType, rmName, rmType string) {\n\t\t\troom, err = CreateRoom(con, rmName, rmType)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, userType, room.Name, \"\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user, ShouldNotResemble, (User{}))\n\n\t\t\trooms, err = GetRoomAllocations(con)\n\t\t}\n\t)\n\n\tConvey(\"Tests for GetRoomAllocations \", t, func() {\n\t\tConvey(\"GetRoomAllocations should return a slice of Room with all the correct values present and an error\", func() {\n\t\t\tfetchRoom(\"Garbrielle\", \"Wanjigi\", \"fellow\", \"Timbuktu\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tfor _, room = range rooms {\n\n\t\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Name, ShouldEqual, \"Timbuktu\")\n\t\t\t\tSo(room.Occupants, ShouldNotBeEmpty)\n\t\t\t\tSo(room.Type, ShouldNotBeBlank)\n\n\t\t\t\tSo(room.Occupants[0].FirstName, ShouldEqual, \"Garbrielle\")\n\t\t\t\tSo(room.Occupants[0].ID, ShouldNotBeBlank)\n\t\t\t\tSo(room.Occupants[0].LastName, ShouldEqual, \"Wanjigi\")\n\t\t\t\tSo(room.Occupants[0].Type, ShouldEqual, \"fellow\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tfetchRoom(\"Ashley\", \"Wanjigi\", \"fellow\", \"Golang\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func printRoomDetails(room controllers.Room) {\n\tfmt.Println()\n\tfmt.Println(\"Room Details\")\n\tfmt.Println(\"=====================\")\n\tfmt.Println(\"Capacity :\", room.Capacity)\n\tfmt.Println(\"ID :\", room.ID)\n\tfmt.Println(\"Name :\", room.Name)\n\tfmt.Println(\"Type :\", room.Type)\n\tfmt.Println(\"Occupants -\")\n\tfor index, user := range room.Occupants {\n\t\tfmt.Println(\"\\tCount :\", index+1)\n\t\tfmt.Println(\"\\tFirstName :\", user.FirstName)\n\t\tfmt.Println(\"\\tID :\", user.ID)\n\t\tfmt.Println(\"\\tLastName\", user.LastName)\n\t\tfmt.Println(\"\\tType :\", user.Type)\n\t\tfmt.Println()\n\t}\n\tfmt.Println(\"=====================\")\n\tfmt.Println()\n\n}", "func roomToTestRoom(room *level.RoomData, inputLevel level.Level) Room {\n\treturn Room{\n\t\tType: \"room\",\n\t\tOrigin: Point{\n\t\t\troom.TopLeft.Row,\n\t\t\troom.TopLeft.Col,\n\t\t},\n\t\tBounds: Bounds{\n\t\t\tRows: room.Size.Row,\n\t\t\tColumns: room.Size.Col,\n\t\t},\n\t\tLayout: TilesToArray(inputLevel.GetTiles(room.TopLeft, room.Size)),\n\t}\n}", "func TestCreateRoom(t *testing.T) {\n\tvar (\n\t\terr error\n\t\troom Room\n\n\t\tcreateRoom = func(name, roomType string) {\n\t\t\troom, err = CreateRoom(con, name, roomType)\n\t\t}\n\t)\n\n\tConvey(\"Tests for CreateRoom \", t, func() {\n\t\tConvey(\"CreateRoom should return Room with all the correct values present and an error\", func() {\n\t\t\tcreateRoom(\"Valhalla\", \"office\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(room.Capacity, ShouldEqual, 6)\n\t\t\tSo(room.ID, ShouldNotBeBlank)\n\t\t\tSo(room.Name, ShouldNotBeBlank)\n\t\t\tSo(room.Occupants, ShouldBeEmpty)\n\t\t\tSo(room.Type, ShouldNotBeBlank)\n\t\t})\n\n\t\tConvey(\"Print the successfully created Room and User\", func() {\n\t\t\tcreateRoom(\"Golang\", \"livingspace\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func (c *Client) GetRoom(ctx context.Context, name string) (*GetRoomResponse, error) {\n\tresp := &GetRoomResponse{}\n\treturn resp, c.request(ctx, \"GET\", \"rooms/\"+name, nil, resp)\n}", "func GetRoom(c *gin.Context) {\n\tsession := sessions.Default(c)\n\tcUser := m.CurrentUser(session.Get(\"uid\").(int))\n\tdomain := m.GetDomain()\n\troomID, _ := strconv.Atoi(c.Param(\"roomID\"))\n\troom := m.GetRoom(roomID)\n\twToken := m.GetWatsonToken()\n\tjoinedFlg := cUser.IsJoin(roomID)\n\n\t// Flash Message\n\tvar joinRoomMessage interface{}\n\tif f := session.Flashes(\"JoinRoom\"); len(f) != 0 {\n\t\tjoinRoomMessage = f[0]\n\t}\n\tc.HTML(http.StatusOK, \"room.tmpl\", gin.H{\n\t\t\"CurrentUser\": cUser,\n\t\t\"Domain\": domain,\n\t\t\"Room\": room,\n\t\t\"WatsonToken\": wToken,\n\t\t\"JoinedFlg\": joinedFlg,\n\t\t\"JoinRoomMessage\": joinRoomMessage,\n\t})\n}", "func TestAddRoom(t *testing.T) {\n\t// first create a new controller\n\tapi := NewRoomApiController()\n\troomrouter := NewRouter(api)\n\ttestserver := httptest.NewServer(roomrouter)\n\tdefer testserver.Close()\n\n\t// api configuration\n\tapiConfig := roomapi.NewConfiguration()\n\tapiConfig.HTTPClient = testserver.Client()\n\ttesturl, err := url.Parse(testserver.URL)\n\tif err != nil {\n\t\tt.Errorf(\"error parsing url from test server: %s\", err)\n\t\treturn\n\t}\n\tapiConfig.Host = testurl.Host\n\n\t// create first client\n\tapic := roomapi.NewAPIClient(apiConfig)\n\tbackground := context.Background()\n\tretRoom, _, err := apic.RoomApi.AddRoom(background)\n\tif err != nil {\n\t\tt.Errorf(\"error adding room: %s\", err)\n\t\treturn\n\t}\n\tt.Logf(\"room id: %d, room id str: %s\\n\", retRoom.Id, retRoom.Code)\n}", "func (c *RoomdetailClient) Get(ctx context.Context, id int) (*Roomdetail, error) {\n\treturn c.Query().Where(roomdetail.ID(id)).Only(ctx)\n}", "func (c *PetruleClient) QueryRoomdetails(pe *Petrule) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := pe.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(petrule.Table, petrule.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, petrule.RoomdetailsTable, petrule.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(pe.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (c *Mock) Room() interfaces.Room {\n\treturn c.FakeRoom()\n}", "func (cl *RestClient) Get(room string) {\n\tresp, err := restGet(room, cl.client, cl.ip, cl.port)\n\tif err != nil {\n\t\tcl.test.Errorf(\"Error with restGet: %v\", err)\n\t}\n\tif resp.StatusCode == 404 { //room not found\n\t\tcl.messages = append(cl.messages, \"Room not Found\")\n\t\tcl.res.RestGet(room)\n\t\treturn\n\t}\n\tif resp.StatusCode != 200 {\n\t\tcl.test.Errorf(\"Rest Get got %v want 200\", resp.StatusCode)\n\t}\n\tdec := json.NewDecoder(resp.Body)\n\tvar messages []string\n\terr = dec.Decode(&messages)\n\tif err != nil {\n\t\tcl.test.Errorf(\"Error decoding in Rest Get: %v\", err)\n\t}\n\tresp.Body.Close()\n\tfor _, mg := range messages {\n\t\tcl.messages = append(cl.messages, mg)\n\t}\n\tcl.res.RestGet(room)\n}", "func GetRoom(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\tvar permission permissionRoom\n\terr := DB.QueryRowx(`\n\t\tSELECT permissions.*, users.*,\n\t\trooms.id as r_id,\trooms.name AS r_name, rooms.home_id AS r_homeid, rooms.created_at AS r_createdat, rooms.updated_at AS r_updatedat FROM permissions\n\t\tJOIN rooms ON permissions.type_id = rooms.id\n\t\tJOIN users ON rooms.creator_id = users.id\n\t\tWHERE permissions.type=$1 AND permissions.type_id=$2 AND permissions.user_id=$3\n\t`, \"room\", c.Param(\"roomId\"), user.ID).StructScan(&permission)\n\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGR001\"}).Errorf(\"QueryRowx: Select error\")\n\t\treturn c.JSON(http.StatusNotFound, ErrorResponse{\n\t\t\tCode: \"CSRGR001\",\n\t\t\tMessage: \"Room can't be found\",\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusOK, roomRes{\n\t\tID: permission.RoomID,\n\t\tName: permission.RoomName,\n\t\tHomeID: permission.RoomHomeID,\n\t\tCreatedAt: permission.RoomCreatedAt,\n\t\tUpdatedAt: permission.RoomUpdatedAt,\n\t\tCreator: permission.User,\n\t\tRead: permission.Permission.Read,\n\t\tWrite: permission.Permission.Write,\n\t\tManage: permission.Permission.Manage,\n\t\tAdmin: permission.Permission.Admin,\n\t})\n}", "func (s *rpcServer) GetRoomInfo(ctx context.Context, in *pb.GetRoomInfoData) (*pb.GetRoomInfoRes, error) {\n\tlogPrefix := \"rpcServer GetRoomInfo\"\n\tlogger := s.nex.GetLogger()\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlogger.LogFile(nxLog.LevelPanic, fmt.Sprintf(\"%s panic:%v\\n\", logPrefix, r))\n\t\t}\n\t}()\n\n\trm := s.nex.GetRoomManager()\n\tr, ok := rm.GetRoom(int(in.RoomID))\n\tif !ok {\n\t\tlogger.LogFile(nxLog.LevelError, fmt.Sprintf(\"%s roomID not found :%d\", logPrefix, int(in.RoomID)))\n\t\treturn nil, errors.New(\"rpcServer GetRoomInfo roomID not found\")\n\t}\n\n\tbrData := s.roomCtrl.GetBootRoundBetMinBetMax(r)\n\tif brData.Err != nil {\n\t\t//error\n\t\treturn nil, brData.Err\n\t}\n\n\t//Get typeData by room type\n\treturn &pb.GetRoomInfoRes{\n\t\tBoot: int64(brData.Boot),\n\t\tRound: brData.Round,\n\t\tRoomID: int64(r.ID()),\n\t\tRoomName: r.Name(),\n\t\tBankerPlayerMin: int64(brData.BetMin),\n\t\tBankerPlayerPairMax: int64(brData.BetMax),\n\t\tTieMin: int64(brData.BetMin),\n\t\tTieMax: int64(brData.BetMax),\n\t\tBankerPlayerPairMin: int64(brData.BetMin),\n\t\tBankerPlayerMax: int64(brData.BetMax),\n\t\tOnline: 999,\n\t\tBetCountDown: 20,\n\t}, nil\n}", "func (r Virtual_Guest) GetServerRoom() (resp datatypes.Location, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getServerRoom\", nil, &r.Options, &resp)\n\treturn\n}", "func (a *RoomHandler) GetRoomList(c echo.Context) error {\n\tsortParam := c.QueryParam(\"sort_by\")\n\torderParam := c.QueryParam(\"order_by\")\n\n\tsortField := formSortField(sortParam)\n\tif sortField == usecase.ErrField {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"sort_by field must be price or date_added\"}, \" \")\n\t}\n\n\tsortOrder := formSortOrder(orderParam)\n\tif sortOrder == usecase.ErrOrder {\n\t\treturn c.JSONPretty(http.StatusBadRequest, ResponseError{Message: \"order_by field must be asc or desc\"}, \" \")\n\t}\n\n\trooms, err := a.RoomUsecase.GetList(sortField, sortOrder)\n\tif err != nil {\n\t\treturn c.JSONPretty(getStatusCode(err), ResponseError{Message: err.Error()}, \" \")\n\t}\n\n\treturn c.JSONPretty(http.StatusOK, rooms, \" \")\n}", "func (m *MockBooking) GetByRoomId(arg0 int) ([]*model.Booking, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetByRoomId\", arg0)\n\tret0, _ := ret[0].([]*model.Booking)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *PledgeClient) QueryRoomdetails(pl *Pledge) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := pl.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(pledge.Table, pledge.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, pledge.RoomdetailsTable, pledge.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(pl.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func getRooms(api *slack.Client) map[string]string {\n\trooms := make(map[string]string)\n\t// get public channels\n\tchannels, _ := api.GetChannels(true)\n\tfor _, channel := range channels {\n\t\trooms[channel.Name] = channel.ID\n\t}\n\t// get private channels\n\tgroups, _ := api.GetGroups(true)\n\tfor _, group := range groups {\n\t\trooms[group.Name] = group.ID\n\t}\n\treturn rooms\n}", "func (c *EmployeeClient) QueryRoomdetails(e *Employee) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := e.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(employee.Table, employee.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, employee.RoomdetailsTable, employee.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(e.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func printRoom(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.GetRoom(con, args.Get(0))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func (c *StaytypeClient) QueryRoomdetails(s *Staytype) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := s.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(staytype.Table, staytype.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, staytype.RoomdetailsTable, staytype.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(s.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (m *MockIRoomService) SGetAllRoom() ([]models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SGetAllRoom\")\n\tret0, _ := ret[0].([]models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetRoom(id int64) (*Room, bool) {\n\n\troom, ok := hotel[id]\n\treturn room, ok\n}", "func TestGetPartnersWorking(t *testing.T) {\n\tclearTable()\n\tinsertGame()\n\tapitest.New().\n\t\tDebug().\n\t\tHandler(newApp().Router).\n\t\tGet(\"/api/assoc_partners\").\n\t\tExpect(t).\n\t\tStatus(http.StatusOK).\n\t\tEnd()\n}", "func (d *Dispatcher) GetRoom(ctx context.Context, roomUID string) *entity.Room {\n\troom := d.rms.GetRoom(roomUID)\n\tif room == nil {\n\t\treturn nil\n\t}\n\treturn room\n}", "func (c *BedtypeClient) QueryRoomdetails(b *Bedtype) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := b.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(bedtype.Table, bedtype.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, bedtype.RoomdetailsTable, bedtype.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(b.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (c *JobpositionClient) QueryRoomdetails(j *Jobposition) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := j.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(jobposition.Table, jobposition.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, jobposition.RoomdetailsTable, jobposition.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(j.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (r *RoomService) Get(ctx context.Context, sidOrUniqueName string) (*Room, error) {\n\troom := new(Room)\n\terr := r.client.GetResource(ctx, roomPathPart, sidOrUniqueName, room)\n\treturn room, err\n}", "func FakeRoom() *RoomModel {\n\treturn &RoomModel{\n\t\tID: faker.RandomString(5),\n\t\tName: faker.Commerce().ProductName(),\n\t\tPhoto: faker.Avatar().String(),\n\t\tDescription: faker.Lorem().Sentence(5),\n\t}\n}", "func GetRooms(c echo.Context) error {\n\tuser := c.Get(\"user\").(User)\n\n\trows, err := DB.Queryx(`\n\t\tSELECT permissions.*, users.*,\n\t\trooms.id as r_id,\trooms.name AS r_name, rooms.home_id AS r_homeid, rooms.created_at AS r_createdat, rooms.updated_at AS r_updatedat FROM permissions\n\t\tJOIN rooms ON permissions.type_id = rooms.id\n\t\tJOIN users ON rooms.creator_id = users.id\n\t\tWHERE permissions.type=$1 AND permissions.user_id=$2 AND rooms.home_id=$3 AND (permissions.read=true OR permissions.admin=true)\n\t`, \"room\", user.ID, c.Param(\"homeId\"))\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS001\"}).Errorf(\"%s\", err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\tCode: \"CSRGRS001\",\n\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t})\n\t}\n\tdefer rows.Close()\n\n\trooms := []roomRes{}\n\tfor rows.Next() {\n\t\tvar permission permissionRoom\n\t\terr := rows.StructScan(&permission)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CSRGRS002\"}).Errorf(\"%s\", err.Error())\n\t\t\treturn c.JSON(http.StatusInternalServerError, ErrorResponse{\n\t\t\t\tCode: \"CSRGRS002\",\n\t\t\t\tMessage: \"Rooms can't be retrieved\",\n\t\t\t})\n\t\t}\n\n\t\trooms = append(rooms, roomRes{\n\t\t\tID: permission.RoomID,\n\t\t\tName: permission.RoomName,\n\t\t\tHomeID: permission.RoomHomeID,\n\t\t\tCreatedAt: permission.RoomCreatedAt,\n\t\t\tUpdatedAt: permission.RoomUpdatedAt,\n\t\t\tCreator: permission.User,\n\t\t\tRead: permission.Permission.Read,\n\t\t\tWrite: permission.Permission.Write,\n\t\t\tManage: permission.Permission.Manage,\n\t\t\tAdmin: permission.Permission.Admin,\n\t\t})\n\t}\n\n\ttotalRooms := strconv.Itoa(len(rooms))\n\tc.Response().Header().Set(\"Content-Range\", \"0-\"+totalRooms+\"/\"+totalRooms)\n\treturn c.JSON(http.StatusOK, rooms)\n}", "func (s *RoomsNightService) Room(ctx context.Context, id int) (*NightRoomResponsePayload, *Response, error) {\n\treq, err := s.NewRequest(id)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpayload := &NightRoomResponsePayload{}\n\tresp, err := s.client.Do(ctx, req, payload)\n\n\treturn payload, resp, nil\n}", "func getRoomMock(cfg roomMockConfig) roomMock {\n\tvar conf config.WorkerConfig\n\tif _, err := config.LoadConfig(&conf, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tconf.Worker.Library.BasePath = cfg.gamesPath\n\n\tfixEmulators(&conf, cfg.autoGlContext)\n\tl := logger.NewConsole(conf.Worker.Debug, \"w\", false)\n\tif cfg.noLog {\n\t\tlogger.SetGlobalLevel(logger.Disabled)\n\t}\n\n\t// sync cores\n\tif err := remotehttp.CheckCores(conf.Emulator, l); err != nil {\n\t\tl.Error().Err(err).Msg(\"cores sync error\")\n\t}\n\tconf.Encoder.Video.Codec = string(cfg.vCodec)\n\n\troom := NewRoom(cfg.roomName, cfg.game, nil, conf, l)\n\n\tif !cfg.dontStartEmulator {\n\t\troom.StartEmulator()\n\t}\n\n\t// loop-wait the room initialization\n\tvar init sync.WaitGroup\n\tinit.Add(1)\n\twasted := 0\n\tgo func() {\n\t\tsleepDeltaMs := 10\n\t\tfor room.emulator == nil {\n\t\t\ttime.Sleep(time.Duration(sleepDeltaMs) * time.Millisecond)\n\t\t\twasted++\n\t\t\tif wasted > 1000 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tinit.Done()\n\t}()\n\tinit.Wait()\n\treturn roomMock{Room: room, startEmulator: !cfg.dontStartEmulator}\n}", "func (n *mockAgent) getGuestDetails(*grpc.GuestDetailsRequest) (*grpc.GuestDetailsResponse, error) {\n\treturn nil, nil\n}", "func getProgrammingsTest(e *httpexpect.Expect, t *testing.T) {\n\ttestCases := []testCase{\n\t\tnotLoggedTestCase,\n\t\t{\n\t\t\tToken: testCtx.Admin.Token,\n\t\t\tParam: \"2018\",\n\t\t\tStatus: http.StatusOK,\n\t\t\tBodyContains: []string{\"Programmings\", `\"PrevCommitmentTotal\":96730644861`},\n\t\t\tCountItemName: `\"id\"`,\n\t\t\tArraySize: 626},\n\t}\n\tf := func(tc testCase) *httpexpect.Response {\n\t\treturn e.GET(\"/api/programmings\").WithHeader(\"Authorization\", \"Bearer \"+tc.Token).\n\t\t\tWithQuery(\"year\", tc.Param).Expect()\n\t}\n\tfor _, r := range chkTestCases(testCases, f, \"GetProgrammings\") {\n\t\tt.Error(r)\n\t}\n}", "func (c *LeaseClient) QueryRoomdetail(l *Lease) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := l.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(lease.Table, lease.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2O, true, lease.RoomdetailTable, lease.RoomdetailColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(l.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (c *RoomdetailClient) QueryRoomdetails(r *Roomdetail) *LeaseQuery {\n\tquery := &LeaseQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := r.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(roomdetail.Table, roomdetail.FieldID, id),\n\t\t\tsqlgraph.To(lease.Table, lease.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2O, false, roomdetail.RoomdetailsTable, roomdetail.RoomdetailsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(r.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (c *CleaningroomClient) QueryRoomdetail(cl *Cleaningroom) *RoomdetailQuery {\n\tquery := &RoomdetailQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := cl.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(cleaningroom.Table, cleaningroom.FieldID, id),\n\t\t\tsqlgraph.To(roomdetail.Table, roomdetail.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.M2O, true, cleaningroom.RoomdetailTable, cleaningroom.RoomdetailColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(cl.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (m *MockIRoomService) SGetRoomByID(arg0 string) (models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SGetRoomByID\", arg0)\n\tret0, _ := ret[0].(models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func getRoom(id proto.RID) *room {\n\troomLock.RLock()\n\tdefer roomLock.RUnlock()\n\tr := rooms[id]\n\treturn r\n}", "func NewRoomdetailClient(c config) *RoomdetailClient {\n\treturn &RoomdetailClient{config: c}\n}", "func (m *PrinterLocation) GetRoomDescription()(*string) {\n val, err := m.GetBackingStore().Get(\"roomDescription\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (c *RoomClient) Get(ctx context.Context, id int) (*Room, error) {\n\treturn c.Query().Where(room.ID(id)).Only(ctx)\n}", "func (c *RoomClient) Get(ctx context.Context, id int) (*Room, error) {\n\treturn c.Query().Where(room.ID(id)).Only(ctx)\n}", "func (m *PlacesRequestBuilder) Room()(*ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.RoomRequestBuilder) {\n return ied3560dba7640bac9d9d8075828556e424213b7810da04eab3db0272bbb513d6.NewRoomRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestViewBookings(t *testing.T) {\n\ttestRouter := SetupRouter()\n\n\treq, err := http.NewRequest(\"GET\", \"/getBookings/1\", nil)\n\treq.SetBasicAuth(\"admin\", \"admin123\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\ttestRouter.ServeHTTP(resp, req)\n\tassert.Equal(t, resp.Code, 200)\n}", "func TestGetRouters(t *testing.T) {\n\trecord(t, \"getrouters\", func(t *testing.T, svc *Service) {\n\t\trouters, err := svc.GetRouters()\n\t\trequire.NoError(t, err)\n\n\t\tassert.Greater(t, len(routers.Routers), 0)\n\t\tassert.Greater(t, len(routers.Routers[0].AttachedNetworks), 0)\n\n\t\trouter, err := svc.GetRouterDetails(&request.GetRouterDetailsRequest{\n\t\t\tUUID: routers.Routers[0].UUID,\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, &(routers.Routers[0]), router)\n\t})\n}", "func (c *ExaminationroomClient) Get(ctx context.Context, id int) (*Examinationroom, error) {\n\treturn c.Query().Where(examinationroom.ID(id)).Only(ctx)\n}", "func NewTestRoom(name string) *Room {\n\treturn NewRoom(nil, name, name, \"\")\n}", "func TestNewBooking(t *testing.T) {\n\ttestRouter := SetupRouter()\n\tvar jsonStr = []byte(`{\"userid\":1,\"pickuplat\":11.0797,\"pickuplong\":76.9997,\"destinationlat\":11.0797,\"destinationlong\":76.9997\n\t}`)\n\treq, err := http.NewRequest(\"POST\", \"/newBooking\", bytes.NewBuffer(jsonStr))\n\treq.SetBasicAuth(\"admin\", \"admin123\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\ttestRouter.ServeHTTP(resp, req)\n\tassert.Equal(t, resp.Code, 200)\n}", "func GetRoomDataById(id int) (ResultRoomData, bool) {\n\to := orm.NewOrm()\n\tqb, _ := orm.NewQueryBuilder(\"mysql\")\n\n\tsql := qb.Select(\"rooms.*\").From(\"rooms\").\n\t\tWhere(\"room_id = \" + fmt.Sprint(id)).\n\t\tAnd(\"deleted_at = \" + strconv.Itoa(conf.NOT_DELETED))\n\n\tvar tmpRooms []ResultRoomData\n\tnum, tmpErr := o.Raw(sql.String()).QueryRows(&tmpRooms)\n\tif num > 0 && tmpErr == nil {\n\t\treturn tmpRooms[0], false\n\t}\n\treturn ResultRoomData{}, true\n}", "func (aec *AddEntryCmd) RequiresRoom() {}", "func TestEmployeeManagerMapGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tr = httptest.NewRequest(\"GET\", \"http://localhost:9090/api/v1/emplymgrmap/Nick?supervisor=true&name=Nick\", nil)\n\trctx := chi.NewRouteContext()\n\trctx.URLParams.Add(\"name\", \"Nick\")\n\tr = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetByID(w, r)\n\texpectedResponse := `{\"supervisor\":\"Sophie\",\"supervisor_of_supervisor\":\"Jonas\"}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func TestMockEntryDetail(t *testing.T) {\n\ttestMockEntryDetail(t)\n}", "func GetRoomsCondition(query map[string]string) (result Rooms, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(Rooms))\n\tqs = RebuildConditions(qs, query)\n\tvar room []Rooms\n\tvar roomId int64\n\tif roomId, err = qs.All(&room); err == nil && roomId > 0 {\n\t\tresult = room[0]\n\t\treturn result, nil\n\t}\n\treturn result, err\n}", "func GetRoomByRoomID(storage storage.Storage) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar room *models.Room\n\t\tvar roomID string\n\t\tvar err error\n\n\t\tif roomID = c.Param(\"roomid\"); roomID == \"\" {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\t\"error\": \"roomid required\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tif room, err = storage.GetRoomByRoomID(roomID); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, room)\n\t}\n}", "func (c *PatientroomClient) Get(ctx context.Context, id int) (*Patientroom, error) {\n\treturn c.Query().Where(patientroom.ID(id)).Only(ctx)\n}", "func (c *Client) ShowRoom(ctx context.Context, path string) (*http.Response, error) {\n\treq, err := c.NewShowRoomRequest(ctx, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Client.Do(ctx, req)\n}", "func TestGet_Unit(t *testing.T) {\n\n\tvar dr Router\n\tdr = &MockedResources{}\n\n\tvar vs Router\n\tvs = &MockedResources{}\n\n\tvar op Operator\n\top = &Istiops{\n\t\tDrRouter: dr,\n\t\tVsRouter: vs,\n\t}\n\n\tirl, err := op.Get(map[string]string{})\n\tassert.Equal(t, router.IstioRouteList{\n\t\tVList: &v1alpha3.VirtualServiceList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.VirtualService{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t\tDList: &v1alpha3.DestinationRuleList{\n\t\t\tTypeMeta: v1.TypeMeta{},\n\t\t\tListMeta: v1.ListMeta{},\n\t\t\tItems: []v1alpha3.DestinationRule{\n\t\t\t\t{},\n\t\t\t},\n\t\t},\n\t}, irl)\n\tassert.NoError(t, err)\n}", "func (m *postgresDBRepo) GetRoomById(id int) (models.Room, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tvar room models.Room\n\tquery := `select id, room_name, created_at, updated_at from rooms where id = $1`\n\n\trow := m.DB.QueryRowContext(ctx, query, id)\n\terr := row.Scan(&room.ID, &room.RoomName, &room.CreatedAt, &room.UpdatedAt)\n\tif err != nil {\n\t\treturn room, err\n\t}\n\n\treturn room, nil\n}", "func createRoom(c *cli.Context) error {\n\tvar (\n\t\targs = c.Args()\n\t\troom, err = controllers.CreateRoom(con, args.Get(0), args.Get(1))\n\t)\n\n\texitOnError(err)\n\n\tprintRoomDetails(room)\n\n\treturn nil\n}", "func (m *MockIRoomService) SCreateRoom(arg0 models.RoomModel) (models.RoomModel, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SCreateRoom\", arg0)\n\tret0, _ := ret[0].(models.RoomModel)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetDevicesByRoom(buildingName string, roomName string) (toReturn []accessors.Device, err error) {\n\terr = GetData(os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\")+\"/buildings/\"+buildingName+\"/rooms/\"+roomName+\"/devices\", &toReturn)\n\treturn\n}", "func TestGetVehicle(t *testing.T) {\n\tsetUp(t)\n\tdefer tearDown()\n\n\t// Expect DB FindVehicle\n\tvehicle := model.Vehicle{Vin: \"vin1\", EngineType: \"Combustion\", EvData: nil}\n\tmockVehicleDAO.EXPECT().FindVehicle(gomock.Eq(\"vin1\")).Return(&vehicle, nil)\n\n\t// Send GET request\n\treq, err := http.NewRequest(\"GET\", \"/vehicle?vin=vin1\", nil)\n\trequire.NoError(t, err)\n\trr := httptest.NewRecorder()\n\thandlers.GetVehicle(rr, req)\n\n\t// Check code\n\trequire.Equal(t, 200, rr.Code)\n\n\t// Check body\n\tvar responseVehicle model.Vehicle\n\terr = helpers.DecodeJSONBody(rr.Body, &responseVehicle)\n\trequire.NoError(t, err)\n\trequire.Equal(t, vehicle, responseVehicle)\n}", "func GetRoomsByBuilding(building string) ([]accessors.Room, error) {\n\n\tlog.Printf(\"dbo.GetRoomsByBuilding called\")\n\n\tlog.Printf(\"getting all rooms from %v ...\", building)\n\turl := os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\") + \"/buildings/\" + building + \"/rooms\"\n\tvar rooms []accessors.Room\n\terr := GetData(url, &rooms)\n\treturn rooms, err\n}", "func TestApiGET(t *testing.T) {\n var response getResponse\n statusCode, err := Get(\"http://dummy.restapiexample.com/api/v1/employees\", &response)\n if err != nil {\n t.Errorf(\"Got err %v while trying rest.Get():\", err)\n return\n }\n if statusCode != 200 {\n t.Errorf(\"Expected status code 200, got %d instead\", statusCode)\n return\n }\n if response.Status != \"success\" {\n t.Errorf(\"Expected response.Status to be success, got %v instead\", response.Status)\n }\n if response.Data[0].Id != \"1\" {\n t.Errorf(\"Expected response.Data[0].Id to be 1, got %s instead\", response.Data[0].Id)\n }\n}", "func CreateRoom(w http.ResponseWriter, request *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tswitch request.Method {\n\tcase \"POST\":\n\t\tdata := request.URL.Query()\n\t\tif !createRoomValidator(w, data) {\n\t\t\treturn\n\t\t}\n\t\tvar room roomJSON\n\t\tmaxUsers, _ := strconv.Atoi(data[\"users\"][0])\n\t\ti := 0\n\t\tfor {\n\t\t\ti++\n\t\t\troomID := rand.Intn(99) + 1\n\t\t\tif ok, _ := getRoomByID(roomID, &Rooms); !ok {\n\t\t\t\troom.ID = roomID\n\t\t\t\troom.MaxUsers = maxUsers\n\t\t\t\troom.State = \"joining\"\n\t\t\t\troom.Daytime = \"day\"\n\t\t\t\troom.Mafia = make([]int, 0)\n\t\t\t\troom.Peaceful = make([]int, 0)\n\t\t\t\troom.Alive = make([]int, 0)\n\t\t\t\troom.Killed = make([]int, 0)\n\t\t\t\troom.Jailed = make([]int, 0)\n\t\t\t\tRooms = append(Rooms, room)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif i >= 100 {\n\t\t\t\thttp.Error(w, \"503 Game is not available\", http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tresp, err := json.Marshal(&room)\n\t\tif err == nil {\n\t\t\tw.Write(resp)\n\t\t}\n\t\treturn\n\tdefault:\n\t\tw.WriteHeader(405)\n\t\tfmt.Fprintf(w, \"Only POST method is allowed\")\n\t}\n}", "func (s *BBRequestTestSuite) TestGetPatient() {\n\tp, err := s.bbClient.GetPatient(\"012345\", \"543210\", \"A0000\", \"\", now)\n\tassert.Nil(s.T(), err)\n\tassert.Equal(s.T(), 1, len(p.Entries))\n\tassert.Equal(s.T(), \"20000000000001\", p.Entries[0][\"resource\"].(map[string]interface{})[\"id\"])\n}", "func (o *GetRoomsParams) WithTimeout(timeout time.Duration) *GetRoomsParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func TestRead(t *testing.T) {\r\n\tpersonsFiltered, err := Read(client, firstname)\r\n\tif err != nil {\r\n\t\tt.Fatalf(\"Failed read test :%s\", err)\r\n\t}\r\n\r\n\tfor _, value := range *personsFiltered {\r\n\t\tif value.ID == _id {\r\n\t\t\tt.Log(\"person exists :\", value.ID)\r\n\t\t\tbreak\r\n\t\t} else {\r\n\t\t\tt.Fatalf(\"Failed read test. \")\r\n\t\t}\r\n\t}\r\n}", "func TestReadTaskAPI(t *testing.T) {\n\n\ttask, err := NewTask(\"test read task api\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error : %v\", err)\n\t}\n\tif err := task.Save(); err != nil {\n\t\tt.Fatalf(\"unexpected error : %v\", err)\n\t}\n\n\tm := mux.NewRouter()\n\tm.HandleFunc(\"/task/{query}\", ReadTaskAPI)\n\n\trr := httptest.NewRecorder()\n\treq, _ := http.NewRequest(http.MethodGet, \"/task/\"+task.SID, strings.NewReader(\"\"))\n\n\tm.ServeHTTP(rr, req)\n\n\t// Test status code.\n\tif rr.Code != http.StatusOK {\n\t\tt.Errorf(\"Code : %v, Error : %v\", rr.Code, rr.Body.String())\n\t}\n\n\t// Test the result data.\n\tfind := new(Task)\n\tif err := jsonapi.UnmarshalPayload(rr.Body, find); err != nil {\n\t\tt.Errorf(\"unexpected error (%v)\", err)\n\t}\n\n\tif find.SID != task.SID {\n\t\tt.Errorf(\"expected task '%v', got '%v'\", task.SID, find.SID)\n\t}\n}", "func testGetExamList(t *testing.T) {\n\tid := uint(1)\n\texamList, err := MainService.GetExamList(id)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif examList != nil {\n\t\tif examList.ID != id {\n\t\t\tt.Errorf(\"There is an error, the id should be %d but got %d\",\n\t\t\t\tid, examList.ID)\n\t\t}\n\n\t\tif len(examList.StudentsExams) != len(students) {\n\t\t\tt.Errorf(\"There is an error, the length should be %d but got %d\",\n\t\t\t\tlen(students), len(examList.StudentsExams))\n\t\t}\n\t}\n}", "func (client *Client) Room() *Room {\n\treturn client.room\n}", "func TestAddPerson(t *testing.T) {\n\tvar (\n\t\terr error\n\t\tuser, testUser User\n\n\t\taddPerson = func(fname, lname, jobType, officeName, livingspaceName string) {\n\t\t\tif livingspaceName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, livingspaceName, \"livingspace\")\n\t\t\t}\n\n\t\t\tif officeName != \"\" {\n\t\t\t\t_, err = CreateRoom(con, officeName, \"office\")\n\t\t\t}\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tuser, err = AddPerson(con, fname, lname, jobType, officeName, livingspaceName)\n\t\t}\n\t)\n\n\tConvey(\"Tests for AddPerson\", t, func() {\n\t\tConvey(\"AddPerson should return a User with all correct values present and an error\", func() {\n\t\t\tvar runValuesTests = func(rm models.Room) {\n\t\t\t\tSo(rm.Capacity, ShouldNotEqual, 0)\n\t\t\t\tSo(rm.ID, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Name, ShouldNotBeBlank)\n\t\t\t\tSo(rm.Type, ShouldNotBeBlank)\n\t\t\t}\n\n\t\t\taddPerson(\"Jade\", \"Flora\", \"fellow\", \"Narnia\", \"PHP\")\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(user.FirstName, ShouldNotBeBlank)\n\t\t\tSo(user.ID, ShouldNotBeBlank)\n\t\t\tSo(user.LastName, ShouldNotBeBlank)\n\t\t\tSo(user.Type, ShouldNotBeBlank)\n\t\t\tSo(user.User, ShouldNotResemble, testUser.User)\n\n\t\t\trunValuesTests(user.LivingSpace)\n\t\t\trunValuesTests(user.Office)\n\t\t})\n\n\t\tConvey(\"Print the successfully created User and Room \", func() {\n\t\t\taddPerson(\"Jackson\", \"Davids\", \"fellow\", \"\", \"Mogadishu\")\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tprintRooms()\n\n\t\t\tprintUsers()\n\n\t\t\tSo(con.DestroyData(), ShouldBeNil)\n\t\t})\n\t})\n}", "func TestListMessages(t *testing.T) {\n\ts = getSpark(t)\n\tif len(allRooms) < 1 {\n\t\tgetAllRooms(t)\n\t}\n\n\tuv := url.Values{}\n\tfmt.Println(\"Title: \", allRooms[0].Title)\n\tuv.Add(\"roomId\", allRooms[0].Id)\n\tallMessages, err := s.ListMessages(&uv)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(allMessages) < 1 {\n\t\tt.Fatal(\"Expected there to be at least one message in the room\")\n\n\t}\n\n\t// test Get messages\n\tfirstMessage := allMessages[0]\n\t_, err = s.GetMessage(firstMessage.Id)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func TestClientSpacesSummary(t *testing.T) {\n\tdeployment := Deploy(t, b.BlueprintOneToOneRoom)\n\tdefer deployment.Destroy(t)\n\n\troomNames := make(map[string]string)\n\n\t// create the rooms\n\talice := deployment.Client(t, \"hs1\", \"@alice:hs1\")\n\troot := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Root\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[root] = \"Root\"\n\tr1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R1\",\n\t})\n\troomNames[r1] = \"R1\"\n\tss1 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"Sub-Space 1\",\n\t\t\"topic\": \"Some topic for sub-space 1\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss1] = \"Sub-Space 1\"\n\tr2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R2\",\n\t})\n\troomNames[r2] = \"R2\"\n\tss2 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"SS2\",\n\t\t\"creation_content\": map[string]interface{}{\n\t\t\t\"type\": \"m.space\",\n\t\t},\n\t})\n\troomNames[ss2] = \"SS2\"\n\tr3 := alice.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R3\",\n\t})\n\troomNames[r3] = \"R3\"\n\t// alice is not joined to R4\n\tbob := deployment.Client(t, \"hs1\", \"@bob:hs1\")\n\tr4 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R4\",\n\t\t\"initial_state\": []map[string]interface{}{\n\t\t\t{\n\t\t\t\t\"type\": \"m.room.history_visibility\",\n\t\t\t\t\"state_key\": \"\",\n\t\t\t\t\"content\": map[string]string{\n\t\t\t\t\t\"history_visibility\": \"world_readable\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\troomNames[r4] = \"R4\"\n\tr5 := bob.CreateRoom(t, map[string]interface{}{\n\t\t\"preset\": \"public_chat\",\n\t\t\"name\": \"R5\",\n\t})\n\n\t// create the links\n\trootToR1 := eventKey(root, r1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\trootToSS1 := eventKey(root, ss1, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss1,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\trootToR2 := eventKey(root, r2, spaceChildEventType)\n\talice.SendEventSynced(t, root, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t\t\"suggested\": true,\n\t\t},\n\t})\n\t// Note that this link gets ignored since R2 is not a space.\n\talice.SendEventSynced(t, r2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r5,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\talice.SendEventSynced(t, r2, b.Event{ // parent link\n\t\tType: spaceParentEventType,\n\t\tStateKey: &root,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss1ToSS2 := eventKey(ss1, ss2, spaceChildEventType)\n\talice.SendEventSynced(t, ss1, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &ss2,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR3 := eventKey(ss2, r3, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r3,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\tss2ToR4 := eventKey(ss2, r4, spaceChildEventType)\n\talice.SendEventSynced(t, ss2, b.Event{\n\t\tType: spaceChildEventType,\n\t\tStateKey: &r4,\n\t\tContent: map[string]interface{}{\n\t\t\t\"via\": []string{\"hs1\"},\n\t\t},\n\t})\n\n\t// - Querying the root returns the entire graph\n\t// - Rooms are returned correctly along with the custom fields `room_type`.\n\t// - Events are returned correctly.\n\tt.Run(\"query whole graph\", func(t *testing.T) {\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, r3, r4, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, func(roomInt interface{}, data gjson.Result) error {\n\t\t\t\t\troomID := roomInt.(string)\n\t\t\t\t\t// check fields\n\t\t\t\t\tif name, ok := roomNames[roomID]; ok {\n\t\t\t\t\t\tif data.Get(\"name\").Str != name {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got name %s want %s\", roomID, data.Get(\"name\").Str, name)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif roomID == ss1 {\n\t\t\t\t\t\twantType := \"m.space\"\n\t\t\t\t\t\tif data.Get(\"room_type\").Str != wantType {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"room %s got type %s want %s\", roomID, data.Get(\"room_type\").Str, wantType)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}),\n\t\t\t\t// Check that the links from Root down to other rooms and spaces exist.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1,\n\t\t\t\t\tss1ToSS2, ss2ToR3, ss2ToR4,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_rooms_per_space works correctly\n\tt.Run(\"max_rooms_per_space\", func(t *testing.T) {\n\t\t// should omit either R3 or R4 if we start from SS1 because we only return 1 link per room which will be:\n\t\t// SS1 -> SS2\n\t\t// SS2 -> R3,R4 (but only 1 is allowed)\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_rooms_per_space\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", ss1, \"spaces\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\twantItems := []interface{}{\n\t\t\tss1ToSS2,\n\t\t\tss2ToR3, ss2ToR4, // one of these\n\t\t}\n\t\tbody := must.ParseJSON(t, res.Body)\n\t\tgjson.GetBytes(body, \"events\").ForEach(func(_, val gjson.Result) bool {\n\t\t\twantItems = must.CheckOff(t, wantItems, eventKey(val.Get(\"room_id\").Str, val.Get(\"state_key\").Str, val.Get(\"type\").Str))\n\t\t\treturn true\n\t\t})\n\t\tif len(wantItems) != 1 {\n\t\t\tif wantItems[0] != ss2ToR3 && wantItems[0] != ss2ToR4 {\n\t\t\t\tt.Errorf(\"expected fewer events to be returned: %s\", string(body))\n\t\t\t}\n\t\t}\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"max_depth\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"max_depth\", \"1\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2, ss1,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2, rootToSS1, ss1ToSS2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting suggested_only works correctly\n\tt.Run(\"suggested_only\", func(t *testing.T) {\n\t\t// Should only include R1, SS1, and R2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"suggested_only\", \"true\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\t// All of the links are still there.\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\t// - Setting max_depth works correctly\n\tt.Run(\"pagination\", func(t *testing.T) {\n\t\t// The initial page should only include Root, R1, SS1, and SS2.\n\t\tquery := make(url.Values, 1)\n\t\tquery.Set(\"limit\", \"4\")\n\t\tres := alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tbody := must.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, ss1, ss2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\t// The following page should include R3, R4, and R2.\n\t\tquery = make(url.Values, 1)\n\t\tquery.Set(\"from\", client.GetJSONFieldStr(t, body, \"next_batch\"))\n\t\tres = alice.MustDoFunc(\n\t\t\tt,\n\t\t\t\"GET\",\n\t\t\t[]string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"},\n\t\t\tclient.WithQueries(query),\n\t\t)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\tr3, r4, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n\n\tt.Run(\"redact link\", func(t *testing.T) {\n\t\t// Remove the root -> SS1 link\n\t\talice.SendEventSynced(t, root, b.Event{\n\t\t\tType: spaceChildEventType,\n\t\t\tStateKey: &ss1,\n\t\t\tContent: map[string]interface{}{},\n\t\t})\n\t\tres := alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"spaces\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"events\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\n\t\tres = alice.MustDo(t, \"GET\", []string{\"_matrix\", \"client\", \"unstable\", \"org.matrix.msc2946\", \"rooms\", root, \"hierarchy\"}, nil)\n\t\tmust.MatchResponse(t, res, match.HTTPResponse{\n\t\t\tJSON: []match.JSON{\n\t\t\t\tmatch.JSONCheckOff(\"rooms\", []interface{}{\n\t\t\t\t\troot, r1, r2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn r.Get(\"room_id\").Str\n\t\t\t\t}, nil),\n\t\t\t\tmatch.JSONCheckOff(\"rooms.#.children_state|@flatten\", []interface{}{\n\t\t\t\t\trootToR1, rootToR2,\n\t\t\t\t}, func(r gjson.Result) interface{} {\n\t\t\t\t\treturn eventKey(r.Get(\"room_id\").Str, r.Get(\"state_key\").Str, r.Get(\"type\").Str)\n\t\t\t\t}, nil),\n\t\t\t},\n\t\t})\n\t})\n}", "func (m *MockService) GetAppDetails(arg0 context.Context, arg1 *v1alpha1.ApplicationSource) (*shared.AppDetail, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAppDetails\", arg0, arg1)\n\tret0, _ := ret[0].(*shared.AppDetail)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetBook(t *testing.T) {\n\tbooks := book.GetBook()\n\n\tif len(books) < 1 {\n\t\tt.Errorf(\"No books loaded from database.\")\n\t} else {\n\t\tfmt.Println(\"book.go Func GetBook PASS\")\n\t}\n}", "func (m *PrinterLocation) GetRoomName()(*string) {\n val, err := m.GetBackingStore().Get(\"roomName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func TestPagarmePlanoGet(t *testing.T) {\n \n Pagarme := pagarme.NewPagarme(\"pt-BR\", ApiKey, CryptoKey)\n Pagarme.SetDebug()\n\n id, _ := client.Get(\"PlanoId\").Int64()\n\n result, err := Pagarme.PlanoGet(id)\n\n if err != nil {\n t.Errorf(\"Erro ao create plano: %v\", err)\n }else{\n //t.Log(fmt.Sprintf(\"result = %v\", customer.Id)) \n\n if result.Plano.Id == 0 {\n t.Errorf(\"plano id is expected\")\n return\n }\n\n\n }\n\n}", "func TestGetAllOrdersForRestaurantID(t *testing.T) {\n\n // ...\n\n}", "func (id DeviceID) Room() string {\n\tsplit := strings.SplitN(string(id), \"-\", 3)\n\tif len(split) != 3 {\n\t\treturn string(id)\n\t}\n\n\treturn split[0] + \"-\" + split[1]\n}", "func (suite *TestManagerSuite) TestManagerGetBy() {\n\tl, err := suite.m.GetBy(\"d1000\", \"ruuid\", []string{v1.MimeTypeNativeReport})\n\trequire.NoError(suite.T(), err)\n\trequire.Equal(suite.T(), 1, len(l))\n\tassert.Equal(suite.T(), suite.rpUUID, l[0].UUID)\n\n\tl, err = suite.m.GetBy(\"d1000\", \"ruuid\", nil)\n\trequire.NoError(suite.T(), err)\n\trequire.Equal(suite.T(), 1, len(l))\n\tassert.Equal(suite.T(), suite.rpUUID, l[0].UUID)\n\n\tl, err = suite.m.GetBy(\"d1000\", \"\", nil)\n\trequire.NoError(suite.T(), err)\n\trequire.Equal(suite.T(), 1, len(l))\n\tassert.Equal(suite.T(), suite.rpUUID, l[0].UUID)\n}", "func (a *Client) GetDetails(params *GetDetailsParams) (*GetDetailsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetDetailsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getDetails\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/details\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetDetailsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetDetailsOK), nil\n\n}", "func getProgrammingsYearsTest(e *httpexpect.Expect, t *testing.T) {\n\ttestCases := []testCase{\n\t\tnotLoggedTestCase,\n\t\t{\n\t\t\tToken: testCtx.Admin.Token,\n\t\t\tStatus: http.StatusOK,\n\t\t\tBodyContains: []string{`{\"ProgrammingsYears\":[{\"year\":2018}]}`}},\n\t}\n\tf := func(tc testCase) *httpexpect.Response {\n\t\treturn e.GET(\"/api/programmings/years\").\n\t\t\tWithHeader(\"Authorization\", \"Bearer \"+tc.Token).Expect()\n\t}\n\tfor _, r := range chkTestCases(testCases, f, \"GetProgrammingsYears\") {\n\t\tt.Error(r)\n\t}\n}", "func (m *GoogleChatManager) Room() string {\n\treturn m.room\n}", "func newRoom(id string, name string) *Room {\n\tr := &Room{\n\t\tid: id,\n\t\tname: name,\n\t\tmembers: make(map[string]*Member),\n\t}\n\treturn r\n}", "func (ng *NameGenerator) GetRoomName() string {\n\treturn ng.generate(ng.generateRoomName)\n}", "func (h *HTTP) getTicketDetails(w http.ResponseWriter, r *http.Request) {\n\tparams := webgo.Context(r).Params()\n\n\t// reads the ticketId from the request path.\n\tticket := &toll.TicketToll{\n\t\tTicketID: params[\"ticketId\"],\n\t}\n\n\t// gets the ticket details corresponding to the provided ticketId\n\ttollTicketData, err := h.APIHandler.TollHandler.GetTollTicketDetails(r.Context(), ticket)\n\tif err != nil {\n\t\twebgo.R400(w, err)\n\t}\n\twebgo.R200(w, tollTicketData)\n}", "func (inst *Instance) GetPlayerRoom(id int32) (room.Room, error) {\n\tfor _, v := range inst.rooms {\n\t\tif v.Present(id) {\n\t\t\treturn v, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Player does not belong to a room\")\n}", "func Test_Get(t *testing.T) {\n\th := NewHttpSend(GetUrlBuild(\"http://192.168.10.76/lotus/lotustest\", map[string]string{\"name\": \"xiaochuan\"}))\n\tbody, err := h.Get()\n\tif err != nil {\n\t\tt.Error(\"请求错误:\", err)\n\t\t//t.Errorf(err.Error())\n\t\tt.Fail()\n\t} else {\n\t\tt.Log(\"正常返回\")\n\n\t\tvar out bytes.Buffer\n\t\terr = json.Indent(&out, body, \"\", \"\\t\")\n\t\tfmt.Println(out.String())\n\t}\n}", "func MyRoomHandler(w http.ResponseWriter, r *http.Request) {\n\n\tuname := r.URL.Query().Get(\"uname\")\n\tlog.Println(\"User checking room:\" + uname)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tif roomID, ok := paired.Get(uname).(string); ok {\n\t\tw.Write([]byte(`{\"code\":200,\"data\":\"` + roomID + `\"}`))\n\t} else {\n\t\tw.Write([]byte(`{\"code\":200,\"msg\":\"Room not found\", \"data\": null}`))\n\t}\n}", "func (_m *Usecase) GetDetail(ctx context.Context, id string,token string)(*models.PromoDto,error) {\n\tret := _m.Called(ctx, id,token)\n\n\tvar r0 *models.PromoDto\n\tif rf, ok := ret.Get(0).(func(context.Context, string,string) *models.PromoDto); ok {\n\t\tr0 = rf(ctx, id,token)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.PromoDto)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string,string) error); ok {\n\t\tr1 = rf(ctx, id,token)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (rl *roomList) get(name string) *Room {\n\trl.RLock()\n\tdefer rl.RUnlock()\n\tr, ok := rl.list[name]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn r\n}", "func (_m *API) GetCharacterOgraphy(_type string, id int) ([]model.Role, int, error) {\n\tret := _m.Called(_type, id)\n\n\tvar r0 []model.Role\n\tif rf, ok := ret.Get(0).(func(string, int) []model.Role); ok {\n\t\tr0 = rf(_type, id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]model.Role)\n\t\t}\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(string, int) int); ok {\n\t\tr1 = rf(_type, id)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, int) error); ok {\n\t\tr2 = rf(_type, id)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func GetAllRooms(query map[string]string, fields []string, sortby []string, order []string,\n\toffset int64, limit int64) (ml []interface{}, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(Rooms))\n\t// query k=v\n\tqs = RebuildConditions(qs, query)\n\t// order by:\n\tqs, errorMq := MakeOrderForQuery(qs, sortby, order)\n\n\tif errorMq != nil {\n\t\treturn ml, errorMq\n\t}\n\n\tvar l []Rooms\n\tif _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {\n\t\tvar result1 []interface{}\n\t\tfor _, v := range l {\n\t\t\tresult1 = append(result1, v)\n\t\t}\n\t\t//filter data by using array field\n\t\tml, err := FilterResultByField(fields, result1)\n\t\treturn ml, err\n\t}\n\treturn nil, err\n}", "func ListRoomPath() string {\n\n\treturn fmt.Sprintf(\"/api/rooms\")\n}", "func TestGetLoots(t *testing.T) {\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tloots, err := db.GetLoots(344178872)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif loots[0].Price != 0.12 || loots[0].Amout != \"100002.0\" || loots[0].Coin != \"MNT\" {\n\t\tt.Errorf(\"I wanna see price = 1000, but %f, amount = 1000, but %s, coin = MNT, but %s\", loots[0].Price, loots[0].Amout, loots[0].Coin)\n\t}\n}", "func (suite *TestAgentItSuite) TestGetAgentById(c *C) {\n\tclient := sling.New().Get(httpClientConfig.String()).\n\t\tPath(\"/api/v1/nqm/agent/36771\")\n\n\tslintChecker := testingHttp.NewCheckSlint(c, client)\n\tjsonResult := slintChecker.GetJsonBody(http.StatusOK)\n\n\tc.Logf(\"[Get A Agent] JSON Result: %s\", json.MarshalPrettyJSON(jsonResult))\n\tc.Assert(jsonResult.Get(\"id\").MustInt(), Equals, 36771)\n}", "func (rf *RoomFinder) RegisterRoom( r *Room ) {\n\tif rf.regRoomIds == nil {\n\t\trf.regRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.sdRoomIds == nil {\n\t\trf.sdRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.ldRoomIds == nil {\n\t\trf.ldRoomIds = make( map[ int64 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.elRoomIds == nil {\n\t\trf.elRoomIds = make( map[ int32 ] *tools.SI64Set, 1 )\n\t}\n\tif rf.regRoomIds[ r.regionId ] == nil {\n\t\trf.regRoomIds[ r.regionId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.regRoomIds[ r.regionId ].Add( r.id )\n\tif rf.sdRoomIds[ r.shortDescId ] == nil {\n\t\trf.sdRoomIds[ r.shortDescId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.sdRoomIds[ r.shortDescId ].Add( r.id )\n\tif rf.ldRoomIds[ r.longDescId ] == nil {\n\t\trf.ldRoomIds[ r.longDescId ] = tools.NewSI64Set( 1 )\n\t}\n\trf.ldRoomIds[ r.longDescId ].Add( r.id )\n\tes := make( []string, len(r.exits) )\n\ti := 0\n\tfor k, _ := range r.exits {\n\t\tes[i] = k\n\t\ti++\n\t}\n\th := hashExits( es )\n\tif rf.elRoomIds[ h ] == nil {\n\t\trf.elRoomIds[ h ] = tools.NewSI64Set( 1 )\n\t}\n\trf.elRoomIds[ h ].Add( r.id )\n\treturn\n}" ]
[ "0.7348406", "0.6444562", "0.61860174", "0.6185885", "0.6089801", "0.59835464", "0.59342754", "0.59273344", "0.5876093", "0.5816311", "0.580744", "0.5780778", "0.56908804", "0.5688876", "0.5670314", "0.5651615", "0.563739", "0.56349933", "0.56153977", "0.5573568", "0.55555546", "0.552053", "0.5507858", "0.55064636", "0.5479298", "0.5472828", "0.5466358", "0.54434747", "0.540783", "0.53926325", "0.5387801", "0.53688437", "0.53674704", "0.536545", "0.53624755", "0.5338937", "0.53313136", "0.53293675", "0.53195846", "0.53008944", "0.52907133", "0.5243429", "0.5188027", "0.5188027", "0.5144996", "0.5125293", "0.50899726", "0.50829947", "0.506921", "0.5060368", "0.5041266", "0.5033729", "0.4991543", "0.498373", "0.49830478", "0.49789074", "0.49699247", "0.49670336", "0.49659324", "0.4963783", "0.49536696", "0.4952778", "0.4921924", "0.49145454", "0.48967123", "0.48820612", "0.4873029", "0.4864119", "0.48511022", "0.48365563", "0.48257458", "0.48245513", "0.48163164", "0.48158813", "0.48104393", "0.4808617", "0.480149", "0.4799983", "0.4797277", "0.4794363", "0.4791459", "0.4789079", "0.47837573", "0.47780722", "0.47723395", "0.4769777", "0.47672614", "0.47640088", "0.4761904", "0.47567636", "0.4756662", "0.47520372", "0.47498837", "0.47103575", "0.46969327", "0.46933153", "0.4686808", "0.46826807", "0.46793848", "0.46792132" ]
0.8174956
0
NewProductRepo will be used to return db
func NewProductRepo(DbConnection *gorm.DB) producthandler.GeneralProductRepo { return &ProductRepo{DbConnection} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newOrderRepo(db *sql.DB) *orderRepo {\n\treturn &orderRepo{\n\t\tdb: db,\n\t}\n}", "func (pr ProductRepository) Create(ctx context.Context, product *domain.Product) error {\n\treturn pr.db.Insert(ctx, product)\n}", "func NewProduct(c *fiber.Ctx) error {\n db := database.Connection()\n\treturn models.NewProduct(db, c)\n}", "func CreateProduct(c *gin.Context) {\n\t// if os.Getenv(\"app_status\") != \"true\" {\n\t// \tc.JSON(http.StatusInternalServerError, \"Product service is temporarily down\")\n\t// \treturn\n\t// }\n\tdb := DbConn()\n\tvar prod Products\n\terr := c.BindJSON(&prod)\n\tfmt.Println(\"Error binding json: \", err)\n\tfmt.Println(\"prod: \", prod)\n\tif err != nil {\n\t\tfmt.Println(\"Error in req format\")\n\t\tc.JSON(http.StatusBadRequest, \"Error in req format\")\n\t}\n\terr = db.Create(&prod).Error\n\tif err != nil {\n\t\tfmt.Println(\"Error in inserting in database\")\n\t\tc.String(http.StatusServiceUnavailable, \"Error in inserting in database\")\n\t}\n\n\tc.String(http.StatusOK, \"Success\")\n\n}", "func NewProductRepository(db *sql.DB) (product.Repository, error) {\n\tpdb, err := mysql.New(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := productRepo{pdb}\n\treturn &r, nil\n}", "func (r ProductRepository) Create(ctx context.Context, entity *product.Product) error {\n\n\tif !r.db.DB().NewRecord(entity) {\n\t\treturn errors.New(\"entity is not new\")\n\t}\n\treturn r.db.DB().Create(entity).Error\n}", "func NewRepo(db *db.DB) {\n\tPsql = db.SQL\n}", "func newUserRepo(db *sql.DB) *userRepo {\n\treturn &userRepo{\n\t\tdb: db,\n\t}\n}", "func newClientMongoRepository() repository.ClientRepository {\n\tmongoAddr := os.Getenv(\"DATABASE_CONN\")\n\tfmt.Println(\"mongoAddr => \", mongoAddr)\n\tclient := repositoryimpl.Connect(mongoAddr)\n\treturn repositoryimpl.NewRepository(client)\n}", "func NewRepository(db *gorm.DB) ProductDomain.Repository {\n\treturn &handler{\n\t\tdb: db,\n\t}\n}", "func PostProduct(data Product) Product {\n\tdatabase.SQL.Create(&data)\n\treturn data\n}", "func NewProductRepositoryImpl(Conn *sql.DB) *ProductRepositoryImpl {\n\treturn &ProductRepositoryImpl{conn: Conn}\n}", "func init() {\n\tRepoCreateCatalog(Catalog{Id: \"Nanaimo Lidar\"})\n\tRepoCreateCatalog(Catalog{Id: \"sample\"})\n}", "func (create) Product(ctx context.Context, db *sqlx.DB, user auth.Claims, np NewProduct, now time.Time) (*Product, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.create.product\")\n\tdefer span.End()\n\n\tp := Product{\n\t\tID: uuid.New().String(),\n\t\tName: np.Name,\n\t\tCost: np.Cost,\n\t\tQuantity: np.Quantity,\n\t\tUserID: user.Subject,\n\t\tDateCreated: now.UTC(),\n\t\tDateUpdated: now.UTC(),\n\t}\n\n\tconst q = `\n\t\tINSERT INTO products\n\t\t(product_id, user_id, name, cost, quantity, date_created, date_updated)\n\t\tVALUES ($1, $2, $3, $4, $5, $6, $7)`\n\n\t_, err := db.ExecContext(ctx, q,\n\t\tp.ID, p.UserID,\n\t\tp.Name, p.Cost, p.Quantity,\n\t\tp.DateCreated, p.DateUpdated)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"inserting product\")\n\t}\n\n\treturn &p, nil\n}", "func New(db *sqlx.DB) promo.Repository {\n\treturn &promoRepository{db}\n}", "func NewProductRepository(db orm.Ormer) IProductRepository {\n\treturn &productRepository{db: db}\n}", "func CreateProduct(c *gin.Context) {\n\tvar product Models.Product\n\tc.BindJSON(&product)\n\terr := Models.CreateProduct(&product)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func New(db *sql.DB, logger log.Logger) (todo.Repository, error) {\n\t// return repository\n\treturn &repository{\n\t\tdb: db,\n\t\tlogger: log.With(logger, \"rep\", \"cockroachdb\"),\n\t}, nil\n}", "func New(db *sql.DB, logger log.Logger) (order.Repository, error) {\n\t// return repository\n\treturn &repository{\n\t\tdb: db,\n\t\tlogger: log.With(logger, \"rep\", \"cockroachdb\"),\n\t}, nil\n}", "func (store *Store) createProductPGStore() error {\n\tconst queries = `CREATE SCHEMA IF NOT EXISTS shopalyst_product_v1;\n CREATE TABLE IF NOT EXISTS shopalyst_product_v1.product(id text DEFAULT ''::text , category_id text DEFAULT ''::text, name text DEFAULT ''::text , description text DEFAULT ''::text , image_url text DEFAULT ''::text ,PRIMARY KEY (id) );\n `\n\t_, err := store.DB.Exec(queries)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (service *Service) CreateProduct(c *gin.Context) error {\n\tname := c.PostForm(\"name\")\n\tdescription := c.PostForm(\"description\")\n\tuserID, err := jwt.VerifyToken(c)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar product Product\n\n\tproduct.SetName(name)\n\tproduct.SetDescription(description)\n\tproduct.SetUserID(userID)\n\n\terr = service.ProductRepository.Create(product)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewProductController(router gin.IRouter, client *ent.Client) *ProductController {\n pc := &ProductController{\n client: client,\n router: router,\n }\n pc.register()\n return pc\n }", "func (r Repository) AddProduct(product Product) bool {\n\tsession, err := mgo.Dial(SERVER)\n\tdefer session.Close()\n\n\tproductId += 1\n\tproduct.ID = productId\n\tsession.DB(DBNAME).C(COLLECTION).Insert(product)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn false\n\t}\n\n\tfmt.Println(\"Added New Product ID- \", product.ID)\n\n\treturn true\n}", "func (r *repo) Create(repository *dbmodels.Repository) error {\n\trc := r.db.Database().Collection(viper.GetString(\"db.repository_collection\"))\n\tctx, cancel := context.WithTimeout(\n\t\tcontext.Background(),\n\t\ttime.Duration(viper.GetInt(\"db.query_timeout_in_sec\"))*time.Second,\n\t)\n\tdefer cancel()\n\n\t_, err := rc.InsertOne(ctx, repository)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create repo with error %v\", err)\n\t}\n\n\treturn nil\n}", "func ProvideRepo(deps BaseDependencies) (db repo.Repository, cleanup func(), err error) {\n\tvar (\n\t\tctx = context.Background()\n\t\tdbCfg = deps.DB\n\t\trepolg = log.NewZapLogger(\"Repo\", dbCfg.Log) // Logger for Repo Layer\n\t)\n\n\tdb, err = repo.NewPostgres(dbCfg.PostgresStr(), repolg, // Postgres\n\t\trepo.SetMaxPostgresConn(dbCfg.MaxConns),\n\t\trepo.SetTracer(deps.OTTracer),\n\t\trepo.EnableMetrics(deps.DBMetrics))\n\tif err != nil {\n\t\trepolg.Error(ctx, \"Error creating repo\", err) // Service exits on any error creating repo\n\t\treturn\n\t}\n\tcleanup = func() {\n\t\tdb.Close()\n\t}\n\treturn\n}", "func NewRepo(uri string) (Repository, error) {\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(uri))\n\tlog.Println(\"db client created\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 20 * time.Second)\n\tdefer cancel()\n\terr = client.Connect(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"db client connected\")\n\n\terr = client.Ping(ctx, readpref.Primary())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"db client ping\")\n\n\tdbName := os.Getenv(\"DATABASE_NAME\")\n\tdb := client.Database(dbName)\n\tcol := db.Collection(os.Getenv(\"TRAVEL_COLLECTION\"))\n\treturn &DBRepository{\n\t\tclient: \tclient,\n\t\tdatabase: db,\n\t\tCollection: col,\n\t}, nil\n}", "func NewProductRepository(db *mongo.Database) (*ProductRepository, error) {\n\treturn &ProductRepository{\n\t\tdb: db,\n\t}, nil\n}", "func NewProductRepository(repository *infrastructure.MongoRepository) (*ProductRepository, error) {\n\tr := &ProductRepository{repository}\n\n\tindex := mgo.Index{\n\t\tKey: []string{\"productid\"},\n\t\tUnique: true,\n\t\tDropDups: true,\n\t\tBackground: true,\n\t\tSparse: true,\n\t}\n\n\tsess := r.Session.Copy()\n\tdefer sess.Close()\n\n\tc := sess.DB(r.DB).C(\"Product\")\n\n\tif err := c.EnsureIndex(index); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func Create() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\trequestBody := productPostRequest{}\n\t\tc.Bind(&requestBody)\n\n\t\tproduct := model.Products{\n\t\t\tProductTypeID: requestBody.ProductTypeID,\n\t\t\tName: requestBody.Name,\n\t\t}\n\n\t\terr := db.Db.Create(&product)\n\n\t\tif product.ID == 0 {\n\t\t\tc.JSON(http.StatusBadRequest, err.Error)\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func (ph *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : POST /app/product API hit!\")\n\tvar request CreateProductRequest\n\tbody := json.NewDecoder(r.Body)\n\terr := body.Decode(&request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.DecodeErrorCode, err.Error())\n\t\treturn\n\t}\n\tvalidator := validator.New()\n\terr = validator.Struct(request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.ValidationErrorCode, err.Error())\n\t\treturn\n\t}\n\tproduct, err := ph.ps.CreateProduct(r.Context(), &request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tif err.Error() == utils.ProductNameExistsError {\n\t\t\tutils.Fail(w, 200, utils.ProductNameExistsErrorCode, err.Error())\n\t\t\treturn\n\t\t}\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : product created! id_product : \", product.ID)\n\tutils.Send(w, 200, product)\n}", "func newMongoDB(addr string, cred *mgo.Credential) (ProductDatabase, error) {\n\tconn, err := mgo.Dial(addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"mongo: could not dial: %v\", err)\n\t}\n\n\tif cred != nil {\n\t\tif err := conn.Login(cred); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &mongoDB{\n\t\tconn: conn,\n\t\tc: conn.DB(\"productshelf\").C(\"products\"),\n\t}, nil\n}", "func NewProductRepository(db *sqlx.DB, cache redis.Conn) ProductRepository {\n\treturn productRepository{db, cache}\n}", "func (pri *ProductRepositoryImpl) StoreProduct(p entity.Product) error {\n\n\t//_, err := pr.conn.Exec(\"INSERT INTO products (itemname,itemtype,quantity,price,description,image)\" +\n\t//\" values(?, ?, ?, ?, ?, ?)\",c.Name, c.ItemType, c.Quantity, c.Price, c.Description, c.Image)\n\n\t//_, err := pri.conn.Exec(\"INSERT INTO products (itemname,itemtype,quantity,price,description,image)\" +\n\t//\t\" values($1, $2, $3, $4, $5, $6)\",p.Name, p.ItemType, p.Quantity, p.Price, p.Description, p.Image)\n\t//\n\t_, err := pri.conn.Exec(\"INSERT INTO products (itemname,quantity,price,description,image)\"+\n\t\t\" values($1, $2, $3, $4, $5)\", p.Name, p.Quantity, p.Price, p.Description, p.Image)\n\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn errors.New(\"Insertion has failed or Item already Exists\")\n\t}\n\n\treturn nil\n}", "func (prod *Product) store() {\n\tcurrentDir, _ := os.ReadDir(\".\")\n\tfmt.Println(currentDir)\n\n\tcheckForFolder(\"products\")\n\n\tfile, _ := os.Create(\"products/\" + prod.id + \".json\")\n\tprodFolder, _ := os.ReadDir(\"products\")\n\tfmt.Printf(\"%v Products\\n\", len(prodFolder))\n\n\t// Created\n\tcontent := fmt.Sprintf(\"{\\n\\\"id\\\": \\\"%v\\\",\\n\\\"title\\\": \\\"%v\\\",\\n\\\"description\\\": \\\"%v\\\",\\n\\\"price_usd\\\": \\\"%.2f\\\"\\n}\",\n\t\tprod.id,\n\t\tprod.title,\n\t\tprod.description,\n\t\tprod.price,\n\t)\n\n\tfile.WriteString(content)\n\tfile.Close()\n}", "func (main *Main) Create(e echo.Context) (err error) {\n\n\t// get request and validate\n\treq := new(request.Create)\n\te.Bind(req)\n\tif err = e.Validate(req); err != nil {\n\t\treturn rest.ConstructErrorResponse(e, exception.NewInputValidationFailed(err.Error()))\n\t}\n\t// map req to input data\n\treqData := input.NewNewProductCreate(\n\t\tmap[string]interface{}{\n\t\t\t\"Name\": req.Name,\n\t\t\t\"Qty\": req.Qty,\n\t\t\t\"Price\": req.Price,\n\t\t\t\"Weight\": req.Weight,\n\t\t\t\"Images\": req.Images,\n\t\t\t\"Description\": req.Description,\n\t\t},\n\t)\n\t//insert data to db\n\tproduct, exc := ProductModel.Create(reqData)\n\tif exc != nil {\n\t\treturn rest.ConstructErrorResponse(e, exc)\n\t}\n\tdata := map[string]contract.Model{\n\t\t\"created_product\": product,\n\t}\n\treturn rest.ConstructSuccessResponse(e, data)\n}", "func New(db *gorm.DB) (Repository, error) {\n\treturn &repo{\n\t\tDB: db,\n\t}, nil\n}", "func (m *Backend) Products() product.Repository {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Products\")\n\tret0, _ := ret[0].(product.Repository)\n\treturn ret0\n}", "func (r Repository) AddProduct(product Product) bool {\n\tsession, err := connectToServer(r.Config)\n\n\tif err != nil {\n\t\tfmt.Println(\"Failed to establish connection to Mongo server:\", err)\n\t\treturn false\n\t}\n\n\tdefer session.Close()\n\n\tproductID++\n\tproduct.ID = productID\n\n\terr = session.DB(r.Config.DatabaseName).C(STORE_COLLECTION).Insert(product)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to insert product:\", err)\n\t\treturn false\n\t}\n\n\tfmt.Println(\"Added New Product ID- \", product.ID)\n\n\treturn true\n}", "func (*Products) Create(product *Products) (int64, error) {\n\n\tstmt, err := db.Prepare(\n\t\t\"insert into products (name, unit) \" +\n\t\t\t\"values ($1, $2) returning id\")\n\n\tif err != nil {\n\t\tlog.Println(\"(CreateProduct:Prepare)\", err)\n\t\treturn -1, err\n\t}\n\n\tdefer stmt.Close()\n\n\terr = stmt.QueryRow(product.Name,\n\t\tproduct.Unit).Scan(&product.ID)\n\n\tif err != nil {\n\t\tlog.Println(\"(CreateProduct:Exec)\", err)\n\t\treturn -1, err\n\t}\n\n\treturn product.ID, nil\n\n}", "func initializeRepo(database *string) repository.ClientRepository {\n\tswitch *database {\n\tcase \"mongo\":\n\t\treturn newClientMongoRepository()\n\tdefault:\n\t\treturn nil // we can have several implementation like in memory, postgress etc\n\t}\n}", "func (e *engine) CreateProduct(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\tvar product = &domain.Product{}\n\t// check is valid json for product\n\terr = c.BindToJson(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tproduct.Iid = id\n\tres, err := e.ProductLogic.NewProduct(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tc.JSON(200, res)\n}", "func CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tvar product types.Product\n\terr := readBody(r, &product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\tsavedProduct, err := repo.CreateProduct(r.Context(), product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, savedProduct, http.StatusCreated)\n}", "func (achieveRepo *mockAchieveRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func NewRepo(dbInfo DBInfo) (*Repo, error) {\n\tctx := context.Background()\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(dbInfo.URL))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.Connect(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Connected to DB\")\n\n\treturn &Repo{\n\t\tclient: client,\n\t\tctx: ctx,\n\t\tdbInfo: dbInfo,\n\t}, err\n\n}", "func (programRepo *mockProgramRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func newGreetingRepository(db *sql.DB) engine.GreetingRepository {\n\treturn &greetingRepository{db}\n}", "func (a *RepoAPI) createRepo(params interface{}) (resp *rpc.Response) {\n\treturn rpc.Success(a.mods.Repo.Create(cast.ToStringMap(params)))\n}", "func (h *ProductHandler) AddProduct(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newProduct newProduct\n\tbody, _ := ioutil.ReadAll(r.Body)\n\terr := json.Unmarshal(body, &newProduct)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\tproduct := models.Product{\n\t\tName: newProduct.Name,\n\t\tSKU: newProduct.SKU,\n\t}\n\terr = h.ProductUsecase.Create(ctx, &product)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tfor _, catID := range newProduct.CategoryID {\n\t\tcat := models.ProductCategory{\n\t\t\tProductID: product.ID,\n\t\t\tCategoryID: catID,\n\t\t}\n\n\t\terr = h.ProductCatUsecase.Create(ctx, &cat)\n\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, price := range newProduct.Price {\n\t\t_price := models.ProductPrice{\n\t\t\tAmount: price.Amount,\n\t\t\tPrice: price.Price,\n\t\t\tProductID: product.ID,\n\t\t}\n\n\t\terr = h.PriceUsecase.Create(ctx, &_price)\n\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tutils.JSON(w, http.StatusOK, product)\n\n}", "func (db Database) saveProduct() error {\n\treturn makeError()\n}", "func (s *RepositoryService) Create(rs app.RequestScope, model *models.Repository) (*models.Repository, error) {\n\tif err := model.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := s.dao.Create(rs.DB(), model); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.dao.Get(rs.DB(), model.Name)\n}", "func ProvideProductService(repo Repository) Service {\n\treturn Service{ProductRepository: repo}\n}", "func GetProduct(c *gin.Context) {\n\tproduct, err := productRepository.ByID(c.Param(\"id\"))\n\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\"status\": \"file not found\"})\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func New() (Repo, error) {\n\t// Open the my.db data file in your current directory.\n\t// It will be created if it doesn't exist.\n\tlogrus.Infof(\"Using database file %s\\n\", conf.Options.DB.ConnectString)\n\tdb, err := bolt.Open(conf.Options.DB.ConnectString, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(\"users\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"teams\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"teamusers\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"oauth\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"channels\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"joinslack\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"convicted\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &repo{\n\t\tdb: db,\n\t\tstop: make(chan bool),\n\t}\n\tgo r.cleanOAuthState()\n\treturn r, nil\n}", "func (db *ProductRepo) Create() (message string) {\n\tcreate := \"This is create function\"\n\treturn create\n}", "func (transactionRepo *mockTransactionRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func CreateProduct(product ProductCreationPayload, db *sql.DB) (Product, error) {\n\tvar id int\n\tresult := db.QueryRow(\"INSERT INTO products (title, price) VALUES ($1, $2) RETURNING product_id\", product.Title, product.Price)\n\terr := result.Scan(&(id))\n\tif err == nil {\n\t\treturn GetProduct(strconv.Itoa(id), db)\n\t}\n\treturn Product{}, err\n}", "func New(db *bolt.DB) Repository {\n\treturn Repository{\n\t\tdb: db,\n\t}\n}", "func (r Repository) AddProduct(product Product) bool {\n\tdb, err := sql.Open(DRIVER, SERVER)\n\n\tif err != nil {\n\t\tfmt.Println(\"Failed to establish connection to MySQL server:\", err)\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Query(\"insert into `products` \"+\n\t\t\"(title, image, description, price, rating, category) values (?, ?, ?, ?, ?, ?)\",\n\t\tproduct.Title, product.Image, product.Description, product.Price, product.Rating, product.Category)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\treturn true\n}", "func createOrUpdateProduct(p Product) (Product, error) {\n\tif p.ID == \"\" {\n\t\tp.ID = strconv.Itoa(len(data) + 1)\n\t\tp.CreatedAt = time.Now()\n\t\tdata = append(data, p)\n\t\treturn p, nil\n\t}\n\tstored, _, err := findProduct(p.ID)\n\tif err != nil {\n\t\tvar empty Product\n\t\treturn empty, err\n\t}\n\n\t//C hange found product\n\tstored.ID = p.ID\n\tstored.Name = p.Name\n\tstored.Price = p.Price\n\treturn *stored, nil\n}", "func TestResult_InsertProduct(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\tps := store.NewMockProductStore(ctrl)\n\tbs := store.NewMockBrandStore(ctrl)\n\tpsr := New(ps, bs)\n\n\ttestcases := []struct {\n\t\tproductName, brandName string\n\t\terr error\n\t}{\n\t\t{\"reebok\", \"bat\", nil},\n\t\t{\"sparten\", \"ball\", nil},\n\t}\n\n\tfor _, tc := range testcases {\n\t\tvar brandResult models.Brand\n\t\tvar brandId, productId int64\n\t\tbs.EXPECT().GetByName(tc.brandName).Return(brandResult, tc.err)\n\t\tbflag, pflag := false, false\n\t\t// if brand is not available in table\n\t\tif tc.err != nil {\n\t\t\t// create brand\n\t\t\tbs.EXPECT().InsertBrand(tc.brandName).Return(brandId, tc.err)\n\t\t\tif tc.err != nil {\n\t\t\t\tlog.Fatal(\"error in inserting brand\")\n\t\t\t}\n\t\t\tbflag = true\n\t\t}\n\t\tvar productResult models.Product\n\t\tps.EXPECT().GetByName(tc.productName).Return(productResult, tc.err)\n\t\t// if product is not available in table\n\t\tif tc.err != nil {\n\t\t\t// create product\n\t\t\tps.EXPECT().InsertProduct(tc.productName).Return(productId, tc.err)\n\t\t\tif tc.err != nil {\n\t\t\t\tlog.Fatal(\"error in inserting product\")\n\t\t\t}\n\t\t\tpflag = true\n\t\t}\n\t\t// if both product and brand are already available\n\t\tif !pflag && !bflag {\n\t\t\t_, err := psr.InsertProduct(tc.productName, tc.brandName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"error in insertion\")\n\t\t\t}\n\t\t}\n\t}\n}", "func NewRepo() (*Repo, error) {\n\tconn, err := dbconn.Connect() \n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trepo := new(Repo)\n\trepo.DB = conn\n\treturn repo, nil\n}", "func NewRepo(a *config.AppConfig, db *driver.DB) *Repository {\n\treturn &Repository{\n\t\tApp: a,\n\t\tDB: dbrepo.NewPostgresRepo(db.SQL, a),\n\t}\n}", "func RepoCreateDatabaseConnection(t DatabaseConnection) DatabaseConnection {\n\tcurrentId += 1\n\tt.Id = currentId\n\tdatabaseConnections = append(databaseConnections, t)\n\treturn t\n}", "func ProvideRepo(engine engine.Engine) Repo {\n\treturn Repo{Engine: engine}\n}", "func (userRepo *mockUserRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (pr *PsqlProduct) Create(p *product.Product) error {\n\treturn nil\n}", "func CreateProduct(w http.ResponseWriter, r *http.Request) {\n var p dynamodbservice.Product\n w.Header().Add(\"Content-Type\", \"application/json\")\n if err := json.NewDecoder(r.Body).Decode(&p); err != nil {\n http.Error(w, err.Error(), http.StatusBadRequest)\n return\n }\n\n defer r.Body.Close()\n\n if err := dynamodbservice.Items.AddProduct(p); err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n return\n }\n\n w.WriteHeader(http.StatusCreated)\n json.NewEncoder(w).Encode(p)\n}", "func NewRepo(a *config.AppConfig, db *driver.DB) *Repository {\n\treturn &Repository{\n\t\tApp: a,\n\t\tDB: dbrepo.NewPostgresRepo(db.SQL, a),\n\t}\n}", "func (repo *PlatformRepository) Create(payload *Platform) (*Platform, error) {\n\terr := repo.db.Create(payload).Error\n\n\treturn payload, err\n}", "func (c *Controller) newChartRepoHandler() cache.ResourceEventHandler {\n\tupdateFunc := func(old, new interface{}) {\n\t\t// oldChartRepo := old.(*alpha1.ChartRepo)\n\t\t// newChartRepo := new.(*alpha1.ChartRepo)\n\t\tklog.V(4).Info(\"receive new chartrepo\")\n\n\t\t// TODO: use a queue\n\t\t//go c.syncChartRepo(new)\n\n\t\tc.enqueueChartRepo(new)\n\n\t\t//if oldChartRepo.Spec.Secret != nil && newChartRepo.Spec.Secret != nil {\n\t\t//\tif oldChartRepo.Spec.Secret.Name != newChartRepo.Spec.Secret.Name {\n\t\t//\t\tc.syncChartRepo(newChartRepo)\n\t\t//\t\treturn\n\t\t//\t}\n\t\t//\tif oldChartRepo.Spec.Secret.Namespace != newChartRepo.Spec.Secret.Namespace {\n\t\t//\t\tc.syncChartRepo(newChartRepo)\n\t\t//\t\treturn\n\t\t//\t}\n\t\t//}\n\t}\n\n\tdeleteFunc := func(obj interface{}) {\n\t\tcr, ok := obj.(*alpha1.ChartRepo)\n\t\tif ok {\n\t\t\tif err := helm.RemoveRepository(cr.GetName()); err != nil {\n\t\t\t\tklog.Error(\"remove repo from helm error:\", err)\n\t\t\t}\n\t\t\tklog.Info(\"delete chartrepo: \", cr.GetName())\n\t\t}\n\t}\n\n\tfuncs := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.enqueueChartRepo,\n\t\tUpdateFunc: updateFunc,\n\t\tDeleteFunc: deleteFunc,\n\t}\n\n\treturn funcs\n}", "func Retrieve(c *gin.Context) *library.Repo {\n\treturn FromContext(c)\n}", "func InsertProduct(c *gin.Context) {\n\n\tstatus := 1\n\tmessage := \"Success\"\n\tvar rensponseInsertProduct ResponseInsertProduct\n\tvar newstocks int\n\tvar products Products\n\tvar products_arr []Products\n\tvar stock_ins Stock_Ins\n\tbuyPrice,_ := strconv.Atoi(c.PostForm(\"buy_price\"))\n\tqtY,_ := strconv.Atoi(c.PostForm(\"qty\"))\n\tcurrentdatetime := time.Now().Format(\"2006-01-02 15:04:05\")\n\tstock_ins = Stock_Ins{Sku:c.PostForm(\"sku\"),Buy_Price:buyPrice,Created_Date:currentdatetime,Qty:qtY,Kwitansi:c.PostForm(\"kwitansi\")}\n\tdb := InitDb()\n\ttx := db.Begin()\n\n\tif err := tx.Create(&stock_ins).Error; err != nil {\n\t\ttx.Rollback()\n\t\tstatus = 0\n\t\tmessage = \"failed to insert data stock_ins\"\n\t} else{\n\n\t\tdb.Where(\"sku = ?\", c.PostForm(\"sku\")).First(&products).Limit(1).Scan(&products_arr)\n\n\t\t// its new record or update record?\n\t\tif (len(products_arr) > 0){\n\n\t\t\tfor i,element := range products_arr{\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tnewstocks = element.Stocks + qtY\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := tx.Model(&products).Where(\"sku = ?\",c.PostForm(\"sku\")).Update(\"stocks\", newstocks).Error; err != nil{\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to update data products\"\n\t\t\t}\n\n\n\t\t}else{\n\t\t\t//insert to table products\n\t\t\tproducts = Products{Sku:c.PostForm(\"sku\"),Stocks:qtY,Product_name:c.PostForm(\"product_name\")}\n\t\t\tif err := tx.Create(&products).Error; err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to insert data products\"\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif status == 1 {\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status, Message:message,Data:DataInsertProduct{Stocks:newstocks, Sku:c.PostForm(\"sku\"), Product_name:c.PostForm(\"product_name\"), Buy_Price:buyPrice, Created_Date:currentdatetime}}\n\t}else{\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status,Message:message}\n\t}\n\n\t//transaction commit\n\ttx.Commit()\n\t// Close connection database\n\tdefer db.Close()\n\n\tc.JSON(200, rensponseInsertProduct)\n}", "func (classRepo *mockClassRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func New() backing.Repo {\n\treturn &Repo{}\n}", "func newRepo(r *github.Repository) Repo {\n\tvar lang string\n\tif r.Language != nil {\n\t\tlang = *r.Language\n\t} else {\n\t\tlang = \"-\"\n\t}\n\treturn Repo{*r.HTMLURL, lang, *r.StargazersCount, *r.ForksCount}\n}", "func (accountRepo *mockAccountRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (announceRepo *mockAnnounceRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func (handler *InitHandler) addRepositoriesinDB(owner, repo, description, t string) error {\n\t// add repository\n\taddrepo := database.Repositories{\n\t\tOwner: owner,\n\t\tRepo: repo,\n\t\tDescription: description,\n\t\tType: t,\n\t}\n\n\t// create repository\n\terr := database.DBConnection.Create(&addrepo).Error\n\tif err != nil {\n\t\tglog.Errorf(\"unable to create repository: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func getProducts(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println()\n\tfmt.Println(\"pulling products\")\n\tfmt.Println()\n\t//Set header content tyep to application/json\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tenableCors(&w)\n\t//Init Products var as a slice Product struct\n\tproducts := []Product{}\n\t//query sent to DB\n\tquery := \"SELECT * FROM products\"\n\n\t//rows = results of the query\n\trows, err := db.Query(query)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t\t// panic(err.Error())\n\t}\n\t// if there is NOT an error do this\n\tfor rows.Next() {\n\t\t// create a new variable and set its value to our existing struct\n\t\t//Create new struct for each rown\n\t\tvar product Product\n\t\t//scan the rows and check for discrepancies and store in \"err\" so we know what the error was for\n\t\terr := rows.Scan(&product.ProductID, &product.Name, &product.Price, &product.Description, &product.Console, &product.ImgLink, &product.ImgAlt, &product.ImgSrc)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t\t// panic(err.Error())\n\t\t}\n\t\t// append the returned values to our products variable\n\t\tproducts = append(products, product)\n\t}\n\n\tjson.NewEncoder(w).Encode(products)\n}", "func (service *Service) CreateProduct(request *restful.Request, response *restful.Response) {\n\tvar req models.ProductRequest\n\tif err := request.ReadEntity(&req); err != nil {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"unable parse request body\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to parse request body:\", err)\n\n\t\treturn\n\t}\n\n\tnewUUID, err := uuid.NewRandom()\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageServerError,\n\t\t\t\"unable to create uuid\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to create uuid:\", err)\n\n\t\treturn\n\t}\n\n\tproduct := models.Product{\n\t\tProductID: newUUID.String(),\n\t\tName: req.Name,\n\t\tDescription: req.Description,\n\t\tPrice: req.Price,\n\t\tPaymentID: req.PaymentID,\n\t\tCategoryID: req.CategoryID,\n\t\tUserID: req.UserID,\n\t\tImage: req.Image,\n\t\tUpdatedAt: time.Now().UTC(),\n\t\tCreatedAt: time.Now().UTC(),\n\t}\n\n\tcreatedProduct, err := service.server.CreateProduct(product)\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageDatabaseError,\n\t\t\t\"unable to create product\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to create product:\", err)\n\n\t\treturn\n\t}\n\n\tresult := &models.CreateProductResponse{\n\t\tResult: *createdProduct,\n\t}\n\n\twriteResponse(response, http.StatusCreated, result)\n}", "func main() {\n\n\thandler, err := NewHandler()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\t// p1 := &Product{\n\t// \tID: \"P2\",\n\t// \tName: \"IPHONE X\",\n\t// \tQuantity: 3,\n\t// }\n\n\t// newProd1, err := handler.SaveProduct(p1)\n\t// if err != nil {\n\t// \tfmt.Println(err)\n\t// \tos.Exit(1)\n\t// }\n\n\t// fmt.Println(newProd1)\n\n\t//=---------------------------\n\n\tproducts, err := handler.GetAllProduct()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfor _, p := range products {\n\t\tfmt.Println(p)\n\t}\n}", "func CreateProduct(rw http.ResponseWriter, r *http.Request) {\n\tvar product data.Product\n\terr := json.NewDecoder(r.Body).Decode(&product)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\n\terr = services.CreateProduct(&product)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\n\tjson.NewEncoder(rw).Encode(product)\n}", "func NewPostgresProductsRepository() *PostgresProductsRepository {\n\tdb, err := sql.Open(\"postgres\", \"postgres://ecommerce:mysecret@products-postgres/ecommerce-products?sslmode=disable\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err = db.Ping(); err != nil {\n\t\tpanic(err)\n\t}\n\n\trepo := &PostgresProductsRepository{\n\t\tdb,\n\t}\n\n\treturn repo\n}", "func AddProduct(p *Product, db *mongo.Client) (string, error) {\n\t//insert product p into db\n\tprodCol := db.Database(DBNAME).Collection(COLLNAME)\n\tresult, err := prodCol.InsertOne(context.TODO(), p)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.InsertedID.(primitive.ObjectID).Hex(), nil\n}", "func newTxAndBoardRepository() (tx *gorm.DB, repo *BoardRepository) {\n\ttx = orm.GetDB().Begin()\n\trepo = NewBoardRepository(tx)\n\treturn\n}", "func testRepo() *library.Repo {\n\treturn &library.Repo{\n\t\tID: new(int64),\n\t\tUserID: new(int64),\n\t\tBuildLimit: new(int64),\n\t\tTimeout: new(int64),\n\t\tCounter: new(int),\n\t\tPipelineType: new(string),\n\t\tHash: new(string),\n\t\tOrg: new(string),\n\t\tName: new(string),\n\t\tFullName: new(string),\n\t\tLink: new(string),\n\t\tClone: new(string),\n\t\tBranch: new(string),\n\t\tVisibility: new(string),\n\t\tPreviousName: new(string),\n\t\tPrivate: new(bool),\n\t\tTrusted: new(bool),\n\t\tActive: new(bool),\n\t\tAllowPull: new(bool),\n\t\tAllowPush: new(bool),\n\t\tAllowDeploy: new(bool),\n\t\tAllowTag: new(bool),\n\t\tAllowComment: new(bool),\n\t}\n}", "func CreateProduct(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n /*\n Arguments:\n * ID\n * Name\n * HeatId\n * Quantity\n * Description\n * Organization\n * Unit\n * CreatedAt\n */\n\n ID := \"product-\" + args[0]\n quantity, err := strconv.ParseFloat(args[4], 64)\n if err != nil {\n return shim.Error(err.Error())\n }\n createdAt := time.Now().Format(\"2006-01-02 15:04:05 +0000 UTC\")\n if quantity < 0 {\n return shim.Error(\"Quantity should be positive\")\n }\n\n var product = types.Product{Class: \"Product\", ID: ID, Name: args[1], HeatID: args[2], Quantity: quantity, Description: args[4], Owner: args[5], Unit: args[6], CreatedAt: createdAt, ModifiedAt: createdAt}\n\n CreatedProductBytes, _ := json.Marshal(product)\n APIstub.PutState(ID, CreatedProductBytes)\n\n return shim.Success(CreatedProductBytes)\n}", "func (p *Products) CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tproduct := r.Context().Value(KeyProduct{}).(data.Product)\n\n\tp.l.Printf(\"[DEBUG] Inserting product: %#v\\n\", product)\n\n\tdata.AddProduct(&product)\n\tw.WriteHeader(http.StatusCreated)\n}", "func init() {\n\tRepoCreateDatabaseConnection(DatabaseConnection{Name: \"Write presentation\"})\n\tRepoCreateDatabaseConnection(DatabaseConnection{Name: \"Host meetup\"})\n}", "func New(connection *gorm.DB) Interface {\n\treturn &Repository{connection: connection}\n}", "func Init(repo, ref string) (*DB, error) {\n\tr, err := git.InitRepository(repo, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb, err := newRepo(r, ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn db, nil\n}", "func (c *client) CreateRepo(r *library.Repo) error {\n\tlogrus.Tracef(\"creating repo %s in the database\", r.GetFullName())\n\n\t// cast to database type\n\trepo := database.RepoFromLibrary(r)\n\n\t// validate the necessary fields are populated\n\terr := repo.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// encrypt the fields for the repo\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/types/database#Repo.Encrypt\n\terr = repo.Encrypt(c.config.EncryptionKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to encrypt repo %s: %v\", r.GetFullName(), err)\n\t}\n\n\t// send query to the database\n\treturn c.Postgres.\n\t\tTable(constants.TableRepo).\n\t\tCreate(repo).Error\n}", "func (c *Repo) CreateRepo(w http.ResponseWriter, req *http.Request) (int, interface{}) {\n\tsctx := req.Context().Value(middlewares.SessionKey)\n\tsession, ok := sctx.(*types.Session)\n\tif !ok {\n\t\tfmt.Println(\"cant convert to session\", sctx)\n\t\treturn httputils.InternalError()\n\t}\n\n\trepo := types.Repo{}\n\n\terr := json.NewDecoder(req.Body).Decode(&repo)\n\tif err != nil {\n\t\treturn httputils.InternalError()\n\t}\n\n\trepo.Uname = session.User.Uname\n\trepo.OwnerID = session.User.ID\n\n\terr = repos.CreateBareRepo(&repo)\n\tif err != nil {\n\t\treturn http.StatusConflict, httputils.ErrorResponse([]string{\"Repo already exists\"})\n\t}\n\n\treturn http.StatusOK, nil\n}", "func (p *Products) POST(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle POST Products\")\n\n\tprod := r.Context().Value(KeyProduct{}).(*data.Product)\n\tp.l.Println(prod)\n\tp.dbConnection.InsertProduct(prod)\n}", "func (productCategory ProductCategory) create() (Entity, error) {\n\n\ten := productCategory\n\n\tif err := db.Create(&en).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := en.GetPreloadDb(false, false, nil).First(&en, en.Id).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tAsyncFire(NewEvent(\"ProductCategoryCreated\", map[string]interface{}{\"account_id\":en.AccountId, \"product_category_id\":en.Id}))\n\n\tvar newItem Entity = &en\n\n\treturn newItem, nil\n}", "func NewRepository(db *sql.DB) payment.Repository {\n\treturn &repository{gq: goqu.New(\"postgres\", db)}\n}", "func (s *Controller) handleCreateProduct(c *gin.Context) {\n\n\tvar product entity.Product\n\n\terr := c.ShouldBindJSON(&product)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\trestErr := resterrors.NewBadRequestError(\"Invalid json body\")\n\t\tc.JSON(restErr.StatusCode, restErr)\n\t\treturn\n\t}\n\n\tproductID, createErr := s.productService.CreateProduct(product)\n\tif createErr != nil {\n\t\tc.JSON(createErr.StatusCode, createErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, gin.H{\"id\": productID})\n}", "func (p *Base) Product() string { // 管理ページ\n\treturn \"https://admin.thebase.in/shop_admin/items/add\"\n}", "func NewRepo(gormDB *gorm.DB) Repo {\n\treturn &repo{\n\t\tgormDB: gormDB,\n\t}\n}", "func NewRepo(gormDB *gorm.DB) Repo {\n\treturn &repo{\n\t\tgormDB: gormDB,\n\t}\n}" ]
[ "0.6434752", "0.6356663", "0.6293656", "0.6217971", "0.6042206", "0.603253", "0.5968381", "0.5959186", "0.58726126", "0.5850399", "0.58471376", "0.5782178", "0.5719935", "0.57115084", "0.5710385", "0.56964815", "0.56876224", "0.56685615", "0.5656337", "0.564007", "0.56267875", "0.5624155", "0.56021875", "0.559436", "0.5554141", "0.55425495", "0.5529161", "0.55238914", "0.5488576", "0.54769254", "0.54719687", "0.5449548", "0.5441222", "0.54394686", "0.5434096", "0.5420605", "0.5413141", "0.5404359", "0.54005235", "0.5398242", "0.53871524", "0.5372134", "0.53373945", "0.53201854", "0.53192127", "0.5319008", "0.5304484", "0.5299507", "0.52884316", "0.5285763", "0.5283047", "0.52826923", "0.5279348", "0.5277817", "0.5275708", "0.52717614", "0.526282", "0.52570367", "0.5253213", "0.52521676", "0.5240795", "0.5239827", "0.523305", "0.522961", "0.52280855", "0.52277726", "0.5226979", "0.5226928", "0.52205044", "0.52054954", "0.52043563", "0.5196384", "0.51918966", "0.5189437", "0.5183476", "0.51754856", "0.51748395", "0.5173339", "0.5171736", "0.5171261", "0.5166142", "0.5165121", "0.51473325", "0.51430976", "0.51425284", "0.5139558", "0.5138644", "0.51347816", "0.5124886", "0.51182795", "0.5115597", "0.51062423", "0.50996894", "0.509924", "0.5097565", "0.50944704", "0.5088986", "0.5087617", "0.50860673", "0.50860673" ]
0.623252
3
FechAll will return all product
func (db *ProductRepo) FechAll() ([]*models.Product, error) { return nil, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *productGrpcClientImpl) FindAll() <-chan pkgGrpc.ServiceResult {\n\toutput := make(chan pkgGrpc.ServiceResult)\n\n\tgo func() {\n\t\tctx := metadata.NewOutgoingContext(context.Background(), nil)\n\t\targ := &pb.ProductQueryRequest{}\n\t\tresStream, err := c.client.FindAll(ctx, arg)\n\n\t\tif err != nil {\n\t\t\toutput <- pkgGrpc.ServiceResult{Error: err}\n\t\t\treturn\n\t\t}\n\n\t\tvar products domain.Products\n\n\t\tfor {\n\t\t\tres, err := resStream.Recv()\n\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\toutput <- pkgGrpc.ServiceResult{Error: err}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//stock from int32 to decimal\n\t\t\tstock, err := decimal.NewFromString(strconv.Itoa(int(res.Stock)))\n\n\t\t\tif err != nil {\n\t\t\t\toutput <- pkgGrpc.ServiceResult{Error: err}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t//price from float64 to decimal\n\t\t\tprice := decimal.NewFromFloat(res.Price)\n\n\t\t\tproduct := domain.Product{\n\t\t\t\tID: int(res.ID),\n\t\t\t\tCategoryID: int(res.CategoryID),\n\t\t\t\tName: res.Name,\n\t\t\t\tDescription: res.Description,\n\t\t\t\tImage: res.Image,\n\t\t\t\tStock: stock,\n\t\t\t\tPrice: price,\n\t\t\t\tVersion: 1,\n\t\t\t\tCreatedAt: time.Now(),\n\t\t\t\tUpdatedAt: time.Now(),\n\t\t\t}\n\n\t\t\tproducts = append(products, product)\n\t\t}\n\n\t\toutput <- pkgGrpc.ServiceResult{Result: products}\n\n\t}()\n\treturn output\n}", "func (pm *ProductModel) GetAll() (*Products, error) {\n\tres, err := pm.DB.Query(GET_ALL_PRODUCT_STMT)\n\tif err != nil {\n\t\tlog.Printf(\"error occured on getting all the products : %s\", err)\n\t}\n\n\tdefer res.Close()\n\tvar products Products\n\tfor res.Next() {\n\t\tproduct := &Product{}\n\t\tres.Scan(&product.ID, &product.ProductName, &product.Price, &product.ShortDescription)\n\t\tproducts = append(products, product)\n\t}\n\n\treturn &products, nil\n}", "func (e *engine) GetAll(c *httpEngine.ServerContext) {\n\tee, err := e.ProductLogic.GetAllProducts()\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\tc.JSON(200, ee)\n}", "func (k Keeper) GetAllProduct(ctx sdk.Context) (list []types.Product) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ProductKey))\n\titerator := sdk.KVStorePrefixIterator(store, []byte{})\n\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar val types.Product\n\t\tk.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val)\n\t\tlist = append(list, val)\n\t}\n\n\treturn\n}", "func (s *APIProductStore) GetAll() (types.APIProducts, types.Error) {\n\n\tquery := \"SELECT \" + apiProductsColumns + \" FROM api_products\"\n\n\tapiproducts, err := s.runGetAPIProductQuery(query)\n\tif err != nil {\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn types.APIProducts{}, types.NewDatabaseError(err)\n\t}\n\n\ts.db.metrics.QueryHit(apiProductsMetricLabel)\n\treturn apiproducts, nil\n}", "func (db Products) GetAll() ([]Product, error) {\n // Price-descending sort\n var temp []Product\n\n result, err := Items.Scan(&dynamodb.ScanInput{TableName: aws.String(TableName)})\n if err != nil {\n return nil, fmt.Errorf(\"Query GetAll failed:\\n%v\", err)\n }\n\n err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &temp)\n if err != nil {\n return nil, fmt.Errorf(\"Unmarshalling GetAll failed:\\n%v\", err)\n }\n\n // Manually sort the results to get a Price-descending sort\n sort.Slice(temp, func(i, j int) bool { return temp[i].Price > temp[j].Price })\n\n return temp, nil\n}", "func GetAllProducts() ([]entity.Product, error) { //passar as colunas como parametro\n\tdb := CreateConnection()\n\tdefer db.Close()\n\n\tvar products []entity.Product\n\n\tsqlStatement := `SELECT id, name, description, price FROM product`\n\n\trows, err := db.Query(sqlStatement)\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\tlog.Print(\"Unable to execute the query. \", err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar product entity.Product\n\t\tvar description, name sql.NullString\n\n\t\terr = rows.Scan(&product.ID, &name,\n\t\t\t&description, &product.Price)\n\n\t\tif err != nil {\n\t\t\tlog.Print(\"Unable to scan the row. \", err)\n\t\t}\n\t\tproduct.Description = description.String\n\t\tproduct.Name = name.String\n\n\t\tproducts = append(products, product)\n\t}\n\n\tif len(products) == 0 {\n\t\treturn nil, errors.New(\"vazio\")\n\t}\n\n\treturn products, nil\n}", "func GetAllProducts(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tvar products models.Products\n\tproducts.FindAll()\n\tmodels.SendData(w, products)\n}", "func (s *SmartContract) getAllProducts(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\t//Get user identity\n\tidentity, err := GetInvokerIdentity(stub)\n\tif err != nil {\n\t\tshim.Error(fmt.Sprintf(\"Error getting invoker identity: %s\\n\", err.Error()))\n\t}\n\n\tif len(args) != 0 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n\t// Get iterator for all entries\n\titerator, err := stub.GetStateByRange(\"\", \"\")\n\tif err != nil {\n\t\tshim.Error(fmt.Sprintf(\"Error getting state iterator: %s\", err))\n\t}\n\tdefer iterator.Close()\n\n\t// Create array\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\tfor iterator.HasNext() {\n\t\tstate, iterErr := iterator.Next()\n\t\tif iterErr != nil {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Error accessing state: %s\", err))\n\t\t}\n\n\t\t// Don't return products issuer isn't a party to\n\t\tvar product Product\n\t\terr = json.Unmarshal(state.Value, &product)\n\t\tif err != nil && err.Error() != \"Not a Product\" {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tif product.AccessibleBy(identity) {\n\t\t\tif buffer.Len() != 1 {\n\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t}\n\t\t\tbuffer.WriteString(string(state.Value))\n\t\t}\n\t}\n\tbuffer.WriteString(\"]\")\n\n\treturn shim.Success(buffer.Bytes())\n}", "func (q contentUnitDerivationQuery) All(exec boil.Executor) (ContentUnitDerivationSlice, error) {\n\tvar o []*ContentUnitDerivation\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"mdbmodels: failed to assign all query results to ContentUnitDerivation slice\")\n\t}\n\n\treturn o, nil\n}", "func (q *productQueryInMemory) FindAll() <-chan QueryResult {\n\toutput := make(chan QueryResult)\n\tgo func() {\n\t\tdefer close(output)\n\n\t\tvar products model.Products\n\t\tfor _, v := range q.db {\n\t\t\tproducts = append(products, *v)\n\t\t}\n\n\t\toutput <- QueryResult{Result: products}\n\t}()\n\treturn output\n}", "func ViewAllProducts(c *gin.Context) {\n\tvar prod []Products\n\tdb := DbConn()\n\terr := db.Find(&prod).Error\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tc.JSON(http.StatusServiceUnavailable, err)\n\t}\n\n\tc.JSON(http.StatusOK, prod)\n}", "func (d *Dao) AllProducts(c context.Context) (res []*model.Product, err error) {\n\tvar rows *xsql.Rows\n\tif rows, err = d.db.Query(c, _allProductsSQL); err != nil {\n\t\tlog.Error(\"d.AllProducts.Query error(%+v), sql(%s)\", err, _allProductsSQL)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar p = &model.Product{}\n\t\tif err = rows.Scan(&p.ID, &p.Name, &p.GroupIDs, &p.Ctime, &p.Mtime); err != nil {\n\t\t\tlog.Error(\"d.AllProducts.Scan error(%+v), sql(%s)\", err, _allProductsSQL)\n\t\t\treturn\n\t\t}\n\t\tif p.GroupIDs != \"\" {\n\t\t\tvar gids []int64\n\t\t\tif gids, err = xstr.SplitInts(p.GroupIDs); err != nil {\n\t\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, p.GroupIDs)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif p.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tres = append(res, p)\n\t}\n\terr = rows.Err()\n\treturn\n}", "func (e Endpoints) GetAllProduct(ctx context.Context) (allRecordResp []*models.Product, err error) {\n\trequest := GetAllProductRequest{}\n\tresponse, err := e.GetAllProductEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(GetAllProductResponse).AllRecordResp, response.(GetAllProductResponse).Err\n}", "func (s *PostgresStorage) FindAll(ctx context.Context, params *product.FindAllProductsParams) ([]*product.Product, *types.Error) {\n\n\tproducts := []*product.Product{}\n\twhere := `\"deleted_at\" IS NULL`\n\n\tif params.ProductID != 0 {\n\t\twhere += ` AND \"id\" = :productId`\n\t}\n\tif params.Name != \"\" {\n\t\twhere += ` AND \"name\" = :name`\n\t}\n\tif params.Search != \"\" {\n\t\twhere += ` AND \"name\" ILIKE :search`\n\t}\n\tif params.Page != 0 && params.Limit != 0 {\n\t\twhere = fmt.Sprintf(`%s ORDER BY \"id\" DESC LIMIT :limit OFFSET :offset`, where)\n\t} else {\n\t\twhere = fmt.Sprintf(`%s ORDER BY \"id\" DESC`, where)\n\t}\n\n\terr := s.Storage.Where(ctx, &products, where, map[string]interface{}{\n\t\t\"productId\": params.ProductID,\n\t\t\"name\": params.Name,\n\t\t\"limit\": params.Limit,\n\t\t\"search\": \"%\" + params.Search + \"%\",\n\t\t\"offset\": ((params.Page - 1) * params.Limit),\n\t})\n\tif err != nil {\n\t\treturn nil, &types.Error{\n\t\t\tPath: \".ProductPostgresStorage->FindAll()\",\n\t\t\tMessage: err.Error(),\n\t\t\tError: err,\n\t\t\tType: \"pq-error\",\n\t\t}\n\t}\n\n\treturn products, nil\n}", "func (fdq *FurnitureDetailQuery) All(ctx context.Context) ([]*FurnitureDetail, error) {\n\tif err := fdq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn fdq.sqlAll(ctx)\n}", "func (p *Products) ListAll(rw http.ResponseWriter, req *http.Request) {\n\tp.log.Println(\"[GET] /products\")\n\n\tlistOfProducts := data.GetProducts()\n\n\terr := data.ToJSON(listOfProducts, rw)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func GetAllProducts(limit int, offset int) []Product {\n\tdata := []Product{}\n\tdatabase.SQL.Limit(limit).Offset(offset).Find(&data)\n\treturn data\n}", "func (p *Products) ListAll(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET all products\")\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tprodList, err := p.dbConnection.GetAllProducts()\n\tif err != nil {\n\t\tp.l.Println(err)\n\t}\n\terr = prodList.ToJSON(w)\n\tif err != nil {\n\t\thttp.Error(w, \"Unable to marshal json.\", http.StatusInternalServerError)\n\t}\n\n}", "func (m *ProductModel) AllProducts() ([]Product, error) {\n\tvar products []Product\n\terr := db.C(PRODUCT).Find(bson.M{}).All(&products)\n\treturn products, err\n}", "func GetAllProducts(db *sql.DB) []Product {\n\treturn ParseProducts(\"SELECT product_id, title, price, inventory_count FROM products_view\", db)\n}", "func (service *Service) GetAllProduct(request *restful.Request, response *restful.Response) {\n\tdbResult, err := service.server.GetAllProduct()\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageDatabaseError,\n\t\t\t\"unable to get all product\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to get all product:\", err)\n\n\t\treturn\n\t}\n\n\tresult := &models.GetProductsResponse{\n\t\tResult: dbResult,\n\t}\n\n\twriteResponse(response, http.StatusOK, result)\n}", "func (s BmProductaggdataStorage) GetAll(r api2go.Request, skip int, take int) []*BmModel.Productaggregation {\n\tin := BmModel.Productaggregation{}\n\tvar out []BmModel.Productaggregation\n\terr := s.db.FindMulti(r, &in, &out, skip, take)\n\tif err == nil {\n\t\tvar tmp []*BmModel.Productaggregation\n\t\tfor i := 0; i < len(out); i++ {\n\t\t\tptr := out[i]\n\t\t\ts.db.ResetIdWithId_(&ptr)\n\t\t\ttmp = append(tmp, &ptr)\n\t\t}\n\t\treturn tmp\n\t} else {\n\t\treturn nil //make(map[string]*BmModel.Productaggregation)\n\t}\n}", "func (t *ProductChaincode) queryProducts(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tit, err := stub.GetStateByPartialCompositeKey(productIndex, []string{})\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer it.Close()\n\n\tentries := []Product{}\n\tfor it.HasNext() {\n\t\tresponse, err := it.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tentry := Product{}\n\n\t\tif err := entry.FillFromLedgerValue(response.Value); err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\t_, compositeKeyParts, err := stub.SplitCompositeKey(response.Key)\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tif err := entry.FillFromCompositeKeyParts(compositeKeyParts); err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tentries = append(entries, entry)\n\t}\n\n\tresult, err := json.Marshal(entries)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\treturn shim.Success(result)\n}", "func Test_GetAllAldoZunkasiteProduct(t *testing.T) {\n\tzunkaProducts, err := getAllAldoZunkasiteProducts()\n\tif err != nil {\n\t\tt.Errorf(\"Failed. %s\", err)\n\t}\n\t// Some product.\n\t// log.Printf(\"zunkaProducts: %+v\", zunkaProducts)\n\tif len(zunkaProducts) == 0 {\n\t\tt.Errorf(\"Received no zunkasite aldo products len = 0.\")\n\t}\n\t// MongodbId.\n\tif len(zunkaProducts[0].MongodbId) != 24 {\n\t\tt.Errorf(\"Invalid MongodbId: %v\", zunkaProducts[0].MongodbId)\n\t}\n\t// Code.\n\tif zunkaProducts[0].Code == \"\" {\n\t\tt.Errorf(\"Invalid code: %v\", zunkaProducts[0].Code)\n\t}\n\t// Price.\n\tif zunkaProducts[0].DealerProductPrice < 100 {\n\t\tt.Errorf(\"Invalid price: %v\", zunkaProducts[0].DealerProductPrice)\n\t}\n\t// Quantity.\n\tif zunkaProducts[0].StoreProductQtd < 0 {\n\t\tt.Errorf(\"Invalid quantity: %v\", zunkaProducts[0].StoreProductQtd)\n\t}\n}", "func (q ticketQuery) All(ctx context.Context, exec boil.ContextExecutor) (TicketSlice, error) {\n\tvar o []*Ticket\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 Ticket slice\")\n\t}\n\n\treturn o, nil\n}", "func All(products []Product, predicate func(Product) bool) bool {\n\tfor _, p := range products {\n\t\tif !predicate(p) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (cq *CartQuery) All(ctx context.Context) ([]*Cart, error) {\n\tif err := cq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cq.sqlAll(ctx)\n}", "func (gq *GoodsQuery) All(ctx context.Context) ([]*Goods, error) {\n\tif err := gq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn gq.gremlinAll(ctx)\n}", "func (cos *ComicService) All(params *ComicParams) ([]Comic, error) {\n\twrap, _, err := cos.AllWrapped(params)\n\treturn wrap.Data.Results, err\n}", "func (fdq *FurnitureDetailQuery) AllX(ctx context.Context) []*FurnitureDetail {\n\tfds, err := fdq.All(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fds\n}", "func (q cmfTurntableQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFTurntableSlice, error) {\n\tvar o []*CMFTurntable\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 CMFTurntable slice\")\n\t}\n\n\tif len(cmfTurntableAfterSelectHooks) != 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 AllProductsEndpoint(w http.ResponseWriter, r *http.Request) {\n\tproducts, err := dao.FindAllProducts()\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trespondWithJson(w, http.StatusOK, products)\n}", "func returnAllFacts(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar facts []Fact\n\n\tresult, err := db.Query(\"SELECT * FROM Facts\")\n\tif err != nil {\n\t\tflushResponseWriter(w, 0)\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\n\tfor result.Next() {\n\t\tvar fact Fact\n\t\terr := result.Scan(&fact.ID, &fact.FactType, &fact.Content)\n\t\tif err != nil {\n\t\t\tflushResponseWriter(w, 0)\n\t\t\tpanic(err.Error())\n\t\t}\n\t\tfacts = append(facts, fact)\n\t}\n\n\tw.WriteHeader(http.StatusOK) //200 to client\n\tjson.NewEncoder(w).Encode(facts)\n}", "func (s *SmartContract) QueryAllForexs(ctx contractapi.TransactionContextInterface) ([]QueryResult, error) {\n\tstartKey := \"\"\n\tendKey := \"\"\n\n\tresultsIterator, err := ctx.GetStub().GetStateByRange(startKey, endKey)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resultsIterator.Close()\n\n\tresults := []QueryResult{}\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tforex := new(Forex)\n\t\t_ = json.Unmarshal(queryResponse.Value, forex)\n\n\t\tqueryResult := QueryResult{Key: queryResponse.Key, Record: forex}\n\t\tresults = append(results, queryResult)\n\t}\n\n\treturn results, nil\n}", "func (q trainingCostQuery) All(ctx context.Context, exec boil.ContextExecutor) (TrainingCostSlice, error) {\n\tvar o []*TrainingCost\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 TrainingCost slice\")\n\t}\n\n\tif len(trainingCostAfterSelectHooks) != 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 getAllItem() ([]ForexData, error) {\n\tparams := &dynamodb.ScanInput{\n\t\tTableName: aws.String(\"Forextable\"),\n\t}\n\tresult, err := db.Scan(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Items == nil {\n\t\treturn nil, nil\n\t}\n\n\tforexItems := []ForexData{}\n\terr = dynamodbattribute.UnmarshalListOfMaps(result.Items, &forexItems)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn forexItems, nil\n\n}", "func FindAll() ([]entity.Hechizo, error) {\n\n\tlog.Println(\"---- Consulta FindAll ----\")\n\tdb := dbUtils.Connect()\n\tdefer dbUtils.Close(db)\n\n\tvar id int64\n\tvar mana, counter int\n\tvar nombre string\n\n\tquery := fmt.Sprintf(\"SELECT * FROM %v\", tabla)\n\tresultQuery, error := db.Query(query)\n\n\thechizos := make([]entity.Hechizo, 0)\n\tif error != nil {\n\t\treturn hechizos, error\n\t}\n\n\tfor resultQuery.Next() {\n\n\t\terrorSelect := resultQuery.Scan(&id, &nombre, &mana)\n\t\tif errorSelect != nil {\n\t\t\tlog.Println(errorSelect)\n\t\t\tcontinue\n\t\t}\n\t\tcounter++\n\t\thechizosDb := entity.Hechizo{Id: id, Nombre: nombre, Mana: mana}\n\t\thechizos = append(hechizos, hechizosDb)\n\t}\n\treturn hechizos, nil\n}", "func (rq *ReceiptQuery) All(ctx context.Context) ([]*Receipt, error) {\n\tif err := rq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn rq.sqlAll(ctx)\n}", "func (q cmfUserSuperQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFUserSuperSlice, error) {\n\tvar o []*CMFUserSuper\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 CMFUserSuper slice\")\n\t}\n\n\tif len(cmfUserSuperAfterSelectHooks) != 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 channelQuery) All(ctx context.Context, exec boil.ContextExecutor) (ChannelSlice, error) {\n\tvar o []*Channel\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 Channel slice\")\n\t}\n\n\tif len(channelAfterSelectHooks) != 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 exchangeCurrencyQuery) All(exec boil.Executor) (ExchangeCurrencySlice, error) {\n\tvar o []*ExchangeCurrency\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to ExchangeCurrency slice\")\n\t}\n\n\tif len(exchangeCurrencyAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(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 recipeAdditiveQuery) All(ctx context.Context, exec boil.ContextExecutor) (RecipeAdditiveSlice, error) {\n\tvar o []*RecipeAdditive\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 RecipeAdditive slice\")\n\t}\n\n\tif len(recipeAdditiveAfterSelectHooks) != 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 GetAllFood() ([]GoodsBrief, error) {\n\tallFood, err := GetAllGoods(\"food\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn allFood, nil\n}", "func (cq *CartQuery) AllX(ctx context.Context) []*Cart {\n\tcs, err := cq.All(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cs\n}", "func (h *Temperature) All(ctx echo.Context) error {\r\n\tdeviceID, err := strconv.ParseInt(ctx.Param(\"deviceID\"), 10, 64)\r\n\tif err != nil {\r\n\t\treturn echo.ErrBadRequest\r\n\t}\r\n\r\n\ttemperatures, err := h.storage.All(deviceID)\r\n\tif err != nil {\r\n\t\treturn echo.ErrBadRequest\r\n\t}\r\n\treturn ctx.JSON(http.StatusOK, temperatures)\r\n}", "func (q withdrawalCryptoQuery) All(ctx context.Context, exec boil.ContextExecutor) (WithdrawalCryptoSlice, error) {\n\tvar o []*WithdrawalCrypto\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"sqlite3: failed to assign all query results to WithdrawalCrypto slice\")\n\t}\n\n\tif len(withdrawalCryptoAfterSelectHooks) != 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 currencyQuery) All(exec boil.Executor) (CurrencySlice, error) {\n\tvar o []*Currency\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Currency slice\")\n\t}\n\n\tif len(currencyAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(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 shelfQuery) All() (ShelfSlice, error) {\n\tvar o ShelfSlice\n\n\terr := q.Bind(&o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Shelf slice\")\n\t}\n\n\tif len(shelfAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(queries.GetExecutor(q.Query)); 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 GetAllAvailableProducts(db *sql.DB) []Product {\n\treturn ParseProducts(\"SELECT product_id, title, price, inventory_count FROM products_view WHERE inventory_count > 0\", db)\n}", "func (h *Handler) All(e *emptypb.Empty, s protobufs.HackerNews_AllServer) error {\n\titems, err := h.reader.GetAllItems(s.Context())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getAllItems: %w\", err)\n\t}\n\n\tfor _, item := range items {\n\t\ts.Send(grpc.ToProto(item))\n\t}\n\n\treturn nil\n}", "func GetAllProducts(rw http.ResponseWriter, r *http.Request) {\n\tproducts, err := services.GetAllProducts()\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\terr = json.NewEncoder(rw).Encode(products)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n}", "func (q featureRelationshipQuery) All() (FeatureRelationshipSlice, error) {\n\tvar o FeatureRelationshipSlice\n\n\terr := q.Bind(&o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"chado: failed to assign all query results to FeatureRelationship slice\")\n\t}\n\n\tif len(featureRelationshipAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(queries.GetExecutor(q.Query)); 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 (rq *ReceiptQuery) AllX(ctx context.Context) []*Receipt {\n\trs, err := rq.All(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn rs\n}", "func Get(w http.ResponseWriter, r *http.Request) {\n\tvar productList []Product\n\tm := map[string]interface{}{}\n\tquery := \"select productid,product_active,product_description,product_name,product_price from products\"\n\titerable := cassandra.Session.Query(query).Iter()\n\tfor iterable.MapScan(m) {\n\t\tproductList = append(productList, Product{\n\t\t\tID: m[\"productid\"].(gocql.UUID),\n\t\t\tActive: m[\"product_active\"].(bool),\n\t\t\tDescript: m[\"product_description\"].(string),\n\t\t\tName: m[\"product_name\"].(string),\n\t\t\tPrice: m[\"product_price\"].(float64),\n\t\t})\n\t\tm = map[string]interface{}{}\n\t}\n\tsetupResponse(&w, r)\n\tjson.NewEncoder(w).Encode(AllProductsResponse{Products: productList})\n}", "func (retProduct) List(ctx context.Context, db *sqlx.DB) ([]Product, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.product.list\")\n\tdefer span.End()\n\n\tproducts := []Product{}\n\tconst q = `SELECT\n\t\t\tp.*,\n\t\t\tCOALESCE(SUM(s.quantity) ,0) AS sold,\n\t\t\tCOALESCE(SUM(s.paid), 0) AS revenue\n\t\tFROM products AS p\n\t\tLEFT JOIN sales AS s ON p.product_id = s.product_id\n\t\tGROUP BY p.product_id`\n\n\tif err := db.SelectContext(ctx, &products, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting products\")\n\t}\n\n\treturn products, nil\n}", "func (q offerQuery) All(exec boil.Executor) (OfferSlice, error) {\n\tvar o []*Offer\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"stellarcore: failed to assign all query results to Offer slice\")\n\t}\n\n\tif len(offerAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(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 (sq *ShopQuery) AllX(ctx context.Context) []*Shop {\n\tsSlice, err := sq.All(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn sSlice\n}", "func (s *Service) GetAllProductSupplier() ([]nmodel.ProductSupplier, error) {\n\tresult, err := s.Repository.GetAllProductSupplier()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (f FeatureFlag) All() (features []FeatureFlag, err error) {\n\t_, err = db.GetDB().Select(&features, \"SELECT * FROM FeatureFlags\")\n\treturn features, err\n}", "func (q cmfBalanceChargeAdminQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFBalanceChargeAdminSlice, error) {\n\tvar o []*CMFBalanceChargeAdmin\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 CMFBalanceChargeAdmin slice\")\n\t}\n\n\tif len(cmfBalanceChargeAdminAfterSelectHooks) != 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 itemQuery) All(ctx context.Context, exec boil.ContextExecutor) (ItemSlice, error) {\n\tvar o []*Item\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 Item slice\")\n\t}\n\n\treturn o, nil\n}", "func (q vendorQuery) All(ctx context.Context, exec boil.ContextExecutor) (VendorSlice, error) {\n\tvar o []*Vendor\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 Vendor slice\")\n\t}\n\n\tif len(vendorAfterSelectHooks) != 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 storeQuery) All(ctx context.Context, exec boil.ContextExecutor) (StoreSlice, error) {\n\tvar o []*Store\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 Store slice\")\n\t}\n\n\treturn o, nil\n}", "func (purchase *Purchase) GetAll() ([]Purchase, error) {\n\treturn nil, nil\n}", "func (t *EnergyMarket) getProductOfferings(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\tvar queryString string\n\tvar err error\n\n\tqueryString = args[0]\n\tif err != nil {\n\t\treturn shim.Error(\"query string not provided\")\n\t}\n\n\tresultsIterator, err := stub.GetQueryResult(queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tobjs, err := getListResult(resultsIterator, stub)\n\tif err != nil {\n\t\treturn shim.Error(\"getListResult failed\")\n\t}\n\n\treturn shim.Success(objs)\n}", "func (q cmfSlideItemQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFSlideItemSlice, error) {\n\tvar o []*CMFSlideItem\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 CMFSlideItem slice\")\n\t}\n\n\tif len(cmfSlideItemAfterSelectHooks) != 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 (r ServiceMock) GetAll() []stocks.Entity {\n\treturn stockList\n}", "func (ch *CartHandler) Query(w http.ResponseWriter, r *http.Request) {\n\n\tp, err := ch.Cart.FetchAll()\n\tif err != nil {\n\t\tRespondWithError(w, http.StatusInternalServerError, err)\n\t}\n\n\tRespond(w, http.StatusOK, p)\n}", "func (hq *HarborQuery) All(ctx context.Context) ([]*Harbor, error) {\n\tif err := hq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn hq.sqlAll(ctx)\n}", "func (q utxoQuery) All(ctx context.Context, exec boil.ContextExecutor) (UtxoSlice, error) {\n\tvar o []*Utxo\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 Utxo slice\")\n\t}\n\n\tif len(utxoAfterSelectHooks) != 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 mempoolBinQuery) All(ctx context.Context, exec boil.ContextExecutor) (MempoolBinSlice, error) {\n\tvar o []*MempoolBin\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 MempoolBin slice\")\n\t}\n\n\treturn o, nil\n}", "func (store *DynamoDBFeatureStore) All(kind ld.VersionedDataKind) (map[string]ld.VersionedData, error) {\n\tvar items []map[string]*dynamodb.AttributeValue\n\n\terr := store.Client.QueryPages(&dynamodb.QueryInput{\n\t\tTableName: aws.String(store.Table),\n\t\tConsistentRead: aws.Bool(true),\n\t\tKeyConditions: map[string]*dynamodb.Condition{\n\t\t\ttablePartitionKey: {\n\t\t\t\tComparisonOperator: aws.String(\"EQ\"),\n\t\t\t\tAttributeValueList: []*dynamodb.AttributeValue{\n\t\t\t\t\t{S: aws.String(kind.GetNamespace())},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, func(out *dynamodb.QueryOutput, lastPage bool) bool {\n\t\titems = append(items, out.Items...)\n\t\treturn !lastPage\n\t})\n\tif err != nil {\n\t\tstore.Logger.Printf(\"ERROR: Failed to get all %q items: %s\", kind.GetNamespace(), err)\n\t\treturn nil, err\n\t}\n\n\tresults := make(map[string]ld.VersionedData)\n\n\tfor _, i := range items {\n\t\titem, err := unmarshalItem(kind, i)\n\t\tif err != nil {\n\t\t\tstore.Logger.Printf(\"ERROR: Failed to unmarshal item: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif !item.IsDeleted() {\n\t\t\tresults[item.GetKey()] = item\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (col *Collection) All() chan map[string]interface{} {\n\tcount := col.Count()\n\tc := make(chan map[string]interface{}, count)\n\tif count == 0 {\n\t\tclose(c)\n\t\treturn c\n\t}\n\tpartDiv := count / col.db.numParts\n\tfor i := 0; i < col.db.numParts; i++ {\n\t\tpart := col.parts[i]\n\t\tfor j := 0; j < partDiv; j++ {\n\t\t\tfor d := range part.All(j, partDiv) {\n\t\t\t\tdoc := make(map[string]interface{})\n\t\t\t\tjson.Unmarshal(d.Data, &doc)\n\t\t\t\tdoc[\"_id\"] = d.Id\n\t\t\t\tc <- doc\n\t\t\t}\n\t\t}\n\t}\n\tclose(c)\n\treturn c\n}", "func (q shelfQuery) AllP() ShelfSlice {\n\to, err := q.All()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn o\n}", "func (sq *ShopQuery) All(ctx context.Context) ([]*Shop, error) {\n\treturn sq.sqlAll(ctx)\n}", "func (s *Service) Products(ctx context.Context) ([]*types.Products, error) {\n\n\titems := make([]*types.Products, 0)\n\tsql := `SELECT id, name, price, qty FROM products WHERE active = true ORDER BY id LIMIT 500;`\n\trows, err := s.pool.Query(ctx, sql)\n\n\tif errors.Is(err, pgx.ErrNoRows) {\n\t\treturn items, nil\n\t}\n\n\tif err != nil {\n\t\treturn nil, ErrInternal\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\titem := &types.Products{}\n\t\terr = rows.Scan(&item.ID, &item.Name, &item.Price, &item.Qty)\n\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\treturn items, nil\n}", "func (pq *PrizeQuery) All(ctx context.Context) ([]*Prize, error) {\n\tif err := pq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn pq.sqlAll(ctx)\n}", "func (c *Client) Products(ctx context.Context, filter map[string]string) <-chan *Product {\n\tprodChan := make(chan *Product)\n\n\tgo func() {\n\t\tdefer close(prodChan)\n\n\t\tc.ProductsTrampoline(filter, func(index uint, product *Product) error {\n\t\t\t// FIXME silent error. maybe prodChan <- nil ?\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn errors.New(\"break\")\n\t\t\tcase prodChan <- product:\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}()\n\n\treturn prodChan\n}", "func (q cmfFamiliesPolicyQuery) All(ctx context.Context, exec boil.ContextExecutor) (CMFFamiliesPolicySlice, error) {\n\tvar o []*CMFFamiliesPolicy\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 CMFFamiliesPolicy slice\")\n\t}\n\n\tif len(cmfFamiliesPolicyAfterSelectHooks) != 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 friendshipQuery) All(ctx context.Context, exec boil.ContextExecutor) (FriendshipSlice, error) {\n\tvar o []*Friendship\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 Friendship slice\")\n\t}\n\n\tif len(friendshipAfterSelectHooks) != 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 btcTXOutputQuery) All(ctx context.Context, exec boil.ContextExecutor) (BTCTXOutputSlice, error) {\n\tvar o []*BTCTXOutput\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 BTCTXOutput slice\")\n\t}\n\n\treturn o, nil\n}", "func (s *Service) GetAll() ([]FoodGenre, error) {\n\tdb := database.GetDB()\n\tvar food_genres []FoodGenre\n\n\t// SELECT * FROM food_genres;\n\tif err := db.Find(&food_genres).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn food_genres, nil\n}", "func (q filesStorageQuery) All(exec boil.Executor) (FilesStorageSlice, error) {\n\tvar o []*FilesStorage\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to FilesStorage slice\")\n\t}\n\n\tif len(filesStorageAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(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 GetAll(ID string) []*Labo {\n\tconst (\n\t\tCSS string = \".product-listing .product-container > p a\"\n\t)\n\tvar (\n\t\tdoc *goquery.Document\n\t\terr error\n\t\tl []*Labo\n\t\tok bool\n\t\treq *http.Request\n\t\tres *http.Response\n\t\ts *goquery.Selection\n\t)\n\treq, err = http.NewRequest(http.MethodGet, fmt.Sprintf(\"%s%s\", storeCategoryURI, ID), nil)\n\tres, err = client.Do(req)\n\tok = (err == nil)\n\tif !ok {\n\t\treturn nil\n\t}\n\tok = (res.StatusCode == http.StatusOK)\n\tif !ok {\n\t\treturn nil\n\t}\n\tdoc, err = goquery.NewDocumentFromResponse(res)\n\tok = (err == nil)\n\tif !ok {\n\t\treturn nil\n\t}\n\ts = doc.Find(CSS)\n\tok = (s.Length() > 0)\n\tif !ok {\n\t\treturn nil\n\t}\n\ts.Each(func(i int, s *goquery.Selection) {\n\t\thref, exists := s.Attr(attrHref)\n\t\tif !exists {\n\t\t\treturn\n\t\t}\n\t\tURL, err := url.Parse(href)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tID := URL.Query().Get(uriQueryParamProductID)\n\t\tlabo := Get(ID)\n\t\tif labo == nil {\n\t\t\treturn\n\t\t}\n\t\tl = append(l, labo)\n\t})\n\treturn l\n}", "func FetchAll(c *gin.Context) {\n\tvar recipies []model.Recipe\n\tmodel.DB.Find(&recipies)\n\n\tif len(recipies) <= 0 {\n\t\tc.JSON(http.StatusNoContent, gin.H{\"message\": \"no recipes found\"})\n\t\treturn\n\t}\n\n\tvar descriptions []*model.RecipeDescription\n\tfor _, r := range recipies {\n\t\tmodel.DB.Model(&r).Related(&r.Resources)\n\t\tdescriptions = append(descriptions, r.Description())\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"message\": strconv.Itoa(len(descriptions)) + \" recipes found\", \"data\": descriptions})\n}", "func computeBasket(w http.ResponseWriter, r *http.Request) {\n\t// List of id products separates by ,\n\tlistProducts := strings.Split(r.FormValue(\"products\"),\",\")\n\t// List of quantity of each product separates by ,\n\tproducts := make([]product,0,len(listProducts))\n\tfor i,q := range strings.Split(r.FormValue(\"quantities\"),\",\") {\n\t\tif quantity,err := strconv.ParseInt(q,10,32) ; err == nil {\n\t\t\tproducts = append(products,product{listProducts[i],int(quantity)})\n\t\t}\n\t}\n\n\tw.Write([]byte(\"0\"))\n\n}", "func (h *Handler) FetchAll(c echo.Context) error {\n\tallRecs, err := h.Store.FetchAll()\n\tif err != nil {\n\t\treturn c.JSON(http.StatusInternalServerError, err)\n\t}\n\n\treturn c.JSON(http.StatusOK, allRecs)\n}", "func main() {\n\n\tfmt.Print(products([]int{1, 2, 3, 4, 5}))\n}", "func (f *Factory) Fees() sdk.Coins { return f.fees }", "func ReadProducts() {\n\tvar myProduct = make([]Product, 0)\n\tstorage.DB().Find(&myProduct)\n\tfor _, product := range myProduct {\n\t\tfmt.Printf(\"ID: %+v | Name: %+v | Price: %+v | Observations: %+v | CreatedAt: %+v | UpdatedAt: %+v | DeletedAt: %+v \\n\\n\", product.ID, product.Name, product.Price, product.Observations.String, product.CreatedAt, product.UpdatedAt, product.DeletedAt.Time)\n\t}\n}", "func (q premiumSlotQuery) All(ctx context.Context, exec boil.ContextExecutor) (PremiumSlotSlice, error) {\n\tvar o []*PremiumSlot\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 PremiumSlot slice\")\n\t}\n\n\treturn o, nil\n}", "func (s *Service) FindAll(ctx context.Context) ([]eh.Entity, error) {\n\treturn nil, errors.New(\"not implemented\")\n}", "func (q descriptionQuery) All(ctx context.Context, exec boil.ContextExecutor) (DescriptionSlice, error) {\n\tvar o []*Description\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 Description slice\")\n\t}\n\n\tif len(descriptionAfterSelectHooks) != 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 FindProducts(c *gin.Context) {\n\n\tok, res := dao.FindAll(\"product\", \"linx\")\n\tif !ok {\n\t\tc.JSON(http.StatusNotFound, res)\n\n\t}\n\tc.JSON(http.StatusOK, res)\n}", "func (deq *DentalExpenseQuery) All(ctx context.Context) ([]*DentalExpense, error) {\n\tif err := deq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn deq.sqlAll(ctx)\n}", "func GetProducts(c *fiber.Ctx) error {\n\tdb := database.Connection()\n\treturn models.GetProducts(db, c)\n}", "func (q stockQuery) All() (StockSlice, error) {\n\tvar o []*Stock\n\n\terr := q.Bind(&o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Stock slice\")\n\t}\n\n\treturn o, nil\n}", "func (s *Stock) FindAll() ([]model.Model, *errors.Error) {\n\trows, err := s.db.Query(\"SELECT SKU, NAME, QUANTITY, BUY_PRICE, SELL_PRICE FROM stock ORDER BY SKU ASC\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, 0)\n\t}\n\tdefer rows.Close()\n\n\tvar sku, name sql.NullString\n\tvar quantity sql.NullInt64\n\tvar buyPrice, sellPrice sql.NullFloat64\n\n\tvar returnedRow []model.Model\n\tvar firstScan = true\n\tfor rows.Next() {\n\t\terr := rows.Scan(&sku, &name, &quantity, &buyPrice, &sellPrice)\n\t\tfirstScan = false\n\t\tif err != nil {\n\t\t\tvar returnedErr error\n\t\t\tif firstScan && err == sql.ErrNoRows {\n\t\t\t\treturnedErr = ErrNotFound\n\t\t\t} else {\n\t\t\t\treturnedErr = err\n\t\t\t}\n\t\t\treturn nil, errors.Wrap(returnedErr, 0)\n\t\t}\n\t\tskuValue := sku.String\n\t\tnameValue := name.String\n\t\tquantityValue := quantity.Int64\n\t\tbuyPriceValue := buyPrice.Float64\n\t\tsellPriceValue := sellPrice.Float64\n\n\t\tstockModel := &model.Stock{\n\t\t\tSku: skuValue,\n\t\t\tName: nameValue,\n\t\t\tQuantity: quantityValue,\n\t\t\tBuyPrice: buyPriceValue,\n\t\t\tSellPrice: sellPriceValue,\n\t\t}\n\t\tstockModel.SetLoadedFromStorage(true)\n\n\t\treturnedRow = append(returnedRow, stockModel)\n\t}\n\treturn returnedRow, nil\n}", "func (q premiumCodeQuery) All(ctx context.Context, exec boil.ContextExecutor) (PremiumCodeSlice, error) {\n\tvar o []*PremiumCode\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 PremiumCode slice\")\n\t}\n\n\treturn o, nil\n}" ]
[ "0.6839194", "0.6555927", "0.65355545", "0.6275736", "0.62427795", "0.6228574", "0.6188044", "0.6157728", "0.6079156", "0.5976212", "0.5969738", "0.59371144", "0.59328425", "0.5881353", "0.5785129", "0.57843214", "0.5767573", "0.5766538", "0.5763392", "0.5757627", "0.5757534", "0.57546306", "0.5736975", "0.5733405", "0.5730413", "0.56950176", "0.56675214", "0.5653717", "0.5615773", "0.5610942", "0.5571544", "0.55678123", "0.5556566", "0.55556875", "0.55497307", "0.5508307", "0.55081016", "0.5487178", "0.5479617", "0.5463029", "0.54599565", "0.544419", "0.5444149", "0.54394066", "0.5433398", "0.54261583", "0.54249746", "0.54245764", "0.5414347", "0.5401586", "0.53945476", "0.5390875", "0.53875303", "0.5385027", "0.53789365", "0.5374111", "0.53696245", "0.5364226", "0.5360757", "0.5357166", "0.5353072", "0.5352772", "0.5352562", "0.53452796", "0.532786", "0.5323021", "0.53209835", "0.5320957", "0.530929", "0.5289481", "0.52885216", "0.5279301", "0.527699", "0.5272537", "0.5267553", "0.5240661", "0.5236107", "0.52280164", "0.5224746", "0.5223449", "0.5213025", "0.52117366", "0.5209223", "0.51983356", "0.519571", "0.518617", "0.51802385", "0.5179774", "0.51784605", "0.51722294", "0.515624", "0.5153901", "0.5150751", "0.5150227", "0.51473415", "0.51466435", "0.5133867", "0.5132965", "0.5132263", "0.5131519" ]
0.8450363
0
Create will deal with creating new product
func (db *ProductRepo) Create() (message string) { create := "This is create function" return create }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (main *Main) Create(e echo.Context) (err error) {\n\n\t// get request and validate\n\treq := new(request.Create)\n\te.Bind(req)\n\tif err = e.Validate(req); err != nil {\n\t\treturn rest.ConstructErrorResponse(e, exception.NewInputValidationFailed(err.Error()))\n\t}\n\t// map req to input data\n\treqData := input.NewNewProductCreate(\n\t\tmap[string]interface{}{\n\t\t\t\"Name\": req.Name,\n\t\t\t\"Qty\": req.Qty,\n\t\t\t\"Price\": req.Price,\n\t\t\t\"Weight\": req.Weight,\n\t\t\t\"Images\": req.Images,\n\t\t\t\"Description\": req.Description,\n\t\t},\n\t)\n\t//insert data to db\n\tproduct, exc := ProductModel.Create(reqData)\n\tif exc != nil {\n\t\treturn rest.ConstructErrorResponse(e, exc)\n\t}\n\tdata := map[string]contract.Model{\n\t\t\"created_product\": product,\n\t}\n\treturn rest.ConstructSuccessResponse(e, data)\n}", "func (ph *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : POST /app/product API hit!\")\n\tvar request CreateProductRequest\n\tbody := json.NewDecoder(r.Body)\n\terr := body.Decode(&request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.DecodeErrorCode, err.Error())\n\t\treturn\n\t}\n\tvalidator := validator.New()\n\terr = validator.Struct(request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.ValidationErrorCode, err.Error())\n\t\treturn\n\t}\n\tproduct, err := ph.ps.CreateProduct(r.Context(), &request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tif err.Error() == utils.ProductNameExistsError {\n\t\t\tutils.Fail(w, 200, utils.ProductNameExistsErrorCode, err.Error())\n\t\t\treturn\n\t\t}\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : product created! id_product : \", product.ID)\n\tutils.Send(w, 200, product)\n}", "func (e *engine) CreateProduct(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\tvar product = &domain.Product{}\n\t// check is valid json for product\n\terr = c.BindToJson(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tproduct.Iid = id\n\tres, err := e.ProductLogic.NewProduct(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tc.JSON(200, res)\n}", "func (ch *CartHandler) Create(w http.ResponseWriter, r *http.Request) {\n\n\tp := new(Product)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&p); err != nil {\n\t\tRespondWithError(w, http.StatusBadRequest, err)\n\t}\n\tdefer r.Body.Close()\n\n\tp, err := ch.Cart.Save(p)\n\tif err != nil {\n\t\tswitch err {\n\t\tcase ErrorCorruptDb:\n\t\t\tRespondWithError(w, http.StatusInternalServerError, err)\n\t\tdefault:\n\t\t\tRespondWithError(w, http.StatusBadRequest, err)\n\t\t}\n\t}\n\n\tRespond(w, http.StatusCreated, p)\n}", "func CreateProduct(c *gin.Context) {\n\t// if os.Getenv(\"app_status\") != \"true\" {\n\t// \tc.JSON(http.StatusInternalServerError, \"Product service is temporarily down\")\n\t// \treturn\n\t// }\n\tdb := DbConn()\n\tvar prod Products\n\terr := c.BindJSON(&prod)\n\tfmt.Println(\"Error binding json: \", err)\n\tfmt.Println(\"prod: \", prod)\n\tif err != nil {\n\t\tfmt.Println(\"Error in req format\")\n\t\tc.JSON(http.StatusBadRequest, \"Error in req format\")\n\t}\n\terr = db.Create(&prod).Error\n\tif err != nil {\n\t\tfmt.Println(\"Error in inserting in database\")\n\t\tc.String(http.StatusServiceUnavailable, \"Error in inserting in database\")\n\t}\n\n\tc.String(http.StatusOK, \"Success\")\n\n}", "func (p *Products) CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tproduct := r.Context().Value(KeyProduct{}).(data.Product)\n\n\tp.l.Printf(\"[DEBUG] Inserting product: %#v\\n\", product)\n\n\tdata.AddProduct(&product)\n\tw.WriteHeader(http.StatusCreated)\n}", "func CreateProduct(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n /*\n Arguments:\n * ID\n * Name\n * HeatId\n * Quantity\n * Description\n * Organization\n * Unit\n * CreatedAt\n */\n\n ID := \"product-\" + args[0]\n quantity, err := strconv.ParseFloat(args[4], 64)\n if err != nil {\n return shim.Error(err.Error())\n }\n createdAt := time.Now().Format(\"2006-01-02 15:04:05 +0000 UTC\")\n if quantity < 0 {\n return shim.Error(\"Quantity should be positive\")\n }\n\n var product = types.Product{Class: \"Product\", ID: ID, Name: args[1], HeatID: args[2], Quantity: quantity, Description: args[4], Owner: args[5], Unit: args[6], CreatedAt: createdAt, ModifiedAt: createdAt}\n\n CreatedProductBytes, _ := json.Marshal(product)\n APIstub.PutState(ID, CreatedProductBytes)\n\n return shim.Success(CreatedProductBytes)\n}", "func (service *Service) CreateProduct(request *restful.Request, response *restful.Response) {\n\tvar req models.ProductRequest\n\tif err := request.ReadEntity(&req); err != nil {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"unable parse request body\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to parse request body:\", err)\n\n\t\treturn\n\t}\n\n\tnewUUID, err := uuid.NewRandom()\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageServerError,\n\t\t\t\"unable to create uuid\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to create uuid:\", err)\n\n\t\treturn\n\t}\n\n\tproduct := models.Product{\n\t\tProductID: newUUID.String(),\n\t\tName: req.Name,\n\t\tDescription: req.Description,\n\t\tPrice: req.Price,\n\t\tPaymentID: req.PaymentID,\n\t\tCategoryID: req.CategoryID,\n\t\tUserID: req.UserID,\n\t\tImage: req.Image,\n\t\tUpdatedAt: time.Now().UTC(),\n\t\tCreatedAt: time.Now().UTC(),\n\t}\n\n\tcreatedProduct, err := service.server.CreateProduct(product)\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageDatabaseError,\n\t\t\t\"unable to create product\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to create product:\", err)\n\n\t\treturn\n\t}\n\n\tresult := &models.CreateProductResponse{\n\t\tResult: *createdProduct,\n\t}\n\n\twriteResponse(response, http.StatusCreated, result)\n}", "func CreateProduct(c *gin.Context) {\n\tvar product Models.Product\n\tc.BindJSON(&product)\n\terr := Models.CreateProduct(&product)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func Create() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\trequestBody := productPostRequest{}\n\t\tc.Bind(&requestBody)\n\n\t\tproduct := model.Products{\n\t\t\tProductTypeID: requestBody.ProductTypeID,\n\t\t\tName: requestBody.Name,\n\t\t}\n\n\t\terr := db.Db.Create(&product)\n\n\t\tif product.ID == 0 {\n\t\t\tc.JSON(http.StatusBadRequest, err.Error)\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func CreateProduct(rw http.ResponseWriter, r *http.Request) {\n\tvar product data.Product\n\terr := json.NewDecoder(r.Body).Decode(&product)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\n\terr = services.CreateProduct(&product)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\n\tjson.NewEncoder(rw).Encode(product)\n}", "func (service *Service) CreateProduct(c *gin.Context) error {\n\tname := c.PostForm(\"name\")\n\tdescription := c.PostForm(\"description\")\n\tuserID, err := jwt.VerifyToken(c)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar product Product\n\n\tproduct.SetName(name)\n\tproduct.SetDescription(description)\n\tproduct.SetUserID(userID)\n\n\terr = service.ProductRepository.Create(product)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (create) Product(ctx context.Context, db *sqlx.DB, user auth.Claims, np NewProduct, now time.Time) (*Product, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.create.product\")\n\tdefer span.End()\n\n\tp := Product{\n\t\tID: uuid.New().String(),\n\t\tName: np.Name,\n\t\tCost: np.Cost,\n\t\tQuantity: np.Quantity,\n\t\tUserID: user.Subject,\n\t\tDateCreated: now.UTC(),\n\t\tDateUpdated: now.UTC(),\n\t}\n\n\tconst q = `\n\t\tINSERT INTO products\n\t\t(product_id, user_id, name, cost, quantity, date_created, date_updated)\n\t\tVALUES ($1, $2, $3, $4, $5, $6, $7)`\n\n\t_, err := db.ExecContext(ctx, q,\n\t\tp.ID, p.UserID,\n\t\tp.Name, p.Cost, p.Quantity,\n\t\tp.DateCreated, p.DateUpdated)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"inserting product\")\n\t}\n\n\treturn &p, nil\n}", "func CreateProduct(w http.ResponseWriter, r *http.Request) {\n var p dynamodbservice.Product\n w.Header().Add(\"Content-Type\", \"application/json\")\n if err := json.NewDecoder(r.Body).Decode(&p); err != nil {\n http.Error(w, err.Error(), http.StatusBadRequest)\n return\n }\n\n defer r.Body.Close()\n\n if err := dynamodbservice.Items.AddProduct(p); err != nil {\n http.Error(w, err.Error(), http.StatusInternalServerError)\n return\n }\n\n w.WriteHeader(http.StatusCreated)\n json.NewEncoder(w).Encode(p)\n}", "func (main *Main) Create(e echo.Context) (err error) {\n\n\t// get request and validate\n\treq := new(request.Create)\n\te.Bind(req)\n\tif err = e.Validate(req); err != nil {\n\t\treturn rest.ConstructErrorResponse(e, exception.NewInputValidationFailed(err.Error()))\n\t}\n\n\t// get user details\n\tuserId := strconv.Itoa(req.UserID)\n\t_, excUser := UserModel.Get(\"id\", userId)\n\tif excUser != nil {\n\t\treturn rest.ConstructErrorResponse(e, excUser)\n\t}\n\n\t// get product details\n\tproductId := strconv.Itoa(req.ProductID)\n\t_, excProduct := ProductModel.Get(\"id\", productId)\n\tif excProduct != nil {\n\t\treturn rest.ConstructErrorResponse(e, excProduct)\n\t}\n\t//check if product exist in cart\n\n\tif CartModel.CheckExistingProduct(userId, productId) == true {\n\t\trest.ConstructErrorResponse(e, exception.NewDuplicateRecordFound(\"product\"))\n\t} else {\n\t\t// map req to input data\n\t\treqData :=\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"UserID\": req.UserID,\n\t\t\t\t\"ProductID\": req.ProductID,\n\t\t\t\t\"Qty\": req.Qty,\n\t\t\t}\n\n\t\t//insert data to db\n\t\tcart, exc := CartModel.Create(reqData)\n\t\tif exc != nil {\n\t\t\treturn rest.ConstructErrorResponse(e, exc)\n\t\t}\n\t\tdata := map[string]contract.Model{\n\t\t\t\"created_cart\": cart,\n\t\t}\n\t\treturn rest.ConstructSuccessResponse(e, data)\n\t}\n\treturn\n}", "func (r ProductRepository) Create(ctx context.Context, entity *product.Product) error {\n\n\tif !r.db.DB().NewRecord(entity) {\n\t\treturn errors.New(\"entity is not new\")\n\t}\n\treturn r.db.DB().Create(entity).Error\n}", "func (pr ProductRepository) Create(ctx context.Context, product *domain.Product) error {\n\treturn pr.db.Insert(ctx, product)\n}", "func CreateProduct(w http.ResponseWriter, r *http.Request) {\n\tvar product types.Product\n\terr := readBody(r, &product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\tsavedProduct, err := repo.CreateProduct(r.Context(), product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, savedProduct, http.StatusCreated)\n}", "func CreateProduct(c echo.Context) error {\n\tvar objRequest types.Product\n\tif err := c.Bind(&objRequest); err != nil {\n\t\tlog.Error(err)\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_ERR\", \"Có lỗi xảy ra, vui lòng kiểm tra lại thông tin\"))\n\t}\n\tif err := c.Validate(&objRequest); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_INVALID\", err.Error()))\n\t}\n\n\tdata, err := db.CreateNewProduct(&objRequest)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotAcceptable, types.ParseStatus(\"NOT_ACCEPTED\", err.Error()))\n\t}\n\treturn c.JSON(http.StatusCreated, data)\n}", "func (fapi *FyndiqAPI) CreateProduct(product *Product) (string, error) {\n\tpost, err := json.Marshal(product)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := httpRequest(\"POST\", fapi.productsURL(RequestParams{}), bytes.NewBuffer(post))\n\tif err == nil {\n\t\treturn resp.header[\"Location\"][0], nil\n\t}\n\treturn \"\", err\n}", "func (*Products) Create(product *Products) (int64, error) {\n\n\tstmt, err := db.Prepare(\n\t\t\"insert into products (name, unit) \" +\n\t\t\t\"values ($1, $2) returning id\")\n\n\tif err != nil {\n\t\tlog.Println(\"(CreateProduct:Prepare)\", err)\n\t\treturn -1, err\n\t}\n\n\tdefer stmt.Close()\n\n\terr = stmt.QueryRow(product.Name,\n\t\tproduct.Unit).Scan(&product.ID)\n\n\tif err != nil {\n\t\tlog.Println(\"(CreateProduct:Exec)\", err)\n\t\treturn -1, err\n\t}\n\n\treturn product.ID, nil\n\n}", "func CreateProduct(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\n\tif len(args) != 5 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 5\")\n\t}\n\tvar products = Products{\n\t\tProductName: args[0],\n\t\tProductId: args[1],\n\t\tProductDescription: args[2],\n\t\tProductPrice: args[3],\n\t\tSellerID: args[4]\n\t\tStatus: args[5]\n\t\tCreatedAt: args[6]\n\t\tUpdatedAt: args[7]\n\t\tCategory: args[8]}\n\n\tproductAsBytes, _ := json.Marshal(products)\n\n\tvar uniqueID = args[1]\n\n\terr := stub.PutState(uniqueID, productAsBytes)\n\n\tif err != nil {\n\t\tfmt.Println(\"Erro in create product\")\n\t}\n\n\treturn shim.Success(nil)\n}", "func (c *Chef) Create(v interface{}) (string, error) {\n\tpdt, ok := v.(model.Product)\n\tif !ok {\n\t\treturn \"\", ErrUnsupportedType\n\t}\n\tpdt.ID = uuid.NewV4().String()\n\n\tif err := pdt.Validate(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr := c.db.Exec(fmt.Sprintf(`INSERT INTO %s (\"id\", \"name\", \"price\", \"weight\", \"available\") VALUES('%s', '%s', %d, %d, %t)`,\n\t\tc.table, pdt.ID, pdt.Name, pdt.Price, pdt.Weight, pdt.Available,\n\t))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn pdt.ID, nil\n}", "func (ac *AdminCtl) Create() {\n\tif ac.Ctx.Request().Method == \"POST\" {\n\t\tnumber, _ := strconv.Atoi(ac.Ctx.Request().FormValue(\"number\"))\n\t\tname := ac.Ctx.Request().FormValue(\"name\")\n\t\tmtype := ac.Ctx.Request().FormValue(\"type\")\n\t\tcount, _ := strconv.Atoi(strings.Trim(ac.Ctx.Request().FormValue(\"count\"), \" \")) // 去除空白字符\n\t\tprice, _ := strconv.Atoi(ac.Ctx.Request().FormValue(\"price\"))\n\t\thref := ac.Ctx.Request().FormValue(\"href\")\n\t\turl := ac.Ctx.Request().FormValue(\"url\")\n\t\tsnumber := ac.Ctx.Request().FormValue(\"number\")\n\n\t\tproduct := &models.Product{\n\t\t\tNumber: number,\n\t\t\tName: name,\n\t\t\tType: mtype,\n\t\t\tCount: count,\n\t\t\tPrice: price,\n\t\t\tHref: href,\n\t\t\tURL: url,\n\t\t\tBrief: \"/data/\" + snumber + \"/brief\",\n\t\t\tDetail: \"/data/\" + snumber + \"/detail\",\n\t\t}\n\t\tac.Ctx.DB.Create(&product)\n\t\tac.Ctx.Redirect(\"/admin\", http.StatusFound)\n\t} else {\n\t\tac.Ctx.Data[\"AddPage\"] = true\n\t\tac.Ctx.Template = \"admin-add\"\n\t\tac.HTML(http.StatusOK)\n\t}\n}", "func (pr *PsqlProduct) Create(p *product.Product) error {\n\treturn nil\n}", "func (s *SmartContract) createProduct(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\tidentity, err := GetInvokerIdentity(stub)\n\tif err != nil {\n\t\tshim.Error(fmt.Sprintf(\"Error getting invoker identity: %s\\n\", err.Error()))\n\t}\n\ts.logger.Infof(\"%+v\\n\", identity.Cert.Subject.String())\n\n\tif !identity.CanInvoke(\"createProduct\") {\n\t\treturn peer.Response{\n\t\t\tStatus: 403,\n\t\t\tMessage: fmt.Sprintf(\"You are not authorized to perform this transaction, cannot invoke createProduct\"),\n\t\t}\n\t}\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t// Create ProductRequest struct from input JSON.\n\targBytes := []byte(args[0])\n\tvar request ProductRequest\n\tif err := json.Unmarshal(argBytes, &request); err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t//Check if product state using id as key exsists\n\ttestProductAsBytes, err := stub.GetState(request.ID)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t// Return 403 if item exisits\n\tif len(testProductAsBytes) != 0 {\n\t\treturn peer.Response{\n\t\t\tStatus: 403,\n\t\t\tMessage: fmt.Sprintf(\"Existing Product %s Found\", args[0]),\n\t\t}\n\t}\n\n\tproduct := Product{\n\t\tID: request.ID,\n\t\tType: \"product\",\n\t\tName: request.ProductName,\n\t\tHealth: \"\",\n\t\tMetadata: request.Metadata,\n\t\tLocation: request.Location,\n\t\tSold: false,\n\t\tRecalled: false,\n\t\tContainerID: \"\",\n\t\tCustodian: identity.Cert.Subject.String(),\n\t\tTimestamp: int64(s.clock.Now().UTC().Unix()),\n\t\tParticipants: request.Participants,\n\t}\n\n\tproduct.Participants = append(product.Participants, identity.Cert.Subject.String())\n\n\t// Put new Product onto blockchain\n\tproductAsBytes, _ := json.Marshal(product)\n\tif err := stub.PutState(product.ID, productAsBytes); err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tresponse := map[string]interface{}{\n\t\t\"generatedID\": product.ID,\n\t}\n\tbytes, _ := json.Marshal(response)\n\n\ts.logger.Infof(\"Wrote Product: %s\\n\", product.ID)\n\treturn shim.Success(bytes)\n}", "func (s *Controller) handleCreateProduct(c *gin.Context) {\n\n\tvar product entity.Product\n\n\terr := c.ShouldBindJSON(&product)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\trestErr := resterrors.NewBadRequestError(\"Invalid json body\")\n\t\tc.JSON(restErr.StatusCode, restErr)\n\t\treturn\n\t}\n\n\tproductID, createErr := s.productService.CreateProduct(product)\n\tif createErr != nil {\n\t\tc.JSON(createErr.StatusCode, createErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, gin.H{\"id\": productID})\n}", "func CreateProduct(product ProductCreationPayload, db *sql.DB) (Product, error) {\n\tvar id int\n\tresult := db.QueryRow(\"INSERT INTO products (title, price) VALUES ($1, $2) RETURNING product_id\", product.Title, product.Price)\n\terr := result.Scan(&(id))\n\tif err == nil {\n\t\treturn GetProduct(strconv.Itoa(id), db)\n\t}\n\treturn Product{}, err\n}", "func (p *Products) POST(rw http.ResponseWriter, r *http.Request) {\n\tprod := r.Context().Value(KeyProduct{}).(data.Product)\n\tdata.AddProduct(prod)\n\n\tp.l.Printf(\"[DEBUG] Inserted product: %#v\\n\", prod)\n}", "func TestProductCreate(t *testing.T) {\n\turl := \"https://storeproject-209402.appspot.com/products?name=Apple&code=testCode12345&description=test&image=thisimage\"\n\texpected := `{\"name\":\"Apple\",\"barcode\":\"testCode12345\",\"description\":\"test\",\"image\":\"thisimage\"}`\n\tif passed, result := testCall(url, \"POST\", expected); !passed {\n\t\tt.Errorf(\"POST product: got %v want %v\",\n\t\t\tresult, expected)\n\t}\n}", "func (e Endpoints) CreateProduct(ctx context.Context, createReq models.CreateProductReq) (createResp *models.CreateProductResp, err error) {\n\trequest := CreateProductRequest{CreateReq: createReq}\n\tresponse, err := e.CreateProductEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(CreateProductResponse).CreateResp, response.(CreateProductResponse).Err\n}", "func (h *ProductHandler) AddProduct(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newProduct newProduct\n\tbody, _ := ioutil.ReadAll(r.Body)\n\terr := json.Unmarshal(body, &newProduct)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\tproduct := models.Product{\n\t\tName: newProduct.Name,\n\t\tSKU: newProduct.SKU,\n\t}\n\terr = h.ProductUsecase.Create(ctx, &product)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tfor _, catID := range newProduct.CategoryID {\n\t\tcat := models.ProductCategory{\n\t\t\tProductID: product.ID,\n\t\t\tCategoryID: catID,\n\t\t}\n\n\t\terr = h.ProductCatUsecase.Create(ctx, &cat)\n\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, price := range newProduct.Price {\n\t\t_price := models.ProductPrice{\n\t\t\tAmount: price.Amount,\n\t\t\tPrice: price.Price,\n\t\t\tProductID: product.ID,\n\t\t}\n\n\t\terr = h.PriceUsecase.Create(ctx, &_price)\n\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tutils.JSON(w, http.StatusOK, product)\n\n}", "func (main *Main) Create(e echo.Context) (err error) {\n\n\t// get request and validate\n\treq := new(request.Create)\n\te.Bind(req)\n\tif err = e.Validate(req); err != nil {\n\t\treturn rest.ConstructErrorResponse(e, exception.NewInputValidationFailed(err.Error()))\n\t}\n\t// map req to input data\n\treqData := input.NewNewTransactionCreate(\n\t\tmap[string]interface{}{\n\t\t\t\"Name\": req.Name,\n\t\t\t\"Qty\": req.Qty,\n\t\t\t\"Price\": req.Price,\n\t\t\t\"Weight\": req.Weight,\n\t\t\t\"Images\": req.Images,\n\t\t\t\"Description\": req.Description,\n\t\t},\n\t)\n\t//insert data to db\n\ttransaction, exc := TransactionModel.Create(reqData)\n\tif exc != nil {\n\t\treturn rest.ConstructErrorResponse(e, exc)\n\t}\n\tdata := map[string]contract.Model{\n\t\t\"created_transaction\": transaction,\n\t}\n\treturn rest.ConstructSuccessResponse(e, data)\n}", "func (p *Products) POST(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle POST Products\")\n\n\tprod := r.Context().Value(KeyProduct{}).(*data.Product)\n\tp.l.Println(prod)\n\tp.dbConnection.InsertProduct(prod)\n}", "func (db *MySQLDB) CreateProduct(ctx context.Context, rec *ProductRecord) (string, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"CreateProduct\")\n\n\t_, err := db.instance.ExecContext(ctx, \"INSERT INTO products(brand_id, name, qty, price, sku) VALUES(?,?,?,?,?)\", rec.BrandID, rec.Name, rec.Qty, rec.Price, rec.SKU)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.ExecContext got %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\n\treturn \"product created successfully\", nil\n}", "func CreateProductPath() string {\n\treturn \"/api/product/create\"\n}", "func (m *SystemMock) CreateProduct(productName string) (string, error) {\n\tnow := time.Now().Format(DateTimeLayout)\n\tproductIndex := len(m.Products)\n\tproduct := Product{\n\t\tName: productName,\n\t\tToken: \"mock-product-token-\" + strconv.Itoa(productIndex),\n\t\tCreationDate: now,\n\t\tLastUpdateDate: now,\n\t}\n\tm.Products = append(m.Products, product)\n\treturn product.Token, nil\n}", "func (c *PurchaseController) Create(ctx *app.CreatePurchaseContext) error {\n\n\t// sets the document id\n\tnewID := bson.NewObjectId()\n\tctx.Payload.ID = &newID\n\n\t// sets initial purchase status\n\tnewStatus := new(string)\n\t*newStatus = \"CREATED\"\n\n\tctx.Payload.Status = newStatus\n\n\t// reuse from connection pool\n\tsession := Database.Session.Copy()\n\tdefer session.Close()\n\n\t// inserts the document into Purchase collection\n\terr := session.DB(\"services-pos\").C(\"Purchase\").Insert(ctx.Payload)\n\n\t// ops! something went wrong...\n\tif err != nil {\n\t\tif mgo.IsDup(err) {\n\t\t\t// purchase already exists. (HTTP 409 - Conflict)\n\t\t\treturn ctx.Conflict()\n\t\t}\n\n\t\tService.LogError(err.Error())\n\n\t\t// HTTP 500 - Internal Server Error\n\t\treturn ctx.Err()\n\t}\n\n\t// indicates the new URI for the created resource (e.g. /purchases/{:id})\n\tctx.ResponseData.Header().Set(\"Location\", app.PurchaseHref(newID.Hex()))\n\n\t// HTTP 201 - Created\n\treturn ctx.Created()\n}", "func (ctl *SaleCounterProductController) Create() {\n\tctl.Data[\"Action\"] = \"create\"\n\tctl.Data[\"Readonly\"] = false\n\tctl.PageAction = utils.MsgCreate\n\tctl.Data[\"FormField\"] = \"form-create\"\n\tctl.Layout = \"base/base.html\"\n\tctl.TplName = \"sale/sale_counter_product_form.html\"\n}", "func (purchase *Purchase) Create(p Purchase) (Purchase, error) {\n\treturn test, nil\n}", "func (productCategory ProductCategory) create() (Entity, error) {\n\n\ten := productCategory\n\n\tif err := db.Create(&en).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := en.GetPreloadDb(false, false, nil).First(&en, en.Id).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tAsyncFire(NewEvent(\"ProductCategoryCreated\", map[string]interface{}{\"account_id\":en.AccountId, \"product_category_id\":en.Id}))\n\n\tvar newItem Entity = &en\n\n\treturn newItem, nil\n}", "func NewProduct(c *fiber.Ctx) error {\n db := database.Connection()\n\treturn models.NewProduct(db, c)\n}", "func PostProduct(data Product) Product {\n\tdatabase.SQL.Create(&data)\n\treturn data\n}", "func (h *Stocks) Create(ctx context.Context, w http.ResponseWriter, r *http.Request, _ map[string]string) error {\n\n\tctxValues, err := webcontext.ContextValues(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclaims, err := auth.ClaimsFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//\n\treq := new(inventory.AddStockRequest)\n\tdata := make(map[string]interface{})\n\tf := func() (bool, error) {\n\t\tif r.Method == http.MethodPost {\n\t\t\terr := r.ParseForm()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tdecoder := schema.NewDecoder()\n\t\t\tdecoder.IgnoreUnknownKeys(true)\n\n\t\t\tif err := decoder.Decode(req, r.PostForm); err != nil {\n\t\t\t\treturn false, errors.WithMessage(err, \"Something wrong\")\n\t\t\t}\n\n\t\t\tresp, err := h.Repo.AddStock(ctx, claims, *req, ctxValues.Now)\n\t\t\tif err != nil {\n\t\t\t\tswitch errors.Cause(err) {\n\t\t\t\tdefault:\n\t\t\t\t\tif verr, ok := weberror.NewValidationError(ctx, err); ok {\n\t\t\t\t\t\tdata[\"validationErrors\"] = verr.(*weberror.Error)\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Display a success message to the product.\n\t\t\twebcontext.SessionFlashSuccess(ctx,\n\t\t\t\t\"Inventory Created\",\n\t\t\t\t\"Inventory successfully created.\")\n\n\t\t\treturn true, web.Redirect(ctx, w, r, urlStocksView(resp.ID), http.StatusFound)\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\tend, err := f()\n\tif err != nil {\n\t\treturn web.RenderError(ctx, w, r, err, h.Renderer, TmplLayoutBase, TmplContentErrorGeneric, web.MIMETextHTMLCharsetUTF8)\n\t} else if end {\n\t\treturn nil\n\t}\n\n\tdata[\"products\"], err = h.ShopRepo.FindProduct(ctx, shop.ProductFindRequest{ Order: []string{\"name\"} })\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata[\"form\"] = req\n\tdata[\"urlStocksIndex\"] = urlStocksIndex()\n\n\tif verr, ok := weberror.NewValidationError(ctx, webcontext.Validator().Struct(inventory.AddStockRequest{})); ok {\n\t\tdata[\"validationDefaults\"] = verr.(*weberror.Error)\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"stocks-create.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func (p *Products) ProductPOST(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Just a test, post work well\")\n\n\tprod := r.Context().Value(KeyProduct{}).(data.Product)\n\tdata.AddProduct(&prod)\n}", "func (a *App) CreateProduct(p *model.Product, fh *multipart.FileHeader, headers []*multipart.FileHeader, tags []*model.ProductTag) (*model.Product, *model.AppErr) {\n\tif fh.Size > model.FileUploadSizeLimit {\n\t\treturn nil, model.NewAppErr(\"createProduct\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgProductSizeExceeded, http.StatusInternalServerError, nil)\n\t}\n\tthumbnail, err := fh.Open()\n\tif err != nil {\n\t\treturn nil, model.NewAppErr(\"createProduct\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgProductSizeExceeded, http.StatusInternalServerError, nil)\n\t}\n\tb, err := ioutil.ReadAll(thumbnail)\n\tif err != nil {\n\t\treturn nil, model.NewAppErr(\"createProduct\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgProductFileErr, http.StatusInternalServerError, nil)\n\t}\n\n\tp.PreSave()\n\tif err := p.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdetails, uErr := a.UploadImage(bytes.NewBuffer(b), fh.Filename)\n\tif uErr != nil {\n\t\treturn nil, uErr\n\t}\n\tp.SetImageURL(details.SecureURL)\n\n\tproduct, pErr := a.Srv().Store.Product().Save(p)\n\tif pErr != nil {\n\t\ta.Log().Error(pErr.Error(), zlog.Err(pErr))\n\t\treturn nil, pErr\n\t}\n\n\tp.Category.ProductID = product.ID\n\tp.Brand.ProductID = product.ID\n\tfor _, t := range tags {\n\t\tt.ProductID = model.NewInt64(product.ID)\n\t}\n\n\timages := make([]*model.ProductImage, 0)\n\n\tfor _, fh := range headers {\n\t\tf, err := fh.Open()\n\t\tif err != nil {\n\t\t\treturn nil, model.NewAppErr(\"createProduct\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgProductFileErr, http.StatusInternalServerError, nil)\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn nil, model.NewAppErr(\"createProduct\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgProductFileErr, http.StatusInternalServerError, nil)\n\t\t}\n\t\t// TODO: upload in parallel...\n\t\tdetails, uErr := a.UploadImage(bytes.NewBuffer(b), fh.Filename)\n\t\tif uErr != nil {\n\t\t\treturn nil, uErr\n\t\t}\n\t\timg := &model.ProductImage{ProductID: model.NewInt64(product.ID), URL: model.NewString(details.SecureURL)}\n\t\timages = append(images, img)\n\t}\n\n\tif len(tags) > 0 {\n\t\tfor _, tag := range tags {\n\t\t\ttag.PreSave()\n\t\t}\n\n\t\ttagids, err := a.Srv().Store.ProductTag().BulkInsert(tags)\n\t\tif err != nil {\n\t\t\ta.Log().Error(err.Error(), zlog.Err(err))\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i, id := range tagids {\n\t\t\ttags[i].ID = model.NewInt64(id)\n\t\t}\n\t} else {\n\t\ttags = make([]*model.ProductTag, 0)\n\t}\n\n\tif len(images) > 0 {\n\t\tfor _, img := range images {\n\t\t\timg.PreSave()\n\t\t}\n\n\t\timgids, err := a.Srv().Store.ProductImage().BulkInsert(images)\n\t\tif err != nil {\n\t\t\ta.Log().Error(err.Error(), zlog.Err(err))\n\t\t\treturn nil, err\n\t\t}\n\t\tfor i, id := range imgids {\n\t\t\timages[i].ID = model.NewInt64(id)\n\t\t}\n\t} else {\n\t\timages = make([]*model.ProductImage, 0)\n\t}\n\n\treturn product, nil\n}", "func (mysql *MySqlDB) CreateProduct(p *models.Product) (int64, error) {\n\n\tif !p.Validate() {\n\t\treturn 0, models.NewError(\"Invalid product data\", INVALID_DATA)\n\t}\n\n\tsql := \"INSERT INTO products (product_name, image, rate) \" +\n\t\t\"SELECT ?, ?, ? FROM DUAL WHERE NOT EXISTS \" +\n\t\t\"(SELECT product_name FROM products WHERE product_name = ?)\"\n\n\tquery, err := mysql.DB.Exec(sql, p.ProductName, p.Image, p.Rate, p.ProductName)\n\tif err != nil {\n\t\treturn 0, models.NewError(\"Internal server error\", ERR_INTERNAL)\n\t}\n\tlastId, _ := query.LastInsertId()\n\treturn lastId, nil\n}", "func createOrUpdateProduct(p Product) (Product, error) {\n\tif p.ID == \"\" {\n\t\tp.ID = strconv.Itoa(len(data) + 1)\n\t\tp.CreatedAt = time.Now()\n\t\tdata = append(data, p)\n\t\treturn p, nil\n\t}\n\tstored, _, err := findProduct(p.ID)\n\tif err != nil {\n\t\tvar empty Product\n\t\treturn empty, err\n\t}\n\n\t//C hange found product\n\tstored.ID = p.ID\n\tstored.Name = p.Name\n\tstored.Price = p.Price\n\treturn *stored, nil\n}", "func (ctl *SaleCounterProductController) PostCreate() {\n\tresult := make(map[string]interface{})\n\tpostData := ctl.GetString(\"postData\")\n\tfmt.Printf(\"%+v\\n\", postData)\n\tcounterProduct := new(md.SaleCounterProduct)\n\tvar (\n\t\terr error\n\t\tid int64\n\t)\n\tif err = json.Unmarshal([]byte(postData), counterProduct); err == nil {\n\t\t// 获得struct表名\n\t\t// structName := reflect.Indirect(reflect.ValueOf(template)).Type().Name()\n\t\tif id, err = md.AddSaleCounterProduct(counterProduct, &ctl.User); err == nil {\n\t\t\tresult[\"code\"] = \"success\"\n\t\t\tresult[\"location\"] = ctl.URL + strconv.FormatInt(id, 10) + \"?action=detail\"\n\t\t} else {\n\t\t\tresult[\"code\"] = utils.FailedCode\n\t\t\tresult[\"message\"] = utils.FailedMsg\n\t\t\tresult[\"debug\"] = err.Error()\n\t\t}\n\t} else {\n\t\tresult[\"code\"] = utils.FailedCode\n\t\tresult[\"message\"] = utils.FailedData\n\t\tresult[\"debug\"] = err.Error()\n\t}\n\tctl.Data[\"json\"] = result\n\tctl.ServeJSON()\n\n}", "func (s *VariantServiceOp) Create(productID int, variant Variant) (*Variant, error) {\n\tpath := fmt.Sprintf(\"%s/%d/variants.json\", productsBasePath, productID)\n\twrappedData := VariantResource{Variant: &variant}\n\tresource := new(VariantResource)\n\terr := s.client.Post(path, wrappedData, resource)\n\treturn resource.Variant, err\n}", "func (store *Store) createProductPGStore() error {\n\tconst queries = `CREATE SCHEMA IF NOT EXISTS shopalyst_product_v1;\n CREATE TABLE IF NOT EXISTS shopalyst_product_v1.product(id text DEFAULT ''::text , category_id text DEFAULT ''::text, name text DEFAULT ''::text , description text DEFAULT ''::text , image_url text DEFAULT ''::text ,PRIMARY KEY (id) );\n `\n\t_, err := store.DB.Exec(queries)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (handler *ProdukHandler) CreateProduk(echoCtx echo.Context) error {\n\tvar form CreateProdukBodyRequest\n\tif err := echoCtx.Bind(&form); err != nil {\n\t\terrorResponse := buildErrorResponse(err, entity.ErrInvalidInput)\n\t\treturn echoCtx.JSON(nethttp.StatusBadRequest, errorResponse)\n\t}\n\n\tprodukEntity := entity.NewProduk(\n\t\tuuid.Nil,\n\t\tform.KodeProduk,\n\t\tform.NamaProduk,\n\t\tint(form.Harga),\n\t\tint64(form.Stok),\n\t)\n\n\tif err := handler.service.Create(echoCtx.Request().Context(), produkEntity); err != nil {\n\t\terrorResponse := buildErrorResponse(err, entity.ErrInternalServerError)\n\t\treturn echoCtx.JSON(nethttp.StatusInternalServerError, errorResponse)\n\t}\n\n\tvar res = entity.NewResponse(nethttp.StatusCreated, \"Request processed successfully.\", produkEntity)\n\treturn echoCtx.JSON(res.Status, res)\n}", "func (s *service) Create(p *Payment) error {\n\tp.ID = uuid.NewV4().String()\n\treturn s.persist(p)\n}", "func CreateProductEndPoint(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"not implemented yet !\")\n}", "func (clgCtl *CatalogueController) Create(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"Creating Catalogue.\\n\")\n\n\tauthClaims := r.Context().Value(contextkey.ClaimToken).(signinclaimresource.SignInClaimResource)\n\n\tnewClg := cataloguemodel.NewCatalogue()\n\terr := json.NewDecoder(r.Body).Decode(newClg)\n\tif err != nil {\n\t\tclgCtl.WriteResponse(w, http.StatusBadRequest, false, nil, \"Invalid create catalogue request.\")\n\t\treturn\n\t}\n\n\tvalid, message := newClg.DoValidate()\n\tif !valid {\n\t\tclgCtl.WriteResponse(w, http.StatusBadRequest, false, nil, message)\n\t\treturn\n\t}\n\n\tnewClg.Status = status.Active.String()\n\tnewClg.CreatedBy = authClaims.GetUsername()\n\tnewClg.ModifiedBy = authClaims.GetUsername()\n\tnewClg.Vers = 1\n\n\tclgRepo := cataloguerepository.NewCatalogueRepository()\n\tnbrRows, err := clgRepo.Create(r.Context(), newClg)\n\tif err != nil {\n\t\tclgCtl.WriteResponse(w, http.StatusInternalServerError, false, nil, err.Error())\n\t\treturn\n\t}\n\n\tif nbrRows == 0 {\n\t\tclgCtl.WriteResponse(w, http.StatusNotFound, false, nil, \"Catalogue was not created.\")\n\t\treturn\n\t}\n\n\tresult, err := clgRepo.GetByID(r.Context(), newClg.GetCode())\n\tif err != nil {\n\t\tclgCtl.WriteResponse(w, http.StatusInternalServerError, false, nil, err.Error())\n\t\treturn\n\t}\n\n\tif result != nil {\n\t\tfieldDefRepo := customfielddefinitionrepository.NewCustomFieldDefinitionRepository()\n\t\tfor _, newFieldDef := range newClg.GetAllCustomFieldDefinitions() {\n\t\t\tif newFieldDef.GetChangeMode() == changemode.Add {\n\t\t\t\tnewFieldDef.CatalogueCode = newClg.GetCode()\n\t\t\t\tnewFieldDef.CreatedBy = newClg.GetCreatedBy()\n\t\t\t\tnewFieldDef.CreatedAt = newClg.GetCreatedAt()\n\t\t\t\tnewFieldDef.ModifiedBy = newClg.GetModifiedBy()\n\t\t\t\tnewFieldDef.ModifiedAt = newClg.GetModifiedAt()\n\t\t\t\tnewFieldDef.Vers = 1\n\n\t\t\t\tnbrRows, err := fieldDefRepo.Create(r.Context(), newFieldDef)\n\t\t\t\tif err != nil {\n\t\t\t\t\tclgCtl.WriteResponse(w, http.StatusInternalServerError, false, nil, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif nbrRows == 0 {\n\t\t\t\t\tclgCtl.WriteResponse(w, http.StatusNotFound, false, nil, \"Custom Field Definition was not created.\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfieldDefs, err := fieldDefRepo.GetByCatalogue(r.Context(), newClg.GetCode())\n\t\tif err != nil {\n\t\t\tclgCtl.WriteResponse(w, http.StatusInternalServerError, false, nil, err.Error())\n\t\t\treturn\n\t\t}\n\t\tresult.CustomFieldDefinitions = fieldDefs\n\t}\n\n\tclgCtl.WriteResponse(w, http.StatusAccepted, true, result, \"Catalogue has been created.\")\n}", "func (v ProspectsResource) Create(c buffalo.Context) error {\n\t// Allocate an empty Prospect\n\tprospect := &models.Prospect{}\n\n\t// Bind prospect to the html form elements\n\tif err := c.Bind(prospect); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Get the DB connection from the context\n\ttx := c.Value(\"tx\").(*pop.Connection)\n\n\t// Validate the data from the html form\n\tverrs, err := tx.ValidateAndCreate(prospect)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif verrs.HasAny() {\n\t\t// Make prospect available inside the html template\n\t\tc.Set(\"prospect\", prospect)\n\n\t\t// Make the errors available inside the html template\n\t\tc.Set(\"errors\", verrs)\n\n\t\t// Render again the new.html template that the user can\n\t\t// correct the input.\n\t\treturn c.Render(422, r.HTML(\"prospects/new.html\"))\n\t}\n\n\t// If there are no errors set a success message\n\tc.Flash().Add(\"success\", \"Prospect was created successfully\")\n\n\t// and redirect to the prospects index page\n\treturn c.Redirect(302, \"/prospects/%s\", prospect.ID)\n}", "func (h *Handler) Create(ctx *gin.Context) {\n\tvar payment models.PaymentInput\n\terr := json.NewDecoder(ctx.Request.Body).Decode(&payment)\n\tif err != nil {\n\t\thandleError(ctx, err, http.StatusBadRequest)\n\t} else {\n\t\tid, err := h.PaymentResource.Create(ctx, payment)\n\t\tif err != nil {\n\t\t\thandleError(ctx, err, 0)\n\t\t} else {\n\t\t\tctx.JSON(http.StatusCreated, models.JSONAPISuccessObject{Status: http.StatusCreated, ID: id})\n\t\t}\n\t}\n}", "func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {\n\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\n\tvar t model.Delivery\n\terr := decoder.Decode(&t)\n\n\tif err != nil {\n\t\te := Error{\n\t\t\tMessage: \"An error has occured during the parsing of the body\",\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 400)\n\t\treturn\n\t}\n\n\tif t.Software == \"\" {\n\t\te := Error{\n\t\t\tMessage: \"The software is mandatory\",\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 400)\n\t\treturn\n\t}\n\n\tif t.Version == \"\" {\n\t\te := Error{\n\t\t\tMessage: \"The version is mandatory\",\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 400)\n\t\treturn\n\t}\n\n\tn := time.Now().UTC().Format(time.RFC3339)\n\tt.Date = n\n\n\terr = h.Source.Insert(n, t)\n\n\tif err != nil {\n\t\te := Error{\n\t\t\tMessage: \"An error occured when trying to create the delivery\",\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 500)\n\t\treturn\n\t}\n\n\tJSONWithHTTPCode(w, t, 201)\n\n}", "func (s *ProductFieldsService) Create(ctx context.Context, opt *ProductFieldCreateOptions) (*ProductFieldResponse, *Response, error) {\n\treq, err := s.client.NewRequest(http.MethodPost, \"/productFields\", nil, opt)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar record *ProductFieldResponse\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 Create(c *gin.Context) {\n\tworkshopData := CreateWorkShop{}\n\tuser := c.MustGet(\"user\").(*entities.User)\n\n\terr := c.ShouldBind(&workshopData)\n\tif err == nil {\n\t\tr, errRegister := RegisterNewWorkShop(user, workshopData)\n\t\tif errRegister != nil {\n\t\t\tresponse := global.ResponseServices(workshopData, \"400\", errRegister.Error())\n\t\t\tc.JSON(400, response)\n\t\t\treturn\n\t\t}\n\t\tresponse := global.ResponseServices(r, \"200\", \"Se he creado el taller con exito\")\n\t\tc.JSON(http.StatusOK, response)\n\t\treturn\n\t}\n\tresponse := global.ResponseServices(workshopData, \"400\", err.Error())\n\tc.JSON(400, response)\n}", "func (v PizzasResource) Create(c buffalo.Context) error {\n\t// Allocate an empty Pizza\n\tpizza := &models.Pizza{}\n\t// Bind pizza to the html form elements\n\terr := c.Bind(pizza)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// Get the DB connection from the context\n\ttx := c.Value(\"tx\").(*pop.Connection)\n\t// Validate the data from the html form\n\tverrs, err := tx.ValidateAndCreate(pizza)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif verrs.HasAny() {\n\t\t// Make pizza available inside the html template\n\t\tc.Set(\"pizza\", pizza)\n\t\t// Make the errors available inside the html template\n\t\tc.Set(\"errors\", verrs)\n\t\t// Render again the new.html template that the user can\n\t\t// correct the input.\n\t\treturn c.Render(422, r.HTML(\"pizzas/new.html\"))\n\t}\n\t// If there are no errors set a success message\n\tc.Flash().Add(\"success\", \"Pizza was created successfully\")\n\t// and redirect to the pizzas index page\n\treturn c.Redirect(302, \"/pizzas/%s\", pizza.ID)\n}", "func InsertProduct(c *gin.Context) {\n\n\tstatus := 1\n\tmessage := \"Success\"\n\tvar rensponseInsertProduct ResponseInsertProduct\n\tvar newstocks int\n\tvar products Products\n\tvar products_arr []Products\n\tvar stock_ins Stock_Ins\n\tbuyPrice,_ := strconv.Atoi(c.PostForm(\"buy_price\"))\n\tqtY,_ := strconv.Atoi(c.PostForm(\"qty\"))\n\tcurrentdatetime := time.Now().Format(\"2006-01-02 15:04:05\")\n\tstock_ins = Stock_Ins{Sku:c.PostForm(\"sku\"),Buy_Price:buyPrice,Created_Date:currentdatetime,Qty:qtY,Kwitansi:c.PostForm(\"kwitansi\")}\n\tdb := InitDb()\n\ttx := db.Begin()\n\n\tif err := tx.Create(&stock_ins).Error; err != nil {\n\t\ttx.Rollback()\n\t\tstatus = 0\n\t\tmessage = \"failed to insert data stock_ins\"\n\t} else{\n\n\t\tdb.Where(\"sku = ?\", c.PostForm(\"sku\")).First(&products).Limit(1).Scan(&products_arr)\n\n\t\t// its new record or update record?\n\t\tif (len(products_arr) > 0){\n\n\t\t\tfor i,element := range products_arr{\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tnewstocks = element.Stocks + qtY\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := tx.Model(&products).Where(\"sku = ?\",c.PostForm(\"sku\")).Update(\"stocks\", newstocks).Error; err != nil{\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to update data products\"\n\t\t\t}\n\n\n\t\t}else{\n\t\t\t//insert to table products\n\t\t\tproducts = Products{Sku:c.PostForm(\"sku\"),Stocks:qtY,Product_name:c.PostForm(\"product_name\")}\n\t\t\tif err := tx.Create(&products).Error; err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to insert data products\"\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif status == 1 {\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status, Message:message,Data:DataInsertProduct{Stocks:newstocks, Sku:c.PostForm(\"sku\"), Product_name:c.PostForm(\"product_name\"), Buy_Price:buyPrice, Created_Date:currentdatetime}}\n\t}else{\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status,Message:message}\n\t}\n\n\t//transaction commit\n\ttx.Commit()\n\t// Close connection database\n\tdefer db.Close()\n\n\tc.JSON(200, rensponseInsertProduct)\n}", "func (p *Products) AddProduct(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle Post Product\")\n\n\tprod := r.Context().Value(KeyProduct{}).(data.Product)\n\tdata.AddProduct(&prod)\n}", "func (s *Store) Create(c *gin.Context) {\n\n}", "func (r *SoftwareResource) Create(item SoftwareConfig) error {\n\tif err := r.c.ModQuery(\"POST\", BasePath+SoftwareEndpoint, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (pri *ProductRepositoryImpl) StoreProduct(p entity.Product) error {\n\n\t//_, err := pr.conn.Exec(\"INSERT INTO products (itemname,itemtype,quantity,price,description,image)\" +\n\t//\" values(?, ?, ?, ?, ?, ?)\",c.Name, c.ItemType, c.Quantity, c.Price, c.Description, c.Image)\n\n\t//_, err := pri.conn.Exec(\"INSERT INTO products (itemname,itemtype,quantity,price,description,image)\" +\n\t//\t\" values($1, $2, $3, $4, $5, $6)\",p.Name, p.ItemType, p.Quantity, p.Price, p.Description, p.Image)\n\t//\n\t_, err := pri.conn.Exec(\"INSERT INTO products (itemname,quantity,price,description,image)\"+\n\t\t\" values($1, $2, $3, $4, $5)\", p.Name, p.Quantity, p.Price, p.Description, p.Image)\n\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn errors.New(\"Insertion has failed or Item already Exists\")\n\t}\n\n\treturn nil\n}", "func (v OrdersResource) Create(c buffalo.Context) error {\n // Allocate an empty Order\n order := &models.Order{}\n\n // Bind order to the html form elements\n if err := c.Bind(order); err != nil {\n return err\n }\n\n // Get the DB connection from the context\n tx, ok := c.Value(\"tx\").(*pop.Connection)\n if !ok {\n return fmt.Errorf(\"no transaction found\")\n }\n\n // Validate the data from the html form\n verrs, err := tx.ValidateAndCreate(order)\n if err != nil {\n return err\n }\n\n if verrs.HasAny() {\n return responder.Wants(\"html\", func (c buffalo.Context) error {\n // Make the errors available inside the html template\n c.Set(\"errors\", verrs)\n\n // Render again the new.html template that the user can\n // correct the input.\n c.Set(\"order\", order)\n\n return c.Render(http.StatusUnprocessableEntity, r.HTML(\"/orders/new.plush.html\"))\n }).Wants(\"json\", func (c buffalo.Context) error {\n return c.Render(http.StatusUnprocessableEntity, r.JSON(verrs))\n }).Wants(\"xml\", func (c buffalo.Context) error {\n return c.Render(http.StatusUnprocessableEntity, r.XML(verrs))\n }).Respond(c)\n }\n\n return responder.Wants(\"html\", func (c buffalo.Context) error {\n // If there are no errors set a success message\n c.Flash().Add(\"success\", T.Translate(c, \"order.created.success\"))\n\n // and redirect to the show page\n return c.Redirect(http.StatusSeeOther, \"/orders/%v\", order.ID)\n }).Wants(\"json\", func (c buffalo.Context) error {\n return c.Render(http.StatusCreated, r.JSON(order))\n }).Wants(\"xml\", func (c buffalo.Context) error {\n return c.Render(http.StatusCreated, r.XML(order))\n }).Respond(c)\n}", "func (db Database) saveProduct() error {\n\treturn makeError()\n}", "func CreateProducts() *Products {\r\n\tproducts := &Products{\r\n\t\tValues: make(map[uint64]*Product),\r\n\t}\r\n\tproducts.Preferences.PreferencesMap = make(map[string]*ProductsPreferences)\r\n\treturn products\r\n}", "func (v PetsResource) Create(c buffalo.Context) error {\n\t// Allocate an empty Pet\n\tpet := &models.Pet{}\n\n\t// Bind pet to the html form elements\n\tif err := c.Bind(pet); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Get the DB connection from the context\n\ttx := c.Value(\"tx\").(*pop.Connection)\n\n\t// Validate the data from the html form\n\tverrs, err := tx.ValidateAndCreate(pet)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif verrs.HasAny() {\n\t\t// Make pet available inside the html template\n\t\tc.Set(\"pet\", pet)\n\n\t\t// Make the errors available inside the html template\n\t\tc.Set(\"errors\", verrs)\n\n\t\t// Render again the new.html template that the user can\n\t\t// correct the input.\n\t\treturn c.Render(422, r.HTML(\"pets/new.html\"))\n\t}\n\n\t// If there are no errors set a success message\n\tc.Flash().Add(\"success\", \"Pet was created successfully\")\n\n\t// and redirect to the pets index page\n\treturn c.Redirect(302, \"/pets/%s\", pet.ID)\n}", "func (p *Products) AddProduct(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle POST Product\")\n\n\tprod := r.Context().Value(KeyProduct{}).(data.Product)\n\n\tdata.AddProduct(prod)\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 CreateProductImage(c buffalo.Context) error {\n\timages := &models.Images{}\n\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.New(\"Transaction not found\")\n\t}\n\tif err := c.Bind(images); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := tx.Create(images); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn c.Render(201, r.JSON(images))\n}", "func (r ApiOrdersCreateProductRequest) Product(product Product) ApiOrdersCreateProductRequest {\n\tr.product = &product\n\treturn r\n}", "func (prod *Product) store() {\n\tcurrentDir, _ := os.ReadDir(\".\")\n\tfmt.Println(currentDir)\n\n\tcheckForFolder(\"products\")\n\n\tfile, _ := os.Create(\"products/\" + prod.id + \".json\")\n\tprodFolder, _ := os.ReadDir(\"products\")\n\tfmt.Printf(\"%v Products\\n\", len(prodFolder))\n\n\t// Created\n\tcontent := fmt.Sprintf(\"{\\n\\\"id\\\": \\\"%v\\\",\\n\\\"title\\\": \\\"%v\\\",\\n\\\"description\\\": \\\"%v\\\",\\n\\\"price_usd\\\": \\\"%.2f\\\"\\n}\",\n\t\tprod.id,\n\t\tprod.title,\n\t\tprod.description,\n\t\tprod.price,\n\t)\n\n\tfile.WriteString(content)\n\tfile.Close()\n}", "func (planetDeliveryRest *PlanetDeliveryRest) Create(w http.ResponseWriter, r *http.Request) {\n\tvar planet entity.Planet\n\n\terr := json.NewDecoder(r.Body).Decode(&planet)\n\tif err != nil {\n\t\tError(w, \"Failed to decode JSON\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tplanetToInsert := *entity.NewPlanet(planet.Name, planet.Climate, planet.Terrain)\n\n\tnewPlanet, err := planetDeliveryRest.planetUsecase.Create(r.Context(), planetToInsert)\n\tif err != nil {\n\t\tError(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tJSON(w, newPlanet, http.StatusCreated)\n}", "func (s *PaymentStorage) Create(\n\tctx context.Context,\n\tid aggregate.ID,\n\tversion transaction.Version,\n\torganisationID transaction.OrganisationID,\n\tattributes interface{},\n) error {\n\tlogger := log.FromContext(ctx)\n\n\tquery := `INSERT INTO %[1]s (id, version, organisation_id, attributes) VALUES ($1, $2, $3, $4)`\n\tquery = fmt.Sprintf(query, s.table)\n\n\tif logger != nil {\n\t\tlogger.Debugf(\"exec in transaction sql %s, values %+v\", query, []interface{}{\n\t\t\tid,\n\t\t\tversion,\n\t\t\torganisationID,\n\t\t\tattributes,\n\t\t})\n\t}\n\n\treturn execInTransaction(s.db, func(tx *sqlx.Tx) error {\n\t\t_, err := tx.ExecContext(ctx, query, id, version, organisationID, attributes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (s *PurchaseOrdersEndpoint) Create(ctx context.Context, division int, entity *PurchaseOrders) (*PurchaseOrders, error) {\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/purchaseorder/PurchaseOrders\", division) // #nosec\n\te := &PurchaseOrders{}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"POST\", u.String(), entity, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}", "func (products *Products) AddProduct(w http.ResponseWriter, r *http.Request) {\n\tproducts.logger.Println(\"post a new product\")\n\tproduct := r.Context().Value(KeyProduct{}).(data.Product)\n\tdata.AddProduct(&product)\n\treturn\n}", "func Create(responseWriter http.ResponseWriter, request *http.Request) {\n\tfmt.Println(\"[ CreateOrder ]\")\n\tbody, _ := json.Marshal(request.Body)\n\tfmt.Println(\"[ CreateOrder ] Body=\" + string(body))\n\t//params := mux.Vars(request)\n\tvar orderEntity OrderEntity\n\t_ = json.NewDecoder(request.Body).Decode(&orderEntity)\n\n\tvar result OrderEntity = Insert(orderEntity)\n\n\tWriteMessages(result, Topic.TOPIC_SUCCESS)\n\n\tjson.NewEncoder(responseWriter).Encode(result)\n}", "func (sc StoreController) Create(c *gin.Context) {\n\tlog.Debug().Caller().Msg(\"stores create\")\n\tp, err := sc.Storeservice.Create(c)\n\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"InvalidAddress\") {\n\t\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\t\tlog.Error().Caller().Err(err).Send()\n\t\t} else {\n\t\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\t\tlog.Error().Caller().Err(err).Send()\n\t\t}\n\t} else {\n\t\tc.JSON(http.StatusCreated, p)\n\t}\n}", "func (c *DeviceController) Create(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(json.NewDecoder(r.Body))\n\tres := db.PutItem(\"home-devices\", NewDevice(\"hello\", \"world\", \"indeed\"))\n\tc.SendJSON(\n\t\tw,\n\t\tr,\n\t\tres,\n\t\thttp.StatusOK,\n\t)\n}", "func (sp *serviceProposal) create(ctx *gin.Context) {\n\tvar p model.Proposal\n\n\terr := ctx.BindJSON(&p)\n\tif err != nil {\n\t\tNewErrorPaylod(ctx, err)\n\t\treturn\n\t}\n\n\t_, err = sp.db.CreateProposal(ctx, &p)\n\tlog.Println(\"the code should not print\")\n\tif err != nil {\n\t\tError(ctx, err)\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, p)\n}", "func Create(ctx *gin.Context, data interface{}) {\n\tctx.JSON(http.StatusCreated, gin.H{\"code\": merrors.ErrSuccess, \"data\": nil})\n\treturn\n}", "func (c *Client) Create(data *CreateParams) (*xendit.Disbursement, *xendit.Error) {\n\treturn c.CreateWithContext(context.Background(), data)\n}", "func (material *Material) Create(ctx *aero.Context) error {\n\tmaterial.ID = GenerateID(\"Material\")\n\tmaterial.Created = utils.DateTimeUTC()\n\tmaterial.CreatedBy = GetUserFromContext(ctx).ID\n\treturn nil\n}", "func (e *Department) Create(storage ent.Storage) error { return ent.CreateEnt(e, storage) }", "func BuildCreatePayload(productCreateBody string, productCreateToken string) (*product.CreatePayload, error) {\n\tvar err error\n\tvar body CreateRequestBody\n\t{\n\t\terr = json.Unmarshal([]byte(productCreateBody), &body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid JSON for body, \\nerror: %s, \\nexample of valid JSON:\\n%s\", err, \"'{\\n \\\"code\\\": \\\"123asd123123asd\\\",\\n \\\"cost_price\\\": 123,\\n \\\"founder_id\\\": \\\"519151ca-6250-4eec-8016-1e14a68dc448\\\",\\n \\\"image\\\": \\\"/images/123.jpg\\\",\\n \\\"is_shelves\\\": false,\\n \\\"market_price\\\": 123,\\n \\\"name\\\": \\\"灌装辣椒\\\",\\n \\\"note\\\": \\\"备注\\\",\\n \\\"size\\\": \\\"瓶\\\",\\n \\\"type\\\": 1,\\n \\\"unit\\\": 1\\n }'\")\n\t\t}\n\t\tif !(body.Unit == 1 || body.Unit == 2 || body.Unit == 3 || body.Unit == 4 || body.Unit == 5 || body.Unit == 6 || body.Unit == 7 || body.Unit == 8) {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.unit\", body.Unit, []interface{}{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t}\n\t\tif !(body.Type == 1 || body.Type == 2 || body.Type == 3 || body.Type == 4 || body.Type == 5 || body.Type == 6 || body.Type == 7 || body.Type == 8) {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.type\", body.Type, []interface{}{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar token string\n\t{\n\t\ttoken = productCreateToken\n\t}\n\tv := &product.CreatePayload{\n\t\tName: body.Name,\n\t\tUnit: body.Unit,\n\t\tCostPrice: body.CostPrice,\n\t\tMarketPrice: body.MarketPrice,\n\t\tNote: body.Note,\n\t\tImage: body.Image,\n\t\tCode: body.Code,\n\t\tSize: body.Size,\n\t\tType: body.Type,\n\t\tIsShelves: body.IsShelves,\n\t\tFounderID: body.FounderID,\n\t}\n\tv.Token = token\n\n\treturn v, nil\n}", "func (c *ProposalController) Create(ctx *app.CreateProposalContext) error {\n\treturn nil\n}", "func (cartItem CartItem) create() (Entity, error) {\n\n\t_item := cartItem\n\tif err := db.Create(&_item).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := _item.GetPreloadDb(false,false, nil).First(&_item,_item.Id).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := (Order{Id: _item.OrderId, AccountId: _item.AccountId}).UpdateDeliveryData(); err != nil {\n\t\tlog.Println(\"Error update cart item: \", err)\n\t}\n\tif err := (Order{Id: _item.OrderId, AccountId: _item.AccountId}).UpdateCost(); err != nil {\n\t\tlog.Println(\"Error update cart item: \", err)\n\t}\n\n\tvar entity Entity = &_item\n\n\treturn entity, nil\n}", "func (r *repositorySupplier) EntityCreate(input *schemas.SchemaSupplier) (*models.ModelSupplier, schemas.SchemaDatabaseError) {\n\tvar supplier models.ModelSupplier\n\tphone, _ := strconv.ParseUint(input.Phone, 10, 64)\n\tsupplier.Name = input.Name\n\tsupplier.Phone = phone\n\tsupplier.Address = input.Address\n\n\terr := make(chan schemas.SchemaDatabaseError, 1)\n\n\tdb := r.db.Model(&supplier)\n\n\tcheckSupplierName := db.Debug().First(&supplier, \"name = ?\", supplier.Name)\n\n\tif checkSupplierName.RowsAffected > 0 {\n\t\terr <- schemas.SchemaDatabaseError{\n\t\t\tCode: http.StatusConflict,\n\t\t\tType: \"error_create_01\",\n\t\t}\n\t\treturn &supplier, <-err\n\t}\n\n\tcheckSupplierPhone := db.Debug().First(&supplier, \"phone = ?\", supplier.Phone)\n\n\tif checkSupplierPhone.RowsAffected > 0 {\n\t\terr <- schemas.SchemaDatabaseError{\n\t\t\tCode: http.StatusConflict,\n\t\t\tType: \"error_create_02\",\n\t\t}\n\t\treturn &supplier, <-err\n\t}\n\n\taddSupplier := db.Debug().Create(&supplier).Commit()\n\n\tif addSupplier.RowsAffected < 1 {\n\t\terr <- schemas.SchemaDatabaseError{\n\t\t\tCode: http.StatusForbidden,\n\t\t\tType: \"error_create_03\",\n\t\t}\n\t\treturn &supplier, <-err\n\t}\n\n\terr <- schemas.SchemaDatabaseError{}\n\treturn &supplier, <-err\n}", "func (t *SimpleChaincode) addProduct(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tfmt.Println(\"Add product...\")\n\tvar product Product\n\tvar err error\n\t\n\tisExistAsBytes,_ := stub.GetState(args[0])\n\n\tif(isExistAsBytes != nil){\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tproduct.SerialNo=args[0]\n\tproduct.BatchId=args[1]\n\tproduct.ModelNo=args[2]\n\tproduct.ModelName=args[3]\n\tproduct.DateOfMfg =args[4]\n\tproduct.CftId=args[5]\n\tproduct.Price=args[6]\n\tproduct.Specification=args[7]\n\tproduct.Status=\"MFG\"\n\tproduct.Ownership=\"Rolex Pvt Ltd\"\n\tproduct.DealerId=\"\"\n\tproduct.DealerName=\"\"\n\tproduct.ShippingDate =\"\"\n\tproduct.DateOfPurchase=\"\"\n\tproduct.Insurance=\"\"\n product.InsuranceExpiry=\"\"\n\tproduct.ServiceId=\"\"\n\tproduct.ServiceHistory=\"\"\n\t\n\tproductAsBytes, _ := json.Marshal(product)\n\terr = stub.PutState(product.SerialNo, productAsBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n//update all batches to the array whose key is \"AllWatches\"\n\tAllWatchesAsBytes, err := stub.GetState(\"AllWatches\")\n\n\tvar allWatches AllWatches\n\n\terr= json.Unmarshal(AllWatchesAsBytes, &allWatches)\n\tallWatches.AllWatches=append(allWatches.AllWatches,product.SerialNo)\n\n\tallwatchesAsBytes,_ :=json.Marshal(allWatches)\n\terr = stub.PutState(\"AllWatches\", allwatchesAsBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n//-----------------------------------------------------------\n\treturn shim.Success(nil)\n}", "func Insert (w http.ResponseWriter, r *http.Request){\n\tif r.Method == \"POST\"{ // se a requisição for do metodo POST, criar um novo produto\n\t\t//buscando os dados\n\t\tnome:= r.FormValue(\"nome\")\n\t\tdescricao := r.FormValue(\"descricao\")\n\t\tpreco := r.FormValue(\"preco\")\n\t\tquantidade := r.FormValue(\"quantidade\")\n\n\n\t//convertendo os valores necessarios(os valores que vem pra nós sao do tipo string) temos q converter;\n\t\t//convertendo string para float64\n\t\tprecoConvertidoParaFloat, err := strconv.ParseFloat(preco, 64)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do preço:\", err)\n\t\t}\n\t\t//convertendo string par int\n\t\tquantidadeConvertidaParaInt, err := strconv.Atoi(quantidade)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do quantidade:\", err)\n\t\t}\n\n\t\t//Pegar os valores e criar (funcao do models)\n\t\tmodels.CriaNovoProduto(nome, descricao, precoConvertidoParaFloat, quantidadeConvertidaParaInt)\n\t}\n\t//depois de passar os dados redirecionar para a pagina inicial\n\thttp.Redirect(w, r, \"/\", 301)\n\treturn\n}", "func (t *ProductChaincode) initProduct(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\t// For loop on quantity\n\tquantity, _ := strconv.Atoi(args[5])\n\n\tfor i := 0; i < quantity; i++ {\n\n\t\tid := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\ttoInt := id.Int()\n\t\ttagID := strconv.Itoa(toInt)\n\n\t\tfinalProduct := tagID\n\t\tvar finalArgs []string\n\t\tfinalArgs = append(finalArgs, finalProduct)\n\t\tfinalArgs = append(finalArgs, args[1])\n\t\tfinalArgs = append(finalArgs, args[2])\n\t\tfinalArgs = append(finalArgs, args[3])\n\t\tfinalArgs = append(finalArgs, args[4])\n\n\t\tvar product Product\n\t\tif err := product.FillFromArguments(finalArgs); err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tif product.ExistsIn(stub) {\n\t\t\tcompositeKey, _ := product.ToCompositeKey(stub)\n\t\t\treturn shim.Error(fmt.Sprintf(\"product with the key %s already exists\", compositeKey))\n\t\t}\n\n\t\t// TODO: set owner from GetCreatorOrg\n\t\tproduct.Value.State = stateRegistered\n\t\tproduct.Value.Name = args[0]\n\n\t\tif err := product.UpdateOrInsertIn(stub); err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\t// TODO: think about index usability\n\t\t// ==== Index the product to enable state-based range queries, e.g. return all Active products ====\n\t\t// An 'index' is a normal key/value entry in state.\n\t\t// The key is a composite key, with the elements that you want to range query on listed first.\n\t\t// In our case, the composite key is based on stateIndexName~state~name.\n\t\t// This will enable very efficient state range queries based on composite keys matching stateIndexName~state~*\n\t\t//stateIndexKey, err := stub.CreateCompositeKey(stateIndexName, []string{strconv.Itoa(product.Value.State), product.Key.Name})\n\t\t//if err != nil {\n\t\t// return shim.Error(err.Error())\n\t\t//}\n\t\t//// Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the product.\n\t\t//// Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value\n\t\t//value := []byte{0x00}\n\t\t//stub.PutState(stateIndexKey, value)\n\t}\n\treturn shim.Success(nil)\n\n}", "func (s *SalesItemPricesEndpoint) Create(ctx context.Context, division int, entity *SalesItemPrices) (*SalesItemPrices, error) {\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/logistics/SalesItemPrices\", division) // #nosec\n\te := &SalesItemPrices{}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"POST\", u.String(), entity, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}", "func init_product(stub shim.ChaincodeStubInterface, args []string) (pb.Response) {\n\tvar err error\n\tfmt.Println(\"starting init_product\")\n\n\n\tif len(args) != 11 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 11\")\n\t}\n\n\n\t//input sanitation\n\terr = sanitize_arguments(args)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tvar product Product\n\n\tproduct.ObjectType = \"product\"\n\n\tproduct.GroupId = args[0]\n\tproduct.GroupName = strings.ToLower(args[1])\n\tproduct.RegisterUserId = args[2]\n\tproduct.RegisterUserName = strings.ToLower(args[3])\n\tproduct.ProductId = args[4]\n\tproduct.RegisterDate = strings.ToLower(args[5])\n\tproduct.ProductName =strings.ToLower(args[6])\n\tproduct.ProductWeight = strings.ToLower(args[7])\n\tproduct.ProductVolume = strings.ToLower(args[8])\n\tproduct.MainIngredientName = strings.ToLower(args[9])\n\tproduct.FORCoin,err = strconv.Atoi(args[10])\n\n\n\tproductAsBytes, _ :=json.Marshal(product)\n\n\tfmt.Println(\"writing product to state\")\n\n\tfmt.Println(string(productAsBytes))\n\tfmt.Println(\"productid\",product.ProductId)\n\terr = stub.PutState(product.ProductId, productAsBytes) //store owner by its Id\n\tif err != nil {\n\t\tfmt.Println(\"Could not store product\")\n\t\treturn shim.Error(err.Error())\n\t}\n\n//\tif err != nil {\n//\t\treturn shim.Error(\"3rd argument must be a numeric string\")\n//\t}\n\n\n\t//build the product json string manually\n//\tstr := `{\n//\t\t\"docType\":\"product\",\n//\t\t\"groupid\": \"` + groupid + `\",\n//\t\t\"groupname\": \"sarang\",\n//\t\t\"registeruserid\": \"sarng2\",\n//\t\t\"registerusername\": \"sarararng\",\n//\t\t\"productid\": \"` + productid + `\",\n//\t\t\"registerdate\": \"` + registerdate + `\",\n//\t\t\"productname\": \"` + productname + `\",\n//\t\t\"productweight\": \"` + productweight + `\",\n//\t\t\"productvolume\": \"` + productvolume + `\",\n//\t\t\"mainingredientname\": \"` + mainingredientname + `\", \n//\t\t\"forcoin\": ` + strconv.Itoa(forcoin) + `, \n//\t}`\n//\terr = stub.PutState(productid, []byte(str)) //store product with id as key\n//\n//\tAvals ,err :=stub.GetState(productid)\n//\tAvalsString :=string(Avals)\n//\n//\tfmt.Println(\"product?\",AvalsString)\n//\n//\n//\tif err != nil {\n//\t\treturn shim.Error(err.Error())\n//\t}\n//\n\tfmt.Println(\"- end init_product\")\n\n\treturn shim.Success(nil)\n}", "func (s *permisoService) Create(p *model.Permiso) (*model.Permiso, error) {\n\tp.ID = uuid.New().String()\n\tp.Status = true\n\tp.CreatedAt = time.Now()\n\tp.UpdatedAt = time.Now()\n\n\treturn repo.Create(p)\n\n\t// return nil, nil\n}", "func (v SongsResource) Create(c buffalo.Context) error {\n\t// Allocate an empty Song\n\tsong := &models.Song{}\n\n\t// Bind song to the html form elements\n\tif err := c.Bind(song); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\t// Validate the data from the html form\n\tverrs, err := tx.ValidateAndCreate(song)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif verrs.HasAny() {\n\t\t// Make the errors available inside the html template\n\t\tc.Set(\"errors\", verrs)\n\n\t\t// Render again the new.html template that the user can\n\t\t// correct the input.\n\t\treturn c.Render(422, r.Auto(c, song))\n\t}\n\n\t// If there are no errors set a success message\n\tc.Flash().Add(\"success\", \"Song was created successfully\")\n\n\t// and redirect to the songs index page\n\treturn c.Render(201, r.Auto(c, song))\n}", "func (mr *MockStorageMockRecorder) CreateProduct(ctx, product interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateProduct\", reflect.TypeOf((*MockStorage)(nil).CreateProduct), ctx, product)\n}", "func (s *StageForDeliveryReversalsEndpoint) Create(ctx context.Context, division int, entity *StageForDeliveryReversals) (*StageForDeliveryReversals, error) {\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/manufacturing/StageForDeliveryReversals\", division) // #nosec\n\te := &StageForDeliveryReversals{}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"POST\", u.String(), entity, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}" ]
[ "0.79167455", "0.7904428", "0.78099734", "0.7786249", "0.77057517", "0.7692949", "0.76893574", "0.76699275", "0.7651793", "0.76174074", "0.7583855", "0.74974906", "0.74508786", "0.74497974", "0.74203223", "0.73531", "0.73341", "0.7308653", "0.73027235", "0.7239612", "0.723393", "0.717116", "0.7158292", "0.7144383", "0.7125346", "0.70407176", "0.70278615", "0.700062", "0.6944955", "0.6919884", "0.68360215", "0.6834742", "0.68092066", "0.6734748", "0.67302084", "0.6723731", "0.6712012", "0.6708163", "0.6692082", "0.66816664", "0.6666636", "0.6636544", "0.6621844", "0.6595259", "0.65946597", "0.6571657", "0.6569542", "0.6555403", "0.64423394", "0.63977605", "0.63654757", "0.6333793", "0.6312207", "0.6277456", "0.6273172", "0.6269254", "0.6268562", "0.62604", "0.62258804", "0.6178999", "0.61699", "0.61680067", "0.614646", "0.61374766", "0.6120197", "0.6109631", "0.610421", "0.6102858", "0.6102817", "0.6101748", "0.61010337", "0.61004096", "0.6084857", "0.6055302", "0.6042946", "0.60344243", "0.6017809", "0.60105383", "0.6001791", "0.6000849", "0.59753025", "0.5963278", "0.5945726", "0.5945295", "0.5935984", "0.5903897", "0.59037536", "0.5889407", "0.5860288", "0.5845989", "0.58446616", "0.58197844", "0.5819345", "0.5819177", "0.58187044", "0.58174044", "0.5815777", "0.5814288", "0.5804885", "0.5804679" ]
0.62068737
59
Update just to update product based on its ID
func (db *ProductRepo) Update(id int) (message string) { update := "this is update" return update }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func UpdateProductByID(c *gin.Context) {\n\t// Get model if exist\n\tvar product models.Product\n\tif err := database.Connector.Where(\"id = ?\", c.Param(\"id\")).First(&product).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\t// Validate input\n\tvar input models.Product\n\tif err := c.ShouldBindJSON(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tdatabase.Connector.Model(&product).Updates(input)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": product})\n}", "func UpdateProduct(c *gin.Context) {\n\n\tid := c.Param(\"id\")\n\t//id := c.Query(\"id\")\n\tfmt.Println(\"id is: \", id)\n\tdb := DbConn()\n\tvar prod Products\n\tdbc := db.Debug().Where(\"id = ?\", id).First(&prod)\n\tif dbc.Error != nil {\n\t\tfmt.Println(\"Error while updating: \", dbc.Error)\n\n\t\tc.String(http.StatusBadRequest, \"Error while updating\")\n\t}\n\tif e := c.BindJSON(&prod); e != nil {\n\t\tfmt.Println(\"Error in req format\", e)\n\t\tc.JSON(http.StatusBadRequest, \"Error in req format\")\n\t}\n\tdb.Save(&prod)\n\tfmt.Println(\"updated successfully\")\n\tc.String(http.StatusOK, \"Success\")\n}", "func updateProduct(dbRef *pg.DB) {\n\tnewPI := &db.ProductItem{\n\t\tID: 11,\n\t\tName: \"Product 6\",\n\t}\n\tnewPI.Update(dbRef)\n}", "func (ph *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : PATCH /app/product/{id_product} API hit!\")\n\tvar request UpdateProductRequest\n\tbody := json.NewDecoder(r.Body)\n\terr := body.Decode(&request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.DecodeErrorCode, err.Error())\n\t\treturn\n\t}\n\tproductID, err := strconv.Atoi(chi.URLParam(r, \"id_product\"))\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.DecodeErrorCode, errors.New(\"invalid id_product\").Error())\n\t\treturn\n\t}\n\trequest.ProductID = productID\n\terr = ph.ps.UpdateProduct(r.Context(), &request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tif err.Error() == utils.NothingToUpdateProductError {\n\t\t\tutils.Fail(w, 400, utils.NothingToUpdateProductErrorCode, err.Error())\n\t\t\treturn\n\t\t} else if err.Error() == utils.InvalidProductIDError {\n\t\t\tutils.Fail(w, 400, utils.InvalidProductIDErrorCode, err.Error())\n\t\t\treturn\n\t\t}\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : product updated! id_product : \", productID)\n\tutils.Send(w, 200, nil)\n}", "func (e *engine) UpdateOne(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\n\tvar product = &domain.Product{}\n\t// check is valid json for product\n\terr = c.BindToJson(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tproduct.Iid = id\n\tres, err := e.ProductLogic.UpdateProduct(product)\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\n\t}\n\tc.JSON(200, res)\n}", "func (fapi *FyndiqAPI) UpdateProduct(id int, updateData []byte) error {\n\t_, err := httpRequest(\"PUT\", fapi.productURL(id), bytes.NewBuffer(updateData))\n\treturn err\n}", "func UpdateProduct(id primitive.ObjectID, p *Product, db *mongo.Client) error {\n\t//find the product with the same id and update it.\n\tprodCol := db.Database(DBNAME).Collection(COLLNAME)\n\n\tfilter := bson.M{\"_id\": id}\n\tresult, err := prodCol.UpdateOne(context.TODO(), filter, bson.D{{\"$set\", p}}) //TODO: omitempty on the model\n\tif err != nil {\n\t\treturn err\n\t} else if result.ModifiedCount == 0 {\n\t\tmsg := \"Failed to update product with id = \" + id.Hex()\n\t\treturn errors.New(msg)\n\t}\n\treturn nil\n}", "func (products *Products) UpdateProduct(w http.ResponseWriter, r *http.Request) {\n\tproducts.logger.Println(\"handle PUT request\")\n\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\thttp.Error(w, \"unable to parse id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tproduct := r.Context().Value(KeyProduct{}).(data.Product)\n\n\terr = data.UpdateProduct(id, &product)\n\tif err == data.ErrProductNotFound {\n\t\thttp.Error(w, \"product not found\", http.StatusNotFound)\n\t\treturn\n\t} else if err != nil {\n\t\t// the product was found but something else went wrong\n\t\thttp.Error(w, \"could not update the product\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\treturn\n}", "func (pm *ProductModel) Update(product Product) error {\n\tif _, err := pm.DB.Query(UPDATE_PRODUCT_STMT, product.ProductName, product.Price, product.ShortDescription, product.ID); err != nil {\n\t\tlog.Printf(\"error occurred on updating a specific product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (*Products) Update(product *Products) (Products, error) {\n\n\t_, err := model.Get(product.ID)\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Get)\", \"Product doesn't exist\")\n\t\treturn Products{}, err\n\t}\n\n\tstmt, err := db.Prepare(\n\t\t\"update products \" +\n\t\t\t\"set name = $1, \" +\n\t\t\t\"unit = $2, \" +\n\t\t\t\"date_updated = now() \" +\n\t\t\t\"where id = $3\")\n\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Prepare)\", err)\n\t\treturn Products{}, err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(product.Name, product.Unit, product.ID)\n\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Exec)\", err)\n\t\treturn Products{}, err\n\t}\n\n\treturn *product, nil\n\n}", "func UpdateProduct(c *gin.Context) {\n\tvar product Models.Product\n\tid := c.Params.ByName(\"id\")\n\terr := Models.GetProductByID(&product, id)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, product)\n\t}\n\tc.BindJSON(&product)\n\terr = Models.UpdateProduct(&product, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func UpdateProduct(id int, p *Product) error {\n\t_, pos, err := findProduct(id)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.ID = id\n\n\tproductList[pos] = p\n\treturn nil\n}", "func (p *Products) PUT(rw http.ResponseWriter, r *http.Request) {\n\t// fetch the id from the query string\n\tid, err := getProductID(r)\n\tif err != nil {\n\t\tp.l.Println(\"[ERROR] unable to find product id in URL\", r.URL.Path, err)\n\t\thttp.Error(rw, \"Missing product id, url should be formatted /products/[id] for PUT requests\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tprod := r.Context().Value(KeyProduct{}).(data.Product)\n\n\t// override the product id\n\tprod.ID = id\n\n\terr = data.UpdateProduct(prod)\n\tif err == data.ErrProductNotFound {\n\t\tp.l.Println(\"[ERROR] product not found\", err)\n\t\thttp.Error(rw, \"Product not found in database\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tp.l.Printf(\"[DEBUG] Updated product: %#v\\n\", prod)\n\n\t// write the no content success header\n\trw.WriteHeader(http.StatusNoContent)\n}", "func update(c echo.Context) error {\n\tdefer c.Request().Body.Close()\n\tprod := product{}\n\terr := json.NewDecoder(c.Request().Body).Decode(&prod)\n\tif err != nil {\n\t\tlog.Error(\"failed to parse product info\", err)\n\t\treturn apiErrProductInfoParseFailed().render(c)\n\t}\n\terr = prod.validate()\n\tif err != nil {\n\t\tlog.Error(\"validation failed\", err)\n\t\treturn apiErrValidationFailed(err).render(c)\n\t}\n\n\tid := prod.ProductID\n\terr = pg_persist.UpdateProduct(id, prod.CurrentPrise.Value, prod.CurrentPrise.CurrencyCode)\n\tif err != nil {\n\t\tlog.Error(\"product update failed\", err)\n\t\treturn apiErrFailedUpdateProduct().render(c)\n\t}\n\n\ti := prod.ProductDetails\n\terr = mg_persist.UpdateProduct(id, i.Name, i.Description, i.Type)\n\tif err != nil {\n\t\tlog.Error(\"product update failed\", err)\n\t\treturn apiErrFailedUpdateProduct().render(c)\n\t}\n\n\treturn c.String(http.StatusOK, `{\"message\":\"update success\"}`)\n}", "func UpdateProduct(id int, p *Product) error {\n\t_, pos, err := findProduct(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.ID = id\n\tproductList[pos] = p\n\n\treturn nil\n}", "func (h *ProductHandler) UpdateProduct(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar updateProduct updateProductData\n\tbody, _ := ioutil.ReadAll(r.Body)\n\terr := json.Unmarshal(body, &updateProduct)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\torigProduct, err := h.ProductUsecase.GetByID(ctx, updateProduct.ID)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, models.ErrNotFound.Error())\n\t\treturn\n\t}\n\n\tproduct := models.Product{\n\t\tID: updateProduct.ID,\n\t\tName: updateProduct.Name,\n\t\tSKU: updateProduct.SKU,\n\t}\n\n\terr = h.ProductUsecase.Update(ctx, &product)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\terr = h.ProductCatUsecase.DeleteByProductID(ctx, product.ID)\n\n\t// Revert when get an error update link product category\n\tif err != nil {\n\t\t_ = h.ProductUsecase.Update(ctx, origProduct)\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\terr = h.PriceUsecase.DeleteByProductID(ctx, product.ID)\n\t// Revert when get an error update price\n\tif err != nil {\n\t\t_ = h.ProductUsecase.Update(ctx, origProduct)\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tfor _, cat := range updateProduct.CategoryID {\n\t\tcat := &models.ProductCategory{\n\t\t\tProductID: updateProduct.ID,\n\t\t\tCategoryID: cat,\n\t\t}\n\n\t\terr = h.ProductCatUsecase.Create(ctx, cat)\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, price := range updateProduct.Price {\n\t\t_price := models.ProductPrice{\n\t\t\tAmount: price.Amount,\n\t\t\tPrice: price.Price,\n\t\t\tProductID: product.ID,\n\t\t}\n\n\t\terr = h.PriceUsecase.Create(ctx, &_price)\n\n\t\tif err != nil {\n\t\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tutils.JSON(w, http.StatusOK, product)\n}", "func UpdateProduct(c echo.Context) error {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_INVALID\", \"ID invalid\"))\n\t}\n\tvar objRequest types.ProductUpdate\n\tif err := c.Bind(&objRequest); err != nil {\n\t\tlog.Error(err)\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_ERR\", \"Có lỗi xảy ra, vui lòng kiểm tra lại thông tin\"))\n\t}\n\tif err := c.Validate(&objRequest); err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_INVALID\", err.Error()))\n\t}\n\n\tdata, err := db.UpdateProduct(id, &objRequest)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotAcceptable, types.ParseStatus(\"NOT_ACCEPTED\", err.Error()))\n\t}\n\treturn c.JSON(http.StatusOK, data)\n}", "func UpdateProduct(w http.ResponseWriter, r *http.Request) {\n\tvar product types.Product\n\terr := readBody(r, &product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\tid := httprouter.GetParam(r, \"id\")\n\n\tupdatedProduct, err := repo.UpdateProduct(r.Context(), id, product)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, updatedProduct, http.StatusOK)\n}", "func UpdateProduct(id int64, product entity.Product) int64 {\n\tdb := CreateConnection()\n\tdefer db.Close()\n\n\tsqlStatement := `update product set \n\tcode=$2, name=$3, description=$4, price=$5, quantity_stock=$6,\n\tstatus=$7, category=$8 \n\twhere id=$1`\n\n\tresponse, err := db.Exec(sqlStatement,\n\t\tid, product.Code, product.Name, product.Description,\n\t\tproduct.Price, product.QuantityStock, product.Status,\n\t\tproduct.Category)\n\n\tif err != nil {\n\t\tlog.Print(\"Unable to execute the query \", err)\n\t}\n\n\trowsAffected, err := response.RowsAffected()\n\tif err != nil {\n\t\tlog.Print(\"Error while checking the affected rows. \", err)\n\t}\n\tlog.Print(\"Total rows/record affected \", rowsAffected)\n\n\treturn rowsAffected\n}", "func (c *Chef) Update(id string, v interface{}) error {\n\tpdt, ok := v.(model.Product)\n\tif !ok {\n\t\treturn ErrUnsupportedType\n\t}\n\tif err := pdt.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tstmt := fmt.Sprintf(`UPDATE %s SET (\"name\", \"price\", \"weight\", \"available\", \"updated_at\") = ('%s', %d, %d, %t, CURRENT_TIMESTAMP)\n\t\tWHERE \"id\"='%s' AND \"deleted\"=FALSE`, c.table, pdt.Name, pdt.Price, pdt.Weight, pdt.Available, id)\n\n\treturn c.db.Exec(stmt)\n}", "func (d *Dao) UpdateProduct(c context.Context, p *model.Product) (res int64, err error) {\n\tvar r sql.Result\n\tif r, err = d.db.Exec(c, _updateProductSQL, p.Name, p.GroupIDs, p.State, p.ID); err != nil {\n\t\tlog.Error(\"d.DeleteProduct.Exec error(%+v), product(%+v)\", err, p)\n\t\treturn\n\t}\n\tif res, err = r.RowsAffected(); err != nil {\n\t\tlog.Error(\"d.DeleteProduct.RowsAffected error(%+v), product(%+v)\", err, p)\n\t}\n\treturn\n}", "func (pri *ProductRepositoryImpl) UpdateProduct(p entity.Product) error {\n\n\t//_, err := pri.conn.Exec(\"UPDATE products SET itemname=?,itemtype=?,\" +\n\t//\t\"quantity=?,price=?,description=?,image=? WHERE id=?\",\n\t//\tc.Name, c.ItemType, c.Quantity, c.Price, c.Description, c.Image, c.ID)\n\n\t//_, err := pri.conn.Exec(\"UPDATE products SET itemname=$1,itemtype=$2,\" +\n\t//\t\"quantity=$3,price=$4,description=$5,image=$6 WHERE id=$7\",\n\t//\tp.Name, p.ItemType, p.Quantity, p.Price, p.Description, p.Image, p.ID)\n\n\t_, err := pri.conn.Exec(\"UPDATE products SET itemname=$1,\"+\n\t\t\"quantity=$2,price=$3,description=$4,image=$5 WHERE id=$6\",\n\t\tp.Name, p.Quantity, p.Price, p.Description, p.Image, p.ID)\n\tif err != nil {\n\t\treturn errors.New(\"Update has failed\")\n\t}\n\n\treturn nil\n}", "func (s Service) Update(ctx context.Context, req *productpb.UpdateRequest) (product *productpb.Product, err error) {\n\tvar updateParams bson.M\n\tif err = mapstructure.Decode(req, &updateParams); err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tupdateLowerParams := make(bson.M, len(updateParams))\n\tfor key, val := range updateParams {\n\t\tr := []rune(key)\n\t\tkey = strings.ToLower(string(r[0])) + string(r[1:])\n\t\tupdateLowerParams[strings.ToLower(key)] = val\n\t}\n\tupdateQuery := &proxy.UpdateParam{\n\t\tFilter: bson.M{\"id\": req.Id},\n\t\tUpdate: updateLowerParams,\n\t\tUpsert: false,\n\t\tMulti: false,\n\t\tAmp: s.Amplifier,\n\t}\n\tchangeInfo, err := s.Storage.Update(ctx, updateQuery)\n\tif err != nil {\n\t\treturn\n\t}\n\tlog.Info(changeInfo)\n\tproduct, err = s.Get(ctx, &productpb.GetRequest{Id: req.Id})\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\treturn\n}", "func UpdateProduct(p *Product) error {\n\ti := findIndexByProductID(p.ID)\n\tif i == -1 {\n\t\treturn ErrProductNotFound\n\t}\n\n\tproductList[i] = p\n\n\treturn nil\n}", "func (m *ProductModel) ProductUpdate(user Product) error {\n\terr := db.C(PRODUCT).UpdateId(user.ID, &user)\n\treturn err\n}", "func (t *ProductChaincode) updateProduct(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar product, productToUpdate Product\n\tif err := product.FillFromArguments(args); err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tproductToUpdate.Key = product.Key\n\n\tif !productToUpdate.ExistsIn(stub) {\n\t\tcompositeKey, _ := productToUpdate.ToCompositeKey(stub)\n\t\treturn shim.Error(fmt.Sprintf(\"product with the key %s doesn't exist\", compositeKey))\n\t}\n\n\tif err := productToUpdate.LoadFrom(stub); err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tif !checkStateValidity(productStateMachine, productToUpdate.Value.State, product.Value.State) {\n\t\treturn shim.Error(fmt.Sprintf(\"product state cannot be updated from %d to %d\",\n\t\t\tproductToUpdate.Value.State, product.Value.State))\n\t}\n\n\t// TODO; check if creator == productToUpdate owner\n\tif productToUpdate.Value.Owner != product.Value.Owner {\n\t\treturn shim.Error(fmt.Sprintf(\"ownership cannot be transferred via product updating (from %s to %s)\",\n\t\t\tproductToUpdate.Value.Owner, product.Value.Owner))\n\t}\n\n\t//oldState := productToUpdate.Value.State\n\n\tproductToUpdate.Value.Desc = product.Value.Desc\n\tproductToUpdate.Value.State = product.Value.State\n\tproductToUpdate.Value.LastUpdated = product.Value.LastUpdated\n\n\tif err := productToUpdate.UpdateOrInsertIn(stub); err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t//// maintain the index\n\t//if productToUpdate.Value.State != oldState {\n\t// //delete old index\n\t// stateIndexKey, err := stub.CreateCompositeKey(stateIndexName,\n\t// []string{strconv.Itoa(oldState), productToUpdate.Key.Name})\n\t// if err != nil {\n\t// return shim.Error(err.Error())\n\t// }\n\t//\n\t// // Delete index entry to state.\n\t// err = stub.DelState(stateIndexKey)\n\t// if err != nil {\n\t// return shim.Error(\"Failed to delete state:\" + err.Error())\n\t// }\n\t// //create new index\n\t// stateIndexKey, err = stub.CreateCompositeKey(stateIndexName,\n\t// []string{strconv.Itoa(productToUpdate.Value.State), productToUpdate.Key.Name})\n\t// if err != nil {\n\t// return shim.Error(err.Error())\n\t// }\n\t// // Save index entry to state. Only the key name is needed, no need to store a duplicate copy of the product.\n\t// // Note - passing a 'nil' value will effectively delete the key from state, therefore we pass null character as value\n\t// value := []byte{0x00}\n\t// stub.PutState(stateIndexKey, value)\n\t//}\n\n\treturn shim.Success(nil)\n}", "func (s *Controller) handleUpdateProduct(c *gin.Context) {\n\tvar product entity.Product\n\n\terr := c.ShouldBindJSON(&product)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\trestErr := resterrors.NewBadRequestError(\"Invalid json body\")\n\t\tc.JSON(restErr.StatusCode, restErr)\n\t\treturn\n\t}\n\n\tproductID, errID := s.getIDParameter(c.Param(\"id\"))\n\tif errID != nil {\n\t\tc.JSON(errID.StatusCode, errID)\n\t\treturn\n\t}\n\n\tproduct.ID = productID\n\n\tresProduct, updateErr := s.productService.UpdateProduct(product)\n\tif updateErr != nil {\n\t\tc.JSON(updateErr.StatusCode, updateErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, resProduct)\n}", "func (service *Service) UpdateProduct(request *restful.Request, response *restful.Response) {\n\tvar req models.ProductRequest\n\tif err := request.ReadEntity(&req); err != nil {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"unable parse request body\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to parse request body:\", err)\n\n\t\treturn\n\t}\n\n\tproduct := models.Product{\n\t\tProductID: req.ProductID,\n\t\tName: req.Name,\n\t\tDescription: req.Description,\n\t\tPrice: req.Price,\n\t\tPaymentID: req.PaymentID,\n\t\tCategoryID: req.CategoryID,\n\t\tUserID: req.UserID,\n\t\tImage: req.Image,\n\t}\n\n\tupdatedProduct, err := service.server.UpdateProduct(product)\n\tif err == dao.ErrRecordNotFound {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"product not found\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to update product:\", err)\n\n\t\treturn\n\t}\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageDatabaseError,\n\t\t\t\"unable to update product\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to update product:\", err)\n\n\t\treturn\n\t}\n\n\tresult := &models.UpdateProductResponse{\n\t\tResult: *updatedProduct,\n\t}\n\n\twriteResponse(response, http.StatusAccepted, result)\n}", "func UpdateProduct(id int, newData Product) *Product {\n\tprodToUpdate, _, err := FindProduct(id)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t// Grab the value of CreatedOn before we replace\n\tcreatedOn := prodToUpdate.CreatedOn\n\n\t*prodToUpdate = newData\n\tprodToUpdate.ID = id\n\tprodToUpdate.CreatedOn = createdOn\n\tprodToUpdate.UpdatedOn = time.Now().UTC().String()\n\n\treturn prodToUpdate\n}", "func (d *DB) UpdateProduct(p Product) bool {\n\tfor i, op := range d.Products {\n\t\tif op.ID == p.ID {\n\t\t\td.Products[i] = p\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s *APIProductStore) Update(p *types.APIProduct) types.Error {\n\n\tquery := \"INSERT INTO api_products (\" + apiProductsColumns + \") VALUES(?,?,?,?,?,?,?,?,?,?,?)\"\n\tif err := s.db.CassandraSession.Query(query,\n\t\tp.Name,\n\t\tp.DisplayName,\n\t\tp.Description,\n\t\tp.Attributes.Marshal(),\n\t\tp.RouteGroup,\n\t\tp.Paths.Marshal(),\n\t\tp.Policies,\n\t\tp.CreatedAt,\n\t\tp.CreatedBy,\n\t\tp.LastmodifiedAt,\n\t\tp.LastmodifiedBy).Exec(); err != nil {\n\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn types.NewDatabaseError(\n\t\t\tfmt.Errorf(\"Cannot update apiproduct '%s'\", p.Name))\n\t}\n\treturn nil\n}", "func UpdateWithID(c *server.Context) error {\n\tvar (\n\t\terr error\n\t\tw *ware.Ware\n\t\treq struct {\n\t\t\tID uint32 `json:\"id\" validate:\"required\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tDesc string `json:\"desc\" validate:\"max=50\"`\n\t\t\tParentCategoryID uint32 `json:\"parent_category_id\"`\n\t\t\tCategoryID uint32 `json:\"category_id\"`\n\t\t\tTotalSale uint32 `json:\"total_sale\"`\n\t\t\tAvatar string `json:\"avatar\"`\n\t\t\tImage string `json:\"image\"`\n\t\t\tDetailPic string `json:\"detail_pic\"`\n\t\t\tInventory uint32 `json:\"inventory\"`\n\t\t}\n\t)\n\n\tisAdmin := c.Request().Context().Value(\"user\").(jwtgo.MapClaims)[util.IsAdmin].(bool)\n\tif !isAdmin {\n\t\tlogger.Error(\"You don't have access\")\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrToken, nil)\n\t}\n\n\terr = c.JSONBody(&req)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInvalidParam, nil)\n\t}\n\n\terr = c.Validate(req)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInvalidParam, nil)\n\t}\n\n\tconn, err := mysql.Pool.Get()\n\tdefer mysql.Pool.Release(conn)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\tw, err = ware.Service.GetByID(conn, req.ID)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\tif len(req.Avatar) > 0 {\n\t\terr = util.UpdatePic(req.Avatar, w.Avatar)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\tif len(req.Image) > 0 {\n\t\terr = util.UpdatePic(req.Image, w.Image)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\tif len(req.DetailPic) > 0 {\n\t\terr = util.UpdatePic(req.DetailPic, w.DetailPic)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrInternalServerError, nil)\n\t\t}\n\t}\n\n\tw.Name = req.Name\n\tw.CategoryID = req.CategoryID\n\tw.Desc = req.Desc\n\tw.ParentCategoryID = req.ParentCategoryID\n\tw.TotalSale = req.TotalSale\n\tw.Inventory = req.Inventory\n\n\terr = ware.Service.UpdateWare(conn, w)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn core.WriteStatusAndDataJSON(c, constants.ErrMysql, nil)\n\t}\n\n\treturn core.WriteStatusAndDataJSON(c, constants.ErrSucceed, nil)\n}", "func (mysql *MySqlDB) UpdateProduct(p *models.Product) (int64, error) {\n\n\tif !p.ValidateUpdate() {\n\t\treturn 0, models.NewError(\"Invalid product data\", INVALID_DATA)\n\t}\n\n\tquery, err := mysql.DB.Exec(\"UPDATE products set product_name =?, image =?, rate =? where product_id = ?\", p.ProductName, p.Image, p.Rate, p.ProductId)\n\tif err != nil {\n\t\treturn 0, models.NewError(\"Internal server error\", ERR_INTERNAL)\n\t}\n\trow, _ := query.RowsAffected()\n\treturn row, nil\n}", "func (m *MockIDb) UpdateProductById(id int64, params map[string]interface{}) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateProductById\", id, params)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r Repository) UpdateProduct(product Product) bool {\n\tdb, err := sql.Open(DRIVER, SERVER)\n\n\tif err != nil {\n\t\tfmt.Println(\"Failed to establish connection to MySQL server:\", err)\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Query(\"update `products` set \"+\n\t\t\"title = ?, image = ?, description = ?, price = ?, rating = ?, category = ? where id = ?\",\n\t\tproduct.Title, product.Image, product.Description, product.Price, product.Rating, product.Category, product.ID)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (pr *Product) Update() *ProductUpdateOne {\n\treturn (&ProductClient{config: pr.config}).UpdateOne(pr)\n}", "func (c *Client) ProductUpdate(productID ID, product *NewProduct) error {\n\tresponse, err := c.R().\n\t\tSetHeader(\"Content-Type\", \"application/json\").\n\t\tSetBody(product).\n\t\tPut(fmt.Sprintf(\"/products/%d\", productID))\n\n\treturn responseUpdate(response, err)\n}", "func (e Endpoints) UpdateProduct(ctx context.Context, upadteReq models.Product) (updateResp *models.Product, err error) {\n\trequest := UpdateProductRequest{UpadteReq: upadteReq}\n\tresponse, err := e.UpdateProductEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(UpdateProductResponse).UpdateResp, response.(UpdateProductResponse).Err\n}", "func UpdateProduct(request ProductsRequest) (products.Return, error) {\n\n\t// Hash the password\n\thash := fmt.Sprintf(\"%x\", md5.Sum([]byte(request.AccountPass)))\n\n\t// Define body data\n\tbody := products.Api{\n\t\t\"public\",\n\t\t\"2.0\",\n\t\trequest.AccountName,\n\t\thash,\n\t\t\"itemUpdate\",\n\t\trequest.AccountName,\n\t\thash,\n\t\trequest.Items,\n\t}\n\n\t// Convert body\n\tconvert, err := xml.Marshal(body)\n\tif err != nil {\n\t\treturn products.Return{}, err\n\t}\n\n\t// Config new request\n\tc := Config{convert}\n\n\t// Send new request\n\tresponse, err := c.Send()\n\tif err != nil {\n\t\treturn products.Return{}, err\n\t}\n\n\t// Close request body\n\tdefer response.Body.Close()\n\n\t// Decode data\n\tvar decode products.Return\n\n\terr = xml.NewDecoder(response.Body).Decode(&decode)\n\tif err != nil {\n\t\treturn products.Return{}, err\n\t}\n\n\t// Return data\n\treturn decode, nil\n\n}", "func (s *ProductFieldsService) Update(ctx context.Context, id int, opt *ProductFieldUpdateOptions) (*ProductFieldResponse, *Response, error) {\n\turi := fmt.Sprintf(\"/productFields/%v\", id)\n\treq, err := s.client.NewRequest(http.MethodPut, uri, nil, opt)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar record *ProductFieldResponse\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 (u *Update) Do() {\n\tif err := u.AccessValidate(); err != nil {\n\t\tu.Err = err\n\t\treturn\n\t}\n\n\tif err := u.Validate(); err != nil {\n\t\tu.Err = err\n\t\treturn\n\t}\n\n\tdbProd := &db.Product{Session: u.Session}\n\n\tdtProd, err := dbProd.Get(bson.ObjectIdHex(u.ReqPayload.ID.ID))\n\tif err != nil {\n\t\tu.Err = apperr.Database{\n\t\t\tWhere: \"Product\",\n\t\t\tAction: \"Update\",\n\t\t\tBase: err,\n\t\t}\n\t\treturn\n\t}\n\n\tu.ResPayload.loadToData(dtProd)\n\tif err := dtProd.Validate(); err != nil {\n\t\tu.Err = err\n\t\treturn\n\t}\n\n\tdtProd.ModifiedBy = u.Who.ID\n\tdtProd.ModifiedAt = time.Now()\n\n\tif err := dbProd.Put(dtProd); err != nil {\n\t\tu.Err = apperr.Database{\n\t\t\tBase: err,\n\t\t\tWhere: \"Product\",\n\t\t\tAction: \"Update\",\n\t\t}\n\t\treturn\n\t}\n\n\tu.ResPayload = ID{ID: string(dtProd.ID)}\n}", "func withProductID(id int) productOption {\n\treturn func(m *ProductMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Product\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Product, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Product.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func withProductID(id int) productOption {\n\treturn func(m *ProductMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Product\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Product, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Product.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func withProductID(id int) productOption {\n\treturn func(m *ProductMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Product\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Product, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Product.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func UpdateProductPath() string {\n\treturn \"/api/product/update\"\n}", "func (res ItemsResource) Update(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Todo item update by id\"))\n}", "func (pu *ProductUpdate) Save(ctx context.Context) (int, error) {\n\tif v, ok := pu.mutation.Productname(); ok {\n\t\tif err := product.ProductnameValidator(v); err != nil {\n\t\t\treturn 0, &ValidationError{Name: \"Productname\", err: fmt.Errorf(\"ent: validator failed for field \\\"Productname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := pu.mutation.Amountofproduct(); ok {\n\t\tif err := product.AmountofproductValidator(v); err != nil {\n\t\t\treturn 0, &ValidationError{Name: \"Amountofproduct\", err: fmt.Errorf(\"ent: validator failed for field \\\"Amountofproduct\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := pu.mutation.Price(); ok {\n\t\tif err := product.PriceValidator(v); err != nil {\n\t\t\treturn 0, &ValidationError{Name: \"Price\", err: fmt.Errorf(\"ent: validator failed for field \\\"Price\\\": %w\", err)}\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(pu.hooks) == 0 {\n\t\taffected, err = pu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ProductMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpu.mutation = mutation\n\t\t\taffected, err = pu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(pu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = pu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, pu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func JSONUpdateTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\tparamID := c.Param(\"id\")\n\n\tdata, e := ioutil.ReadAll(c.Request.Body)\n\tif e != nil {\n\t\tc.JSON(http.StatusBadRequest, e.Error())\n\t}\n\n\tvar tabelproduct entities.TabelProduct\n\terr2 := json.Unmarshal(data, &tabelproduct)\n\tif err2 != nil {\n\t \tfmt.Println(err2)\n\t}\n\t\n\timagepath := tabelproduct.ImagePath\n\ttitle := tabelproduct.Title\n\tdescription := tabelproduct.Description\n\tprice := strconv.Itoa(tabelproduct.Price)\n\tmQuery := `UPDATE tabelproduct SET imagepath ='` + imagepath + `', title='` + title + `', description='` + description + `',\n\t\t\t\t\t price='` + price + `' WHERE id ='`+paramID+`';`\t\t\t\t\t\t\t \n\tupdDB, err := Db.Query(mQuery)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer updDB.Close()\n\tDb.Close()\n\tc.JSON(http.StatusOK, \"Update record successfully\")\n}", "func (p *ProductDlv) UpdateProduct(c context.Context, req entity.Product) error {\n\treturn nil\n}", "func (s *permisoService) Update(id string, p *model.Permiso) error {\n\n\t// p.UpdatedAt = time.Now()\n\n\t// return s.service.Update(id, p)\n\n\treturn nil\n}", "func TestProductUC_UpdateProduct(t *testing.T) {\n\n\ttype args struct {\n\t\tc context.Context\n\t\treq entity.Product\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\n\t\twantErr bool\n\t}{\n\t\t//TODO: Add test cases\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\texecutor := &ProductUC{}\n\t\t\terr := executor.UpdateProduct(tt.args.c, tt.args.req)\n\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (puo *ProductUpdateOne) Save(ctx context.Context) (*Product, error) {\n\tif v, ok := puo.mutation.Productname(); ok {\n\t\tif err := product.ProductnameValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"Productname\", err: fmt.Errorf(\"ent: validator failed for field \\\"Productname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := puo.mutation.Amountofproduct(); ok {\n\t\tif err := product.AmountofproductValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"Amountofproduct\", err: fmt.Errorf(\"ent: validator failed for field \\\"Amountofproduct\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := puo.mutation.Price(); ok {\n\t\tif err := product.PriceValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"Price\", err: fmt.Errorf(\"ent: validator failed for field \\\"Price\\\": %w\", err)}\n\t\t}\n\t}\n\n\tvar (\n\t\terr error\n\t\tnode *Product\n\t)\n\tif len(puo.hooks) == 0 {\n\t\tnode, err = puo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ProductMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpuo.mutation = mutation\n\t\t\tnode, err = puo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(puo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = puo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, puo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (p *ProductsDB) UpdateProduct(pr Product) error {\n\ti := findIndexByProductID(pr.ID)\n\tif i == -1 {\n\t\treturn ErrProductNotFound\n\t}\n\n\t// update the product in the DB\n\tproductList[i] = &pr\n\n\treturn nil\n}", "func (s *DealFieldsService) Update(ctx context.Context, id int, opt *DealFieldUpdateOptions) (*ProductFieldResponse, *Response, error) {\n\turi := fmt.Sprintf(\"/dealFields/%v\", id)\n\treq, err := s.client.NewRequest(http.MethodPut, uri, nil, opt)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar record *ProductFieldResponse\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 (t *Typeproduct) Update() *TypeproductUpdateOne {\n\treturn (&TypeproductClient{config: t.config}).UpdateOne(t)\n}", "func (c *Easee) ProductUpdate(i json.RawMessage) {\n\tvar (\n\t\tonce sync.Once\n\t\tres easee.Observation\n\t)\n\n\tif err := json.Unmarshal(i, &res); err != nil {\n\t\tc.log.ERROR.Printf(\"invalid message: %s %v\", i, err)\n\t\treturn\n\t}\n\n\tvalue, err := res.TypedValue()\n\tif err != nil {\n\t\tc.log.ERROR.Println(err)\n\t\treturn\n\t}\n\n\t// https://github.com/evcc-io/evcc/issues/8009\n\t// logging might be slow or block, execute outside lock\n\tc.log.TRACE.Printf(\"ProductUpdate %s: (%v) %s %v\", res.Mid, res.Timestamp, res.ID, value)\n\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\n\tif c.updated.IsZero() {\n\t\tdefer once.Do(func() {\n\t\t\tclose(c.done)\n\t\t})\n\t}\n\tc.updated = time.Now()\n\n\tif prevTime, ok := c.obsTime[res.ID]; ok && prevTime.After(res.Timestamp) {\n\t\t// received observation is outdated, ignoring\n\t\treturn\n\t}\n\tc.obsTime[res.ID] = res.Timestamp\n\n\tswitch res.ID {\n\tcase easee.USER_IDTOKEN:\n\t\tc.rfid = res.Value\n\tcase easee.IS_ENABLED:\n\t\tc.chargerEnabled = value.(bool)\n\tcase easee.SMART_CHARGING:\n\t\tc.smartCharging = value.(bool)\n\tcase easee.TOTAL_POWER:\n\t\tc.currentPower = 1e3 * value.(float64)\n\tcase easee.SESSION_ENERGY:\n\t\tc.sessionEnergy = value.(float64)\n\tcase easee.LIFETIME_ENERGY:\n\t\tc.totalEnergy = value.(float64)\n\tcase easee.IN_CURRENT_T3:\n\t\tc.currentL1 = value.(float64)\n\tcase easee.IN_CURRENT_T4:\n\t\tc.currentL2 = value.(float64)\n\tcase easee.IN_CURRENT_T5:\n\t\tc.currentL3 = value.(float64)\n\tcase easee.PHASE_MODE:\n\t\tc.phaseMode = value.(int)\n\tcase easee.DYNAMIC_CHARGER_CURRENT:\n\t\tc.dynamicChargerCurrent = value.(float64)\n\tcase easee.CHARGER_OP_MODE:\n\t\tc.opMode = value.(int)\n\tcase easee.REASON_FOR_NO_CURRENT:\n\t\tc.reasonForNoCurrent = value.(int)\n\t}\n\n\tselect {\n\tcase c.obsC <- res:\n\tdefault:\n\t}\n}", "func (a *App) PatchProduct(pid int64, patch *model.ProductPatch) (*model.Product, *model.AppErr) {\n\told, err := a.Srv().Store.Product().Get(pid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\told.Patch(patch)\n\told.PreUpdate()\n\tuprod, err := a.Srv().Store.Product().Update(pid, old)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn uprod, nil\n}", "func ModifyProduct(c *fiber.Ctx) error {\n\tdb := database.Connection()\n\treturn models.ModifyProduct(db, c)\n}", "func UpdateProductEndPoint(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"not implemented yet !\")\n}", "func (s *Service) ChangeProduct(ctx context.Context, product *types.Products) (*types.Products, error) {\n\n\tvar err error\n\n\tif product.ID == 0 {\n\t\tsql1 := `INSERT INTO products (name, qty, price) VALUES ($1, $2, $3)\n\t\t\t\t RETURNING id, name, qty, price, active, created;`\n\t\terr = s.pool.QueryRow(ctx, sql1, product.Name, product.Qty, product.Price).Scan(\n\t\t\t&product.ID,\n\t\t\t&product.Name,\n\t\t\t&product.Qty,\n\t\t\t&product.Price,\n\t\t\t&product.Active,\n\t\t\t&product.Created)\n\n\t} else {\n\t\tsql2 := `UPDATE products SET name = $1, qty = $2, price = $3 WHERE id = $4 \n\t\t\t\t RETURNING id, name, qty, price, active, created;`\n\t\terr = s.pool.QueryRow(ctx, sql2, product.Name, product.Qty, product.Price, product.ID).Scan(\n\t\t\t&product.ID,\n\t\t\t&product.Name,\n\t\t\t&product.Qty,\n\t\t\t&product.Price,\n\t\t\t&product.Active,\n\t\t\t&product.Created)\n\t}\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, ErrInternal\n\t}\n\treturn product, nil\n\n}", "func (c *Client) UpdateProduct(product *Product) (p *Product, err error) {\n\terr = c.patch(nil, \"products/\"+product.ID, &product, &p)\n\treturn\n}", "func (o *Stock) SetProduct(exec boil.Executor, insert bool, related *Product) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(exec); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE `stock` SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, []string{\"product_id\"}),\n\t\tstrmangle.WhereClause(\"`\", \"`\", 0, stockPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ProductID, o.StockID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\to.ProductID = related.ProductID\n\n\tif o.R == nil {\n\t\to.R = &stockR{\n\t\t\tProduct: related,\n\t\t}\n\t} else {\n\t\to.R.Product = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &productR{\n\t\t\tStocks: StockSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.Stocks = append(related.R.Stocks, o)\n\t}\n\n\treturn nil\n}", "func (pu *ProductUpdate) Save(ctx context.Context) (int, error) {\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(pu.hooks) == 0 {\n\t\taffected, err = pu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ProductMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpu.mutation = mutation\n\t\t\taffected, err = pu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(pu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = pu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, pu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (tx *Tx) UpsertProduct(product *AWSProductInfo) error {\n\t_, err := tx.NamedExec(\"INSERT INTO aws_product (product_code, name, description) VALUES (:product_code, :name, :description) ON CONFLICT (product_code) DO UPDATE SET name = :name, description = :description;\", product)\n\tif err != nil {\n\t\treturn errors.InternalError(err)\n\t}\n\tlog.Printf(\"Upserted product %s\", *product)\n\treturn nil\n}", "func (duo *DealUpdateOne) SetProductId(i int64) *DealUpdateOne {\n\tduo.mutation.ResetProductId()\n\tduo.mutation.SetProductId(i)\n\treturn duo\n}", "func Update (w http.ResponseWriter, r *http.Request){\n\tif r.Method == \"POST\"{ // retorna tudo em string\n\t\tid := r.FormValue(\"id\")\n\t\tnome := r.FormValue(\"nome\")\n\t\tdescricao := r.FormValue(\"descricao\")\n\t\tpreco := r.FormValue(\"preco\")\n\t\tquantidade := r.FormValue(\"quantidade\")\n\n\t\t//convertendo os valores\n\n\t\tidConvertidoParaInt, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tlog.Println(\"erro na conversão do ID para int:\", err)\n\t\t}\n\n\t\tprecoConvertidoParaFloat , err := strconv.ParseFloat(preco,64)\n\t\tif err != nil {\n\t\t\tlog.Println(\"erro na conversão do preço para float64:\", err)\n\t\t}\n\n\t\tquantidadeConvertidaParaInt, err := strconv.Atoi(quantidade)\n\t\tif err != nil {\n\t\t\tlog.Println(\"erro na conversão da quantidade para int:\", err)\n\t\t}\n\n\t\t//Mostrando quais os valores pra atualizar\n\t\tmodels.AtualizaProduto(idConvertidoParaInt, nome, descricao, precoConvertidoParaFloat, quantidadeConvertidaParaInt)\n\t}\n\thttp.Redirect(w, r, \"/\", 301)\n\n}", "func (o *Transaction) SetProduct(exec boil.Executor, insert bool, related *Product) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(exec); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE `transactions` SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, []string{\"product_id\"}),\n\t\tstrmangle.WhereClause(\"`\", \"`\", 0, transactionPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ProductID, o.TransactionID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\to.ProductID.Int = related.ProductID\n\to.ProductID.Valid = true\n\n\tif o.R == nil {\n\t\to.R = &transactionR{\n\t\t\tProduct: related,\n\t\t}\n\t} else {\n\t\to.R.Product = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &productR{\n\t\t\tTransactions: TransactionSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.Transactions = append(related.R.Transactions, o)\n\t}\n\n\treturn nil\n}", "func (sc StoreController) Update(c *gin.Context) {\n\tlog.Debug().Caller().Msg(\"stores update\")\n\tid := c.Params.ByName(\"id\")\n\tp, err := sc.Storeservice.Update(id, c)\n\n\tif err != nil {\n\t\tif gorm.IsRecordNotFoundError(err) {\n\t\t\tc.AbortWithStatus(http.StatusNotFound)\n\t\t\tlog.Error().Caller().Err(err).Send()\n\t\t} else {\n\t\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\t\tlog.Error().Caller().Err(err).Send()\n\t\t}\n\t} else {\n\t\tc.JSON(http.StatusOK, p)\n\t}\n}", "func createOrUpdateProduct(p Product) (Product, error) {\n\tif p.ID == \"\" {\n\t\tp.ID = strconv.Itoa(len(data) + 1)\n\t\tp.CreatedAt = time.Now()\n\t\tdata = append(data, p)\n\t\treturn p, nil\n\t}\n\tstored, _, err := findProduct(p.ID)\n\tif err != nil {\n\t\tvar empty Product\n\t\treturn empty, err\n\t}\n\n\t//C hange found product\n\tstored.ID = p.ID\n\tstored.Name = p.Name\n\tstored.Price = p.Price\n\treturn *stored, nil\n}", "func (puo *ProductUpdateOne) Save(ctx context.Context) (*Product, error) {\n\tvar (\n\t\terr error\n\t\tnode *Product\n\t)\n\tif len(puo.hooks) == 0 {\n\t\tnode, err = puo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*ProductMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tpuo.mutation = mutation\n\t\t\tnode, err = puo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(puo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = puo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, puo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (pu *ProductUpdate) Exec(ctx context.Context) error {\n\t_, err := pu.Save(ctx)\n\treturn err\n}", "func (pu *ProductUpdate) Exec(ctx context.Context) error {\n\t_, err := pu.Save(ctx)\n\treturn err\n}", "func UpdateProductRowsByID(ctx context.Context, db SQLHandle, changeset ProductValues, keys ...interface{}) (numRows int64, err error) {\n\tnumRows, err = execWithJSONArgs(ctx, db, SQLUpdateProductRowsByID, changeset, keys)\n\tif err != nil {\n\t\treturn numRows, formatError(\"UpdateProductRowsByID\", err)\n\t}\n\treturn numRows, nil\n}", "func PutProduct(newData Product) Product {\n\toldData := Product{Id: newData.Id}\n\tdatabase.SQL.Model(&oldData).Updates(newData)\n\treturn GetProduct(newData.Id)\n}", "func withOrderproductID(id int) orderproductOption {\n\treturn func(m *OrderproductMutation) {\n\t\tvar (\n\t\t\terr error\n\t\t\tonce sync.Once\n\t\t\tvalue *Orderproduct\n\t\t)\n\t\tm.oldValue = func(ctx context.Context) (*Orderproduct, error) {\n\t\t\tonce.Do(func() {\n\t\t\t\tif m.done {\n\t\t\t\t\terr = fmt.Errorf(\"querying old values post mutation is not allowed\")\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = m.Client().Orderproduct.Get(ctx, id)\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn value, err\n\t\t}\n\t\tm.id = &id\n\t}\n}", "func (r ApiOrdersUpdateProductRequest) UpdateProduct(updateProduct UpdateProduct) ApiOrdersUpdateProductRequest {\n\tr.updateProduct = &updateProduct\n\treturn r\n}", "func (c *MySQLClient) Update(p *purchase.Purchase) error {\n\tif p.ID == 0 {\n\t\treturn fmt.Errorf(\"purchase must have a preexisting ID\")\n\t}\n\n\tbuyBytes, err := json.Marshal(p.BuyOrder)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshal buy order: %v\", err)\n\t}\n\n\tsellBytes, err := json.Marshal(p.SellOrder)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshal sell order: %v\", err)\n\t}\n\n\tquery := `UPDATE trader_one\n SET\n buy_order = ?,\n sell_order = ?,\n updated_at = NOW()\n WHERE\n id = ?`\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFunc()\n\tstmt, err := c.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to prepare SQL statement: %v\", err)\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.ExecContext(ctx, jsonString(buyBytes), jsonString(sellBytes), p.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to update row: %v\", err)\n\t}\n\treturn nil\n}", "func (s *service) Update(ID string, p *Payment) error {\n\tp.ID = ID\n\t_, err := s.Get(p.ID)\n\tif err != nil {\n\t\tif err != ErrPaymentNotFound {\n\t\t\treturn err\n\t\t}\n\n\t\treturn s.persist(p)\n\t}\n\n\treturn s.update(p)\n}", "func (pr postRepository) Update(id string, p Post) error {\n\treturn pr.getCollection().Update(bson.M{\"_id\": bson.ObjectIdHex(id)}, p)\n}", "func (gi *Sensor) Update(db *pg.DB) error {\r\n\tlog.Printf(\"===>sensorItem.Update()\")\r\n\r\n\t_, updateErr := db.Model(gi).\r\n\t\tWhere(\"id = ?0\", gi.ID).Update()\r\n\tif updateErr != nil {\r\n\t\tlog.Printf(\"Error while updating item in sensorItem.Update()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", updateErr)\r\n\t\treturn updateErr\r\n\t}\r\n\tlog.Printf(\"Product %s updated successfully in table\", gi.Sensorname)\r\n\treturn nil\r\n}", "func (*Products) Delete(id int64) error {\n\n\t_, err := model.Get(id)\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Get)\", \"Product doesn't exist\")\n\t\treturn err\n\t}\n\n\tstmt, err := db.Prepare(\n\t\t\"delete from products where id = $1\")\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Prepare)\", err)\n\t\treturn err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(id)\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Physical:Exec)\", err)\n\n\t\tstmt, err = db.Prepare(\n\t\t\t\"update products \" +\n\t\t\t\t\"set deleted = true, \" +\n\t\t\t\t\"date_updated = now() \" +\n\t\t\t\t\"where id = $1\")\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeteleProduct:Logic:Prepare)\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = stmt.Exec(id)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeleteProduct:Logic:Exec)\", err)\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (r repository) Product(productId string) (*model.Product, error) {\n\tfilter := bson.M{\n\t\t\"product_id\": productId,\n\t\t\"price\": bson.M{\n\t\t\t\"$exists\": true,\n\t\t},\n\t}\n\n\tctx, _ := context.WithTimeout(context.Background(), 1*time.Second)\n\n\tresult := r.collection.FindOne(ctx, filter)\n\tif result.Err() != nil {\n\n\t\tif result.Err() == mongo.ErrNoDocuments {\n\t\t\tlogrus.Infof(\"No document for product %s\", productId)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tlogrus.Errorf(\"FindOne failed for product %s Error: %s\", productId, result.Err())\n\t\treturn nil, result.Err()\n\t}\n\n\tvar product *model.Product\n\terr := result.Decode(&product)\n\tif err != nil {\n\t\tlogrus.Errorf(\"FindOne failed for product %s. Error: %s\", productId, err)\n\t\treturn nil, err\n\t}\n\n\t// ToDo - check why productId was not set\n\tproduct.ProductId = productId\n\n\treturn product, nil\n}", "func Update(writer http.ResponseWriter, request *http.Request) {\n\tsp := getByID(request.FormValue(\"id\"))\n\tfmt.Println(sp)\n\ttemplate_html.ExecuteTemplate(writer, \"Update\", sp)\n}", "func (dao *OrderDao) Update(order Order, id string) (*Order, error) {\n\tquery := `\n\t\tUPDATE orders SET status=$2, customerid=$3, productid=$4\n\t\tWHERE id=$1 \n\t`\n\tstmt, err := dao.DB.Prepare(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = stmt.Exec(order.ID, order.Status, order.CustomerID, order.ProductID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n}", "func (mr *MockIDbMockRecorder) UpdateProductById(id, params interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateProductById\", reflect.TypeOf((*MockIDb)(nil).UpdateProductById), id, params)\n}", "func (du *DealUpdate) SetProductId(i int64) *DealUpdate {\n\tdu.mutation.ResetProductId()\n\tdu.mutation.SetProductId(i)\n\treturn du\n}", "func (gi *Sensor) UpdatePid(db *pg.DB, pid int, state int) error {\r\n\t// log.Printf(\">===>sensorItem.Update()\")\r\n\r\n\t_, updateErr := db.Model(gi).\r\n\t\tSet(\"sensorpid=?0,sensorstate=?1\", pid, state).\r\n\t\tWhere(\"id = ?0\", gi.ID).Update()\r\n\tif updateErr != nil {\r\n\t\tlog.Printf(\"Error while updating item in sensorModel.Update()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", updateErr)\r\n\t\treturn updateErr\r\n\t}\r\n\t// log.Printf(\"Product %s updated successfully in table\", gi.Sensorname)\r\n\treturn nil\r\n}", "func (od *OrderDetail) Update(ctx context.Context, db DB) error {\n\tswitch {\n\tcase !od._exists: // doesn't exist\n\t\treturn logerror(&ErrUpdateFailed{ErrDoesNotExist})\n\tcase od._deleted: // deleted\n\t\treturn logerror(&ErrUpdateFailed{ErrMarkedForDeletion})\n\t}\n\t// update with primary key\n\tconst sqlstr = `UPDATE northwind.order_details SET ` +\n\t\t`unit_price = ?, quantity = ?, discount = ? ` +\n\t\t`WHERE order_id = ? AND product_id = ?`\n\t// run\n\tlogf(sqlstr, od.UnitPrice, od.Quantity, od.Discount, od.OrderID, od.ProductID)\n\tif _, err := db.ExecContext(ctx, sqlstr, od.UnitPrice, od.Quantity, od.Discount, od.OrderID, od.ProductID); err != nil {\n\t\treturn logerror(err)\n\t}\n\treturn nil\n}", "func (dao ArtistDAO) Update(id string, a Artist) error {\n\treturn dao.getCollection().Update(bson.M{\"_id\": bson.ObjectIdHex(id)}, a)\n}", "func (d *Dao) Product(c context.Context, id int64) (res *model.Product, err error) {\n\tres = &model.Product{}\n\tif err = d.db.QueryRow(c, _productSQL, id).Scan(&res.ID, &res.Name, &res.GroupIDs, &res.Ctime, &res.Mtime); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Product.Scan error(%+v), id(%d)\", err, id)\n\t}\n\tif res.GroupIDs != \"\" {\n\t\tvar gids []int64\n\t\tif gids, err = xstr.SplitInts(res.GroupIDs); err != nil {\n\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, res.GroupIDs)\n\t\t\treturn\n\t\t}\n\t\tif res.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func updatePaymentByID(c *gin.Context) {\n\n\tpaymentsDB, err := setup(paymentsStorage)\n\n\t//connect to db\n\tif err != nil {\n\t\tlogHandler.Error(\"problem connecting to database\", log.Fields{\"dbname\": paymentsStorage.Cfg.Db, \"func\": \"updatePaymentByID\"})\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"error\", \"message\": \"Problem connecting to db\"})\n\t\treturn\n\t}\n\tdefer paymentsDB.Close()\n\n\tvar p storage.Payments\n\terr = c.BindJSON(&p)\n\n\terr = paymentsDB.UpdatePayment(c.Param(\"id\"), &p)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": \"error\", \"message\": \"Could not update the payment\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"status\": \"success\", \"message\": \"Payment updated\"})\n\n}", "func (o *Description) SetProduct(ctx context.Context, exec boil.ContextExecutor, insert bool, related *Product) error {\n\tvar err error\n\tif insert {\n\t\tif err = related.Insert(ctx, exec, boil.Infer()); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t}\n\t}\n\n\tupdateQuery := fmt.Sprintf(\n\t\t\"UPDATE `descriptions` SET %s WHERE %s\",\n\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, []string{\"product_id\"}),\n\t\tstrmangle.WhereClause(\"`\", \"`\", 0, descriptionPrimaryKeyColumns),\n\t)\n\tvalues := []interface{}{related.ID, o.ID}\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tif _, err = exec.ExecContext(ctx, updateQuery, values...); err != nil {\n\t\treturn errors.Wrap(err, \"failed to update local table\")\n\t}\n\n\to.ProductID = related.ID\n\tif o.R == nil {\n\t\to.R = &descriptionR{\n\t\t\tProduct: related,\n\t\t}\n\t} else {\n\t\to.R.Product = related\n\t}\n\n\tif related.R == nil {\n\t\trelated.R = &productR{\n\t\t\tDescriptions: DescriptionSlice{o},\n\t\t}\n\t} else {\n\t\trelated.R.Descriptions = append(related.R.Descriptions, o)\n\t}\n\n\treturn nil\n}", "func (ctl *SaleCounterProductController) Edit() {\n\tid := ctl.Ctx.Input.Param(\":id\")\n\tif id != \"\" {\n\t\tif idInt64, e := strconv.ParseInt(id, 10, 64); e == nil {\n\t\t\tif counterProduct, err := md.GetSaleCounterProductByID(idInt64); err == nil {\n\t\t\t\tctl.Data[\"SaleCounterProduct\"] = counterProduct\n\t\t\t\tctl.PageAction = counterProduct.SaleCounter.Name\n\t\t\t}\n\t\t}\n\t}\n\tctl.Data[\"FormField\"] = \"form-edit\"\n\tctl.Data[\"RecordID\"] = id\n\tctl.Data[\"Action\"] = \"edit\"\n\tctl.Layout = \"base/base.html\"\n\tctl.TplName = \"sale/sale_counter_product_form.html\"\n}", "func (s *MongoStore) UpdateEntity(name string, id string, data interface{}, result interface{}) error {\n\tentityId := bson.ObjectIdHex(id)\n\terr := s.db.C(name).UpdateId(entityId, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = s.db.C(name).FindId(entityId).One(result); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (api *MysqlAPI) Update(table string, id interface{}, obj map[string]interface{}) (rs sql.Result, err error) {\n\tif id != nil {\n\t\tsql, err := api.sql.UpdateByTableAndId(table, id, obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn api.exec(sql)\n\t} else {\n\t\terr = fmt.Errorf(\"please give inot support update by where\")\n\t\treturn\n\t}\n}", "func (intr Internal) StoreProduct(ctx context.Context, tx *sql.Tx, product Product) (ID int64, err error) {\n\tvar args []interface{}\n\tquery := `INSERT INTO product \n\t\t\t\t\t(\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tsku,\n\t\t\t\t\t\tstock \n\t\t\t\t\t)\n\t\t\tVALUES (\n\t\t\t\t\t\t?, \n\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)\n\t\t\t`\n\targs = append(args, product.Name, product.Sku, product.Stock)\n\tif product.ProductID != 0 {\n\t\tquery = `UPDATE product \n\t\t\t\t SET \n\t\t\t\t\t\tname = ?,\n\t\t\t\t\t\tsku = ?,\n\t\t\t\t\t\tstock = ?\n\t\t\t\tWHERE \n\t\t\t\t\t\tproduct_id = ?\n\t\t\t\t\t\t \n\t\t`\n\t\targs = append(args, product.ProductID)\n\t}\n\n\tresult, err := tx.ExecContext(ctx, query, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif product.ProductID == 0 {\n\t\t// no need to check error, since it will be occurred by database incompatibility\n\t\tproduct.ProductID, _ = result.LastInsertId()\n\t}\n\n\treturn product.ProductID, err\n}", "func (puo *ProductUpdateOne) Exec(ctx context.Context) error {\n\t_, err := puo.Save(ctx)\n\treturn err\n}", "func (puo *ProductUpdateOne) Exec(ctx context.Context) error {\n\t_, err := puo.Save(ctx)\n\treturn err\n}", "func (m *OrderonlineMutation) ProductID() (id int, exists bool) {\n\tif m.product != nil {\n\t\treturn *m.product, true\n\t}\n\treturn\n}", "func (s *OrderItemService) Update(ctx context.Context, id string, uoi entity.UpdateOrderItem) error {\n\treturn s.repo.Update(ctx, id, uoi)\n}" ]
[ "0.7564828", "0.7524328", "0.7471212", "0.7395203", "0.73369896", "0.73237836", "0.7239688", "0.7186437", "0.71534777", "0.71368057", "0.7101492", "0.708472", "0.70754033", "0.7064517", "0.70336276", "0.700576", "0.69777745", "0.69599026", "0.6941749", "0.69018483", "0.68307996", "0.67878485", "0.676195", "0.6727618", "0.66951215", "0.6692318", "0.66867936", "0.6655973", "0.66540504", "0.6649137", "0.66317916", "0.661449", "0.653793", "0.6452344", "0.6451841", "0.643462", "0.64257795", "0.64099276", "0.6409746", "0.63682395", "0.6289243", "0.6268326", "0.62682664", "0.62682664", "0.6258063", "0.6199433", "0.61973596", "0.6179616", "0.6170442", "0.6154656", "0.61246866", "0.61203", "0.61117136", "0.6067843", "0.6060239", "0.6057612", "0.59866965", "0.5981965", "0.59319365", "0.59217715", "0.5906166", "0.5905825", "0.58929104", "0.5886487", "0.5879049", "0.5875824", "0.58732", "0.58711034", "0.5868129", "0.5848496", "0.5846838", "0.5846838", "0.58376247", "0.58255345", "0.5804465", "0.57981116", "0.5781749", "0.57603556", "0.5747346", "0.5745707", "0.573637", "0.5728994", "0.5726261", "0.5724586", "0.57227594", "0.5718318", "0.5712137", "0.5705174", "0.5691252", "0.5675203", "0.56742984", "0.5668857", "0.5665171", "0.5649013", "0.5648453", "0.5637397", "0.5634974", "0.5634974", "0.5629305", "0.562101" ]
0.6712571
24
Delete product based on its ID
func (db *ProductRepo) Delete(id int) (message string) { delete := "this is delelte methode" return delete }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DeleteProduct(c *gin.Context) {\n\tID := c.Param(\"id\")\n\n\t//ID := c.Query(\"id\")\n\tfmt.Println(\"id is: \", ID)\n\tlog.Println(\"id: \", ID)\n\tdb := DbConn()\n\tvar prod Products\n\tdbc := db.Where(\"id = ?\", ID).Delete(&prod).Error\n\tif dbc != nil {\n\t\tfmt.Println(\"Error while deleting: \", dbc)\n\t\tc.String(http.StatusBadRequest, \"Error while deleting\")\n\t}\n\tc.String(http.StatusOK, \"Success\")\n}", "func (*Products) Delete(id int64) error {\n\n\t_, err := model.Get(id)\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Get)\", \"Product doesn't exist\")\n\t\treturn err\n\t}\n\n\tstmt, err := db.Prepare(\n\t\t\"delete from products where id = $1\")\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Prepare)\", err)\n\t\treturn err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(id)\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Physical:Exec)\", err)\n\n\t\tstmt, err = db.Prepare(\n\t\t\t\"update products \" +\n\t\t\t\t\"set deleted = true, \" +\n\t\t\t\t\"date_updated = now() \" +\n\t\t\t\t\"where id = $1\")\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeteleProduct:Logic:Prepare)\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = stmt.Exec(id)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeleteProduct:Logic:Exec)\", err)\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func DeleteProductByID(c *gin.Context) {\n\t// Get model if exist\n\tvar product models.Product\n\tif err := database.Connector.Where(\"id = ?\", c.Param(\"id\")).First(&product).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\n\tdatabase.Connector.Delete(&product)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": true})\n}", "func (r Repository) DeleteProduct(id int) string {\n\tdb, err := sql.Open(DRIVER, SERVER)\n\n\tif err != nil {\n\t\tfmt.Println(\"Failed to establish connection to MySQL server:\", err)\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Query(\"delete from `products` where id = ?\", id)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn \"INTERNAL ERR\"\n\t}\n\treturn \"OK\"\n}", "func DeleteProduct(id primitive.ObjectID, db *mongo.Client) (int, error) {\n\t//delete product with id from db\n\tprodCol := db.Database(DBNAME).Collection(COLLNAME)\n\n\tfilter := bson.M{\"_id\": id}\n\tresult, err := prodCol.DeleteOne(context.TODO(), filter)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(result.DeletedCount), nil\n}", "func (pri *ProductRepositoryImpl) DeleteProduct(id int) error {\n\n\t//_, err := pri.conn.Exec(\"DELETE FROM products WHERE id=?\", id)\n\t_, err := pri.conn.Exec(\"DELETE FROM products WHERE id=$1\", id)\n\tif err != nil {\n\t\treturn errors.New(\"Delete has failed\")\n\t}\n\n\treturn nil\n}", "func deleteProduct(dbRef *pg.DB) {\n\tnewPI := &db.ProductItem{\n\t\tName: \"Product 2\",\n\t}\n\tnewPI.Delete(dbRef)\n}", "func DeleteProduct(id string, db *sql.DB) error {\n\t_, err := db.Exec(\"DELETE FROM products WHERE product_id = $1\", id)\n\treturn err\n}", "func (this *ProductController) Del() {\n\tid := this.GetParamAsInt(\"id\")\n\terr := models.DbOb.Exec(fmt.Sprintf(`delete from product where id=%d`, id))\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tthis.ReturnJsonString(0, \"删除失败,请刷新\", \"\")\n\t} else {\n\t\tthis.ReturnJsonString(1, \"删除成功\", \"\")\n\t}\n}", "func (p *Products) Delete(c *gin.Context) {\n\n\t//fetch id from uri\n\tid, err := getProductIDFromParam(c)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"Error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tp.l.Println(\"Deleting Product\", \"id\", id)\n\n\terr = data.DeleteProductByID(id)\n\tif err != nil {\n\t\tp.l.Println(\"[Error] deleting product\", err.Error())\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"Message\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tif err == data.ErrProductNotFound {\n\t\tp.l.Println(\"[Error] deleting product\", err.Error())\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"Message\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tc.Writer.WriteHeader(http.StatusNoContent)\n}", "func DeleteProduct(w http.ResponseWriter, r *http.Request) {\n\tid := httprouter.GetParam(r, \"id\")\n\n\terr := repo.DeleteProduct(r.Context(), id)\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithStatus(w, http.StatusOK)\n}", "func DeleteProduct(id int64) int64 {\n\tdb := CreateConnection()\n\tdefer db.Close()\n\n\tsqlStatement := `delete from products where id=$1`\n\tresponse, err := db.Exec(sqlStatement, id)\n\n\tif err != nil {\n\t\tlog.Print(\"Unable to execute the query. \", err)\n\t}\n\n\trowsAffected, err := response.RowsAffected()\n\tif err != nil {\n\t\tlog.Print(\"Error while checking the affected rows. \", err)\n\t}\n\n\tlog.Print(\"Total rows/record affected \", err)\n\n\treturn rowsAffected\n}", "func DeleteProduct(c *gin.Context) {\n\tvar product Models.Product\n\tid := c.Params.ByName(\"id\")\n\terr := Models.DeleteProduct(&product, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{\"id\" + id: \"is deleted\"})\n\t}\n}", "func (e *engine) DeleteOne(c *httpEngine.ServerContext) {\n\t// check iid exists or not\n\tid, err := c.GetURLParam(\"iid\")\n\tif err != nil {\n\t\tc.ErrorHandler(400, err)\n\t\treturn\n\t}\n\tvar product = &domain.Product{}\n\tproduct.Iid = id\n\terr = e.ProductLogic.DeleteProduct(product)\n\tif err != nil {\n\t\tc.JSON(400,\n\t\t\tmap[string]string{\n\t\t\t\t\"error\": \"can't delete this product(invalid id)\",\n\t\t\t},\n\t\t)\n\t\treturn\n\t}\n\tc.JSON(200,\n\t\tmap[string]string{\n\t\t\t\"message\": \"product deletet successfully\",\n\t\t},\n\t)\n}", "func DeleteProduct(id int) error {\n\t_, pos, err := findProduct(id)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproductList = append(productList[:pos], productList[pos+1:]...)\n\treturn nil\n}", "func (r ProductRepository) Delete(ctx context.Context, id uint) error {\n\tentity, err := r.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.db.DB().Delete(entity).Error\n}", "func Delete(id int) bool{\n\tfound, product := GetProduct(id)\n\n\tif !found {\n\t\treturn false\n\t}\n\tdatabase.DB.Delete(product)\n\treturn true\n}", "func (fapi *FyndiqAPI) DeleteProduct(id int) error {\n\t_, err := httpRequest(\"DELETE\", fapi.productURL(id), nil)\n\treturn err\n}", "func (intr Internal) DeleteProduct(ctx context.Context, ID int64) error {\n\tquery := `DELETE FROM product \n\t\t\t WHERE \n\t\t\t\t product_id = ?\n\t\t\t `\n\tdb := intr.Storage.DB\n\n\t_, err := db.ExecContext(ctx, query, ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}", "func (h *ProductHandler) DeleteProduct(w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tid, err := strconv.ParseInt(params.Get(\"id\"), 0, 64)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\terr = h.ProductUsecase.Delete(ctx, id)\n\n\tif err != nil {\n\t\tutils.Error(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\t// escape error because there is no connection between product and category already\n\t_ = h.ProductCatUsecase.DeleteByProductID(ctx, id)\n\n\tutils.JSON(w, http.StatusOK, \"success\")\n}", "func DeleteProduct(id int) error {\n\ti := findIndexByProductID(id)\n\tif i == -1 {\n\t\treturn ErrProductNotFound\n\t}\n\n\tproductList = append(productList[:i], productList[i+1])\n\n\treturn nil\n}", "func DeleteProduct(id int) error {\n\t_, i, err := FindProduct(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproductsList = removeIndex(productsList, i)\n\treturn nil\n}", "func DeleteProduct(c echo.Context) (err error) {\n\tvar m models.ResponseMessage\n\tvar productID int\n\n\tproductIDParam := c.Param(\"id\")\n\n\tif productID, err = utils.Atoi(productIDParam); err != nil || productID == 0 {\n\t\tm.Error = fmt.Sprintf(\"%v: id\", errs.ErrInvalidParam)\n\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, m)\n\t}\n\n\tdb, err := database.Get()\n\tif err != nil {\n\t\tc.Logger().Error(err)\n\n\t\treturn echo.ErrInternalServerError\n\t}\n\n\terr = dbu.DeleteProduct(\n\t\tdb,\n\t\tdbm.Product{\n\t\t\tID: int64(productID),\n\t\t},\n\t)\n\tif err != nil {\n\t\tif errors.Is(err, errs.ErrNotExistentObject) {\n\t\t\tm.Error = fmt.Sprintf(\"%v: product\", errs.ErrNotExistentObject)\n\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, m)\n\t\t}\n\t\tc.Logger().Error(err)\n\n\t\treturn echo.ErrInternalServerError\n\t}\n\n\tm.Message = \"Deleted.\"\n\treturn c.JSON(http.StatusOK, m)\n}", "func DeleteProduct(c echo.Context) error {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\treturn c.JSON(http.StatusBadRequest, types.ParseStatus(\"REQ_INVALID\", \"ID invalid\"))\n\t}\n\tdata, err := db.DeleteAtProduct(id)\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotAcceptable, types.ParseStatus(\"NOT_ACCEPTED\", err.Error()))\n\t}\n\treturn c.JSON(http.StatusOK, data)\n}", "func (d *Dao) DeleteProduct(c context.Context, id int64) (res int64, err error) {\n\tvar r sql.Result\n\tif r, err = d.db.Exec(c, _deleteProductSQL, id); err != nil {\n\t\tlog.Error(\"d.DeleteProduct.Exec error(%+v), id(%d)\", err, id)\n\t\treturn\n\t}\n\tif res, err = r.RowsAffected(); err != nil {\n\t\tlog.Error(\"d.DeleteProduct.RowsAffected error(%+v), id(%d)\", err, id)\n\t}\n\treturn\n}", "func (s *APIProductStore) Delete(apiProduct string) types.Error {\n\n\tapiproduct, err := s.Get(apiProduct)\n\tif err != nil {\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn err\n\t}\n\n\tquery := \"DELETE FROM api_products WHERE name = ?\"\n\tif err := s.db.CassandraSession.Query(query, apiproduct.Name).Exec(); err != nil {\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn types.NewDatabaseError(err)\n\t}\n\treturn nil\n}", "func removeProduct(writer http.ResponseWriter, request *http.Request) {\n\ttransactionId := request.Header.Get(\"transactionId\")\n\tlog.Printf(\"Removing product for trasnsactionId %s!\", transactionId)\n\tdecoder := json.NewDecoder(request.Body)\n\tremoveProductCommand := command.RemoveProductCommand{}\n\terr := decoder.Decode(&removeProductCommand)\n\tif err != nil {\n\t\twriteErrorResponse(writer, err)\n\t}\n\tproductHandler.RemoveProduct(transactionId, removeProductCommand)\n\trenderResponse(writer, []byte(\"\"))\n}", "func (pm *ProductModel) Delete(product Product) error {\n\tif _, err := pm.DB.Query(DELETE_PRODUCT_STMT, product.ProductName); err != nil {\n\t\tlog.Printf(\"error occurred on deleting a specific product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteProduct(ID uint, parent string) bool {\n\tvar data Product\n\tvar del bool\n\tif parent == \"\" {\n\t\tdatabase.SQL.Where(\"product.id=(?)\", ID).First(&data)\n\t} else {\n\t\tdatabase.SQL.Where(\"product.id=(?)\", ID).Where(\"product.product_type=(?)\", parent).First(&data)\n\t}\n\tif data.Id != 0 {\n\t\tdatabase.SQL.Delete(&data)\n\t\tdel = true\n\t}\n\treturn del\n}", "func (e Endpoints) DeleteProduct(ctx context.Context, id string) (deleteResp *models.DeleteProductResp, err error) {\n\trequest := DeleteProductRequest{Id: id}\n\tresponse, err := e.DeleteProductEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(DeleteProductResponse).DeleteResp, response.(DeleteProductResponse).Err\n}", "func (ph *Handler) RemoveProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : Delete /app/product/{id_product} API hit!\")\n\tproductID, err := strconv.Atoi(chi.URLParam(r, \"id_product\"))\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.DecodeErrorCode, errors.New(\"invalid id_product\").Error())\n\t\treturn\n\t}\n\trequest := RemoveProductRequest{\n\t\tProductID: productID,\n\t}\n\terr = ph.ps.RemoveProduct(r.Context(), &request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tif err.Error() == utils.InvalidProductIDError {\n\t\t\tutils.Fail(w, 500, utils.InvalidProductIDErrorCode, err.Error())\n\t\t\treturn\n\t\t}\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : product removed! id_product : \", productID)\n\tutils.Send(w, 200, nil)\n}", "func (ch *CartHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\terr := ch.Cart.Delete(id)\n\tif err != nil {\n\t\tswitch err {\n\t\tcase ErrorCorruptDb:\n\t\t\tRespondWithError(w, http.StatusInternalServerError, err)\n\t\tdefault:\n\t\t\tRespondWithError(w, http.StatusNotFound, err)\n\t\t}\n\t}\n\n\tRespond(w, http.StatusNoContent, nil)\n}", "func (mysql *MySqlDB) DeleteProduct(productId int64) (int64, error) {\n\tres, err := mysql.DB.Exec(\"DELETE FROM products where product_id = ?\", productId)\n\tif err != nil {\n\t\treturn int64(0), models.NewError(\"Internal server error\", ERR_INTERNAL)\n\t}\n\trow, _ := res.RowsAffected()\n\treturn row, nil\n}", "func (service *Service) DeleteProduct(request *restful.Request, response *restful.Response) {\n\tvar req models.ProductRequest\n\tif err := request.ReadEntity(&req); err != nil {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"unable parse request body\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to parse request body:\", err)\n\n\t\treturn\n\t}\n\n\tproduct := models.Product{\n\t\tProductID: req.ProductID,\n\t\tName: req.Name,\n\t\tDescription: req.Description,\n\t\tPrice: req.Price,\n\t\tPaymentID: req.PaymentID,\n\t\tCategoryID: req.CategoryID,\n\t\tUserID: req.UserID,\n\t\tImage: req.Image,\n\t}\n\n\terr := service.server.DeleteProduct(product)\n\tif err == dao.ErrRecordNotFound {\n\t\trespondErr(response, http.StatusBadRequest, messageBadRequest,\n\t\t\t\"product not found\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusBadRequest}).\n\t\t\tError(\"Unable to update product:\", err)\n\n\t\treturn\n\t}\n\tif err != nil {\n\t\trespondErr(response, http.StatusInternalServerError, messageDatabaseError,\n\t\t\t\"unable to update product\")\n\n\t\tlogrus.WithFields(logrus.Fields{\"module\": \"service\", \"resp\": http.StatusInternalServerError}).\n\t\t\tError(\"Unable to update product:\", err)\n\n\t\treturn\n\t}\n\n\tresult := &models.DeleteProductResponse{\n\t\tResult: models.ProductResponse{},\n\t}\n\n\twriteResponse(response, http.StatusNoContent, result)\n}", "func (s *Controller) handleDeleteProduct(c *gin.Context) {\n\n\tproductID, errID := s.getIDParameter(c.Param(\"id\"))\n\tif errID != nil {\n\t\tc.JSON(errID.StatusCode, errID)\n\t\treturn\n\t}\n\n\tdeleteErr := s.productService.DeleteProduct(productID)\n\tif deleteErr != nil {\n\t\tc.JSON(deleteErr.StatusCode, deleteErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, map[string]string{\"status\": \"Deleted\"})\n}", "func Delete(w http.ResponseWriter, r *http.Request){\n\n\t//pegando a url atraves da requisiçãp (.Get = pegar )\n\tidDoProduto := r.URL.Query().Get(\"id\") // pegando o id da url\n\n\tmodels.DeletaProduto(idDoProduto)\n\thttp.Redirect(w, r, \"/\", 301)\n}", "func (s *ProductFieldsService) Delete(ctx context.Context, id int) (*Response, error) {\n\turi := fmt.Sprintf(\"/productFields/%v\", id)\n\treq, err := s.client.NewRequest(http.MethodDelete, uri, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(ctx, req, nil)\n}", "func (p *ProductsDB) DeleteProduct(id int) error {\n\ti := findIndexByProductID(id)\n\tif i == -1 {\n\t\treturn ErrProductNotFound\n\t}\n\tif i == len(productList) - 1 {\n\t\tproductList = productList[:i]\n\t} else {\n\t\tproductList = append(productList[:i], productList[(i+1):]...)\n\t}\n\n\treturn nil\n}", "func (s *ApplicationServer) deleteProductHandler() func(*gin.Context) {\n\ttype deleteProductHandlerURI struct {\n\t\tID int64 `uri:\"id\"`\n\t}\n\n\treturn func(c *gin.Context) {\n\t\tvar request deleteProductHandlerURI\n\n\t\tif err := c.BindUri(&request); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tc.AbortWithStatusJSON(http.StatusUnprocessableEntity, ApplicationServerResponse{\n\t\t\t\tMessage: infrastructure.GetMessageForHTTPStatus(http.StatusUnprocessableEntity),\n\t\t\t\tError: err.Error(),\n\t\t\t\tUnixTimestamp: time.Now().Unix(),\n\t\t\t})\n\n\t\t\treturn\n\t\t}\n\n\t\tif err := warehouse.DeleteProducts(s.State.DB, []int64{request.ID}); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, ApplicationServerResponse{\n\t\t\t\tMessage: infrastructure.GetMessageForHTTPStatus(http.StatusInternalServerError),\n\t\t\t\tError: err.Error(),\n\t\t\t\tUnixTimestamp: time.Now().Unix(),\n\t\t\t})\n\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, ApplicationServerResponse{\n\t\t\tMessage: infrastructure.GetMessageForHTTPStatus(http.StatusOK),\n\t\t\tUnixTimestamp: time.Now().Unix(),\n\t\t})\n\t}\n}", "func (r *SoftwareResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+SoftwareEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *permisoService) Delete(id string) error {\n\t// return s.service.Delete(id)\n\n\treturn nil\n}", "func (c *Client) DeleteProduct(id string) error {\n\treturn c.del(nil, \"products/\"+id)\n}", "func (d *DB) DeleteProductByID(id string) (deleted bool) {\n\tlist := make([]Product, 0, len(d.Products))\n\tfor _, p := range d.Products {\n\t\tif p.ID != id {\n\t\t\tlist = append(list, p)\n\t\t} else {\n\t\t\tdeleted = true\n\t\t}\n\t}\n\td.Products = list\n\treturn\n}", "func (r *SoftwareImageResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+SoftwareImageEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ProductDeleteAction(req *http.Request) (interface{}, error) {\n\tp, err := getProduct(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := container.ProductManager.DeleteProduct(req.Context(), p); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newProductData(p), nil\n}", "func (s *VariantServiceOp) Delete(productID int, variantID int) error {\n\treturn s.client.Delete(fmt.Sprintf(\"%s/%d/variants/%d.json\", productsBasePath, productID, variantID))\n}", "func (m *ProductModel) ProductDelete(user Product) error {\n\terr := db.C(PRODUCT).Remove(&user)\n\treturn err\n}", "func (s *PostgresStorage) Delete(ctx context.Context, productID int) *types.Error {\n\terr := s.Storage.Delete(ctx, productID)\n\tif err != nil {\n\t\treturn &types.Error{\n\t\t\tPath: \".ProductPostgresStorage->Delete()\",\n\t\t\tMessage: err.Error(),\n\t\t\tError: err,\n\t\t\tType: \"pq-error\",\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *SoftwareVolumeResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+SoftwareVolumeEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *VCMPResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+VCMPEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func delete(w http.ResponseWriter, r *http.Request) {\r\n\tid, _ := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\r\n\tquery := \"DELETE from public.item where id=$1\"\r\n\t_, err = db.Exec(query,id)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//json.NewEncoder(w).Encode()\t\r\n}", "func TestProductUC_DeleteProduct(t *testing.T) {\n\n\ttype args struct {\n\t\tc context.Context\n\t\treq entity.Product\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\n\t\twantErr bool\n\t}{\n\t\t//TODO: Add test cases\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\texecutor := &ProductUC{}\n\t\t\terr := executor.DeleteProduct(tt.args.c, tt.args.req)\n\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (s *PaymentStorage) Delete(ctx context.Context, id aggregate.ID) error {\n\tlogger := log.FromContext(ctx)\n\n\tquery := `DELETE FROM %[1]s WHERE id = $1`\n\tquery = fmt.Sprintf(query, s.table)\n\n\tif logger != nil {\n\t\tlogger.Debugf(\"exec in transaction sql %s, values %+v\", query, []interface{}{\n\t\t\tid,\n\t\t})\n\t}\n\n\treturn execInTransaction(s.db, func(tx *sqlx.Tx) error {\n\t\t_, err := tx.ExecContext(ctx, query, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (s *Service) RemoveProductByID(ctx context.Context, id int64) (*types.Products, error) {\n\titem := &types.Products{}\n\n\tsql := `DELETE FROM products WHERE id = $1 RETURNING id, name, price, qty, active, created;`\n\terr := s.pool.QueryRow(ctx, sql, id).Scan(\n\t\t&item.ID,\n\t\t&item.Name,\n\t\t&item.Price,\n\t\t&item.Qty,\n\t\t&item.Active,\n\t\t&item.Created)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, ErrInternal\n\t}\n\treturn item, nil\n}", "func DeleteProductPath() string {\n\treturn \"/api/product/delete\"\n}", "func (k Keeper) RemoveProduct(ctx sdk.Context, id uint64) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ProductKey))\n\tstore.Delete(GetProductIDBytes(id))\n}", "func (m *MockIDb) DeleteProductById(id int64) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteProductById\", id)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (a *App) DeleteProduct(pid int64) *model.AppErr {\n\treturn a.Srv().Store.Product().Delete(pid)\n}", "func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {\n\n\tp := mux.Vars(r)\n\tid := p[\"id\"]\n\n\terr := h.Source.Delete(id)\n\n\tif err != nil {\n\t\te := Error{\n\t\t\tMessage: fmt.Sprintf(\"An error occured when trying to delete the delivery : %s\", err),\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 500)\n\t\treturn\n\t}\n\n\tJSONWithHTTPCode(w, nil, 204)\n\n}", "func JSONDeleteTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\tparamID := c.Param(\"id\")\n\tquery := `DELETE FROM tabelproduct WHERE id ='` + paramID + `';`\n\tupdDB, err := Db.Query(query)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer updDB.Close()\n\tDb.Close()\n\tc.JSON(http.StatusOK, \"Delete record successfully\")\n}", "func Delete(c *gin.Context) {\n\tid, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\terr = utils.DeleteItem(id)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\"status\": \"Item deleted\"})\n}", "func (mu mainUC) Delete(id uint) (interface{}, error) {\n\tcat, err := mu.recipeRepo.Find(id)\n\tif err != nil {\n\t\treturn nil, errors.New(\"recipe data not found\")\n\t}\n\tnow := time.Now()\n\tcat.DeletedAt = &now\n\n\ttx := mu.recipeRepo.DBConn().Begin()\n\terr = mu.recipeRepo.Update(cat, tx)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, errors.New(\"error while deleting recipe\")\n\t}\n\n\ttx.Commit()\n\n\treturn \"recipe deleted\", err\n}", "func (o *RecipeLipid) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no RecipeLipid provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), recipeLipidPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"recipe_lipid\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from recipe_lipid\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for recipe_lipid\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (r *ECMResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+ECMEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t TalentRepositoryImpl) Delete(ctx context.Context, ID int64) error {\n\tquery, args, err := squirrel.Delete(\"talent\").\n\t\tWhere(squirrel.Eq{\"id\": ID}).ToSql()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = t.db.Exec(query, args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"success delete talent with id : %d\", ID)\n\treturn nil\n}", "func (r *pgRepository) Delete(ctx context.Context, tenantID string, id string) error {\n\treturn r.deleter.DeleteOne(ctx, resource.API, tenantID, repo.Conditions{repo.NewEqualCondition(\"id\", id)})\n}", "func (s *Store) Delete(id string) error {\n\t// We're going to be modifying our items slice - lock for writing.\n\ts.mutex.Lock()\n\n\t// Unlock once we're done.\n\tdefer s.mutex.Unlock()\n\n\tremainingItems := make([]item, 0, len(s.items))\n\n\t// Only keep items which do not match the ID provided.\n\tfor _, item := range s.items {\n\t\tif item.id != id {\n\t\t\tremainingItems = append(remainingItems, item)\n\t\t}\n\t}\n\n\t// If the number of items is the same then we haven't found anything to delete.\n\tif len(s.items) == len(remainingItems) {\n\t\treturn moodboard.ErrNoSuchItem\n\t}\n\n\ts.items = remainingItems\n\n\treturn nil\n}", "func (v *Voto) Delete() {\n\tsql := \"DELETE FROM PRO_VOTOS WHERE id=?\"\n\tExec(sql, v.ID)\n}", "func (r *repository) Delete(id uint) error {\n\tif err := r.db.Where(\"id = ?\", id).Delete(&models.Upload{}).Error; err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *CarHandler) Delete(c echo.Context) error {\n\tidP, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\treturn c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})\n\t}\n\n\tid := int64(idP)\n\tctx := c.Request().Context()\n\n\terr = a.CarUsecase.Delete(ctx, id)\n\tif err != nil {\n\t\treturn c.JSON(getStatusCode(err), ResponseError{Message: err.Error()})\n\t}\n\n\treturn c.JSON(http.StatusOK, ResponseError{Message: fmt.Sprintf(\"id %d is deleted.\", id)})\n}", "func DeleteArtikel(id int) (err error) {\n\t_, err = config.Db.Exec(\"delete from Artikel where ArtikelID = $1\", id)\n\treturn\n}", "func (p *pool) deleteFromID(id int) error {\n\tconn := p.Get()\n\tdefer conn.Close()\n\n\text, err := redis.String(conn.Do(\"HGET\", key(\"entry\", strconv.Itoa(id)), \"fileext\"))\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"can not get image extension %d: %w\", id, err)\n\t}\n\n\t// Delete from list\n\tif _, err := conn.Do(\"SREM\", key(\"entries\"), id); err != nil {\n\t\treturn xerrors.Errorf(\"can not delete entry id: %w\", err)\n\t}\n\n\t// Delete from redis\n\tif _, err := conn.Do(\"DEL\", key(\"entry\", strconv.Itoa(id))); err != nil {\n\t\treturn xerrors.Errorf(\"can not delete entry: %w\", err)\n\t}\n\n\t// Delete image from disk\n\tfilePath := path.Join(mailimagePath(), \"images\", fmt.Sprintf(\"%d%s\", id, ext))\n\tif err := os.Remove(filePath); err != nil {\n\t\treturn xerrors.Errorf(\"can not delete image from disk: %w\", err)\n\t}\n\n\t// Delete mail fom disk\n\tfilePath = path.Join(mailimagePath(), \"success\", strconv.Itoa(id))\n\tif err := os.Remove(filePath); err != nil {\n\t\treturn xerrors.Errorf(\"can not delete file from disk: %w\", err)\n\t}\n\treturn nil\n}", "func removeProductHandle(response http.ResponseWriter, request *http.Request) {\n\torderId := strings.Split(request.URL.Path, \"/\")[3]\n\tlog.Printf(\"Remove product for order %s!\", orderId)\n\tdecoder := json.NewDecoder(request.Body)\n\tremoveProductCommand := commands.RemoveProduct{}\n\terr := decoder.Decode(&removeProductCommand)\n\tif err != nil {\n\t\twriteErrorResponse(response, err)\n\t}\n\torder := <-orderHandler.RemoveProductInOrder(OrderId{Id: orderId}, removeProductCommand)\n\twriteResponse(response, order)\n}", "func (sp *serviceProposal) delete(ctx *gin.Context) {\n\tuuid := ctx.Param(\"uuid\")\n\terr := sp.db.DeleteProposal(uuid)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tctx.JSON(http.StatusNoContent, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, nil)\n}", "func (s *OrderItemService) Delete(ctx context.Context, id string) error {\n\treturn s.repo.Delete(ctx, id)\n}", "func (i *Docker) Delete(assembly *global.AssemblyWithComponents, id string) (string, error) {\n\n\tpair_endpoint, perrscm := global.ParseKeyValuePair(assembly.Inputs, \"endpoint\")\n\tif perrscm != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", perrscm)\n\t}\n\n\tpair_id, iderr := global.ParseKeyValuePair(assembly.Components[0].Outputs, \"id\")\n\tif iderr != nil {\n\t\tlog.Error(\"Failed to get the endpoint value : %s\", iderr)\n\t}\n\n\tvar endpoint string\n\tif pair_endpoint.Value == BAREMETAL {\n\n\t\tapi_host, _ := config.GetString(\"docker:swarm_host\")\n\t\tendpoint = api_host\n\n\t} else {\n\t\tendpoint = pair_endpoint.Value\n\t}\n\n\tclient, _ := docker.NewClient(endpoint)\n\tkerr := client.KillContainer(docker.KillContainerOptions{ID: pair_id.Value})\n\tif kerr != nil {\n\t\tlog.Error(\"Failed to kill the container : %s\", kerr)\n\t\treturn \"\", kerr\n\t}\n\tlog.Info(\"Container is killed\")\n\treturn \"\", nil\n}", "func (u *App) Delete(c echo.Context, id string) error {\n\tif err := u.rbac.EnforceRole(c, model.AdminRole); err != nil {\n\t\treturn err\n\t}\n\n\tpost, err := u.udb.View(u.db, id)\n\tif err = zaplog.ZLog(err); err != nil {\n\t\treturn err\n\t}\n\n\tif post.Status != model.StatusDraft {\n\t\treturn zaplog.ZLog(errors.New(\"Apenas é possível eliminar artigos em rascunho\"))\n\t}\n\n\treturn u.udb.Delete(u.db, id)\n}", "func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {\n\tvar res DeleteResult\n\n\t_, res.Err = client.Request(\"DELETE\", resourceURL(client, id), gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\n\treturn res\n}", "func (r *PoolNAPTRResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+PoolNAPTREndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Delete(ctx context.Context, client *selvpcclient.ServiceClient, id string) (*selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL, id}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\terr = responseResult.Err\n\t}\n\treturn responseResult, err\n}", "func Delete(c *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := c.Delete(resourceURL(c, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func DeleteProductEndPoint(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"not implemented yet !\")\n}", "func (r *REST) Delete(ctx kapi.Context, id string) (runtime.Object, error) {\n\tname, tag, err := nameAndTag(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trepo, err := r.imageRepositoryRegistry.GetImageRepository(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif repo.Tags == nil {\n\t\treturn nil, errors.NewNotFound(\"imageRepositoryTag\", tag)\n\t}\n\n\t_, ok := repo.Tags[tag]\n\tif !ok {\n\t\treturn nil, errors.NewNotFound(\"imageRepositoryTag\", tag)\n\t}\n\n\tdelete(repo.Tags, tag)\n\n\terr = r.imageRepositoryRegistry.UpdateImageRepository(ctx, repo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error removing tag from image repository: %s\", err)\n\t}\n\n\treturn &kapi.Status{Status: kapi.StatusSuccess}, nil\n}", "func (o *Inventory) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Inventory provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), inventoryPrimaryKeyMapping)\n\tsql := \"DELETE FROM `inventory` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from inventory\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteByID() {\n\n}", "func (w Webhook) Delete(ctx context.Context, id postmand.ID) error {\n\tquery := `\n\t\tDELETE FROM webhooks WHERE id = $1\n\t`\n\t_, err := w.db.ExecContext(ctx, query, id)\n\treturn err\n}", "func (dao ArtistDAO) Delete(id string) error {\n\treturn dao.getCollection().Remove(bson.M{\"_id\": bson.ObjectIdHex(id)})\n}", "func (s ArticleService) Delete(ctx context.Context, id string) error {\n\tstat := `DELETE FROM article WHERE id = ?;`\n\t_, err := s.DB.ExecContext(ctx, stat, id)\n\treturn err\n}", "func (i Inventory) DelItemById(id int) (string, *ErrHandler) {\n err := i.Db.DelItemById(id)\n if err != nil {\n return \"\", err\n }\n return \"item deleted\", nil\n}", "func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tcop._deleted = true\n\n\treturn nil\n}", "func delete(resource string, id string) ([]byte, error) {\n\thttpParams := &HTTPParams{\n\t\tResource: resource + \"/\" + id,\n\t\tVerb: \"DELETE\",\n\t}\n\treturn processRequest(httpParams)\n}", "func DeleteMachine(w http.ResponseWriter, r *http.Request) {\n id := chi.URLParam(r, \"id\")\n log.Printf(\"Uninstall Machine: id:%s %s\\n\", id, r.Body)\n respondwithJSON(w, http.StatusOK, map[string]string{\"message\": \"update successfully\"})\n\n}", "func (s *Service) Delete(id int) error {\n\treturn s.MedicineRepository.Delete(id)\n}", "func (h *Handler) Delete(ctx *gin.Context) {\n\tpaymentID := ctx.Param(\"paymentID\")\n\terr := h.PaymentResource.Delete(ctx, paymentID)\n\tif err != nil {\n\t\thandleError(ctx, err, 0)\n\t} else {\n\t\tctx.JSON(http.StatusOK, models.JSONAPISuccessObject{Status: http.StatusOK, ID: paymentID})\n\t}\n}", "func (f FileRepo) Delete(context context.Context, id string) (string, error) {\n\topts := options.FindOneAndDelete().SetProjection(bson.D{{\"_id\", 1}})\n\tobjID, err := primitive.ObjectIDFromHex(id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tquery := bson.M{\n\t\t\"_id\": objID,\n\t}\n\tvar delFile model.File\n\terr = f.collection.FindOneAndDelete(context, query, opts).Decode(&delFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn delFile.ID.Hex(), nil\n}", "func (r *FeatureModuleResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+FeatureModuleEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, id), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}" ]
[ "0.7757489", "0.76673293", "0.76519656", "0.7512921", "0.7440399", "0.74301046", "0.7407575", "0.73662084", "0.7328349", "0.73067236", "0.7305396", "0.72893065", "0.72891355", "0.72719294", "0.71947736", "0.7177986", "0.7172759", "0.7170307", "0.716193", "0.7072734", "0.69870406", "0.6914507", "0.68965256", "0.68610054", "0.68050826", "0.6754969", "0.6743646", "0.6705128", "0.66452336", "0.6641585", "0.66350687", "0.66231436", "0.65914285", "0.6569521", "0.6547649", "0.6539508", "0.65389055", "0.6421396", "0.6415199", "0.63664114", "0.63579357", "0.633578", "0.63315874", "0.63258076", "0.6290464", "0.62737393", "0.6272432", "0.6233744", "0.6220692", "0.6206218", "0.61954325", "0.61842805", "0.6160985", "0.61589366", "0.61404115", "0.61105037", "0.60912794", "0.60713065", "0.60480446", "0.60327923", "0.6010813", "0.5996406", "0.5984363", "0.5956206", "0.5953478", "0.59526724", "0.59463054", "0.59398836", "0.59387994", "0.5934711", "0.5933924", "0.5931582", "0.5930135", "0.5923725", "0.5906095", "0.58881456", "0.5879351", "0.5877162", "0.5876602", "0.58672255", "0.585595", "0.58513623", "0.5846537", "0.58433187", "0.5843119", "0.58332676", "0.58139795", "0.58133817", "0.5813086", "0.580682", "0.5795714", "0.57943904", "0.5791532", "0.57726616", "0.5764278", "0.57620823", "0.5759811", "0.5759811", "0.5759811", "0.5759811" ]
0.6546024
35
InitializeDB brings the database into an initialized state
func InitializeDB(connection *gorm.DB) { connection.AutoMigrate(&ent.City{}) connection.AutoMigrate(&ent.CityCollection{}) var initialContent []ent.CityCollection // populate the database with initial fixtures if it is empty connection.Find(&initialContent) if len(initialContent) == 0 { populateDatabase(connection) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func InitializeDB(dbfile string) error {\n\tCloseDB()\n\tdb, err := prepareDB(dbfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tadb = &agendaDB{\n\t\tdb: db,\n\t\tfile: dbfile,\n\t\tqueue: startExecQueue(db),\n\t}\n\treturn nil\n}", "func InitDatabase(dbName *string, dst ...interface{}) {\n\tlog.Info().Msgf(\"Loading database %v\", *dbName)\n\tvar err error\n\tdbFile = sqlite.Open(fmt.Sprintf(\"%v.db\", *dbName))\n\tdatastore, err = gorm.Open(dbFile, &gorm.Config{\n\t\tDisableForeignKeyConstraintWhenMigrating: true,\n\t})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\t// Migrate the schema\n\terr = datastore.AutoMigrate(dst...)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Migration failed! Please check the logs!\")\n\t}\n}", "func InitializeDB() *Database {\n\tconfig := new(dbConfig)\n\tconfigFile, err := ioutil.ReadFile(\"config.yaml\")\n\terr = yaml.Unmarshal(configFile, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcredentials := fmt.Sprintf(\"%s:%s@/%s?charset=utf8&parseTime=True&loc=Local\", config.Database.DatabaseUser, config.Database.DatabasePassword, config.Database.Database)\n\tdialect := config.Database.DatabaseType\n\n\tdb, err := gorm.Open(dialect, credentials)\n\tif err != nil {\n\t\tlog.Fatal().Msgf(\"Failed to connect to Database. Reason: %v\\n\", err)\n\t}\n\tlog.Info().Msg(\"Successfully connected to qBot Database.\")\n\n\tdb.DB().SetConnMaxLifetime(time.Second * 100)\n\tdb.DB().SetMaxIdleConns(50)\n\tdb.DB().SetMaxOpenConns(200)\n\n\t//db.DropTableIfExists(models.User{}, models.Question{}, models.Answer{}) // Temp\n\t//db.DropTable(\"user_questions\", \"question_answers\", \"user_answers\") // Temp\n\tif err := db.AutoMigrate(models.User{}, models.Question{}, models.Answer{}).Error; err != nil {\n\t\tlog.Fatal().Msgf(\"Unable to migrate database. \\nReason: %v\", err)\n\t}\n\tlog.Info().Msg(\"Database migration successful.\")\n\treturn &Database{db}\n}", "func (sql *SqlConnection) InitDB() error {\n\n\tvar err error\n\n\t// open a db connection //\n\tsql.Db, err = gorm.Open(\"sqlite3\", \"/var/tmp/tennis.db\")\n\tif err != nil {\n\t\tfmt.Println(\"Failed to connect database : \", err.Error())\n\t}\n\tsql.Db.LogMode(true)\n\n\treturn err\n}", "func InitializeDB(models ...interface{}) *gorm.DB {\n\tdb, err := ConnectDB()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tdb.DB()\n\tfor _, model := range models {\n\t\tdb.AutoMigrate(model)\n\t}\n\n\treturn db\n}", "func InitializeDatabase(config string, log debug.Logger) {\n\tdatabaseAccess = databaseConnection{dbconfig: config, log: log}\n\tdatabaseAccess.initialize()\n}", "func initializeDB(path string) error {\n\tstore, err := buntdb.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer store.Close()\n\n\terr = store.Update(func(tx *buntdb.Tx) error {\n\t\t// set schema version\n\t\ttx.Set(keySchemaVersion, strconv.Itoa(latestDbSchema), nil)\n\t\ttx.Set(keyCloakSecret, utils.GenerateSecretKey(), nil)\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func InitializeDB() error {\n\tdsn := fmt.Sprintf(\"user=%s password=%s dbname=%s host=%s port=%s sslmode=disable\",\n\t\tconfig.C.Database.Postgres.PostgresUsername,\n\t\tconfig.C.Database.Postgres.PostgresPassword,\n\t\tconfig.C.Database.Postgres.PostgresDatabaseName,\n\t\tconfig.C.Database.Postgres.PostgresHost,\n\t\tconfig.C.Database.Postgres.PostgresConnectionPort,\n\t)\n\n\tvar err error\n\tDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\n\tdoAutoMigrations()\n\n\treturn err\n}", "func (db *DbCtxt) InitDatabase() error {\n\tvar models []interface{}\n\tmodels = append(models,\n\t\t&Hotel{},\n\t\t&Room{},\n\t\t&RatePlan{},\n\t)\n\tfor _, model := range models {\n\t\terr := db.client.AutoMigrate(model)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func InitDB(path string) error {\n\tif err := checkDBReadyForInit(path); err != nil {\n\t\treturn err\n\t}\n\n\tif err := initializeDB(path); err != nil {\n\t\treturn fmt.Errorf(\"Could not save datastore: %w\", err)\n\t}\n\treturn nil\n}", "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 (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 Initialize() error {\n\tsugar.Debug(\"Initialize\")\n\tif nil != DB {\n\t\tDB.Close()\n\t\tDB = nil\n\t}\n\tif err := removeDatabase(); err != nil {\n\t\treturn err\n\t}\n\treturn ConnectDB()\n}", "func (env *Env) InitDB(filename string) {\n\t// sqlite3 database\n\tdb, err := gorm.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// setup schema\n\tdb.AutoMigrate(&WineInfo{})\n\n\tenv.db = db\n}", "func InitDb() *gorm.DB {\n\tdb := openConnection()\n\n\tmodels.RunMigrations(db)\n\treturn db\n}", "func InitDB() {\n\tvar err error\n\tdb, err = gorm.Open(sqlite.Open(\"./test.db\"), &gorm.Config{})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\treturn\n}", "func InitDB(dataSourceName string) (*sqlx.DB, error) {\n\tvar err error\n\n\tdb, err = sqlx.Open(\"sqlite3\", dataSourceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttableSchema := `CREATE TABLE IF NOT EXISTS agents (\n\t\tagent_id TEXT PRIMARY KEY UNIQUE,\n\t\tstarted_at datetime NOT NULL,\n\t\tterminated_at datetime,\n\t\tcurrent_status TEXT NOT NULL,\n\t\teffective_config TEXT NOT NULL\n\t);`\n\n\t_, err = db.Exec(tableSchema)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error in creating agents table: %s\", err.Error())\n\t}\n\n\tAllAgents = Agents{\n\t\tagentsById: make(map[string]*Agent),\n\t\tconnections: make(map[types.Connection]map[string]bool),\n\t\tmux: sync.RWMutex{},\n\t}\n\treturn db, nil\n}", "func InitDB() *DB {\n\treturn &DB{\n\t\tActiveReq: InitActReq(),\n\t\tInactiveReq: &InactiveReq{},\n\t}\n}", "func DBInit() {\n\t// Mode = \"PRODUCTION\"\n\t// if Mode == \"PRODUCTION\" {\n\t// \tDatabaseURL = \"test.sqlite3\"\n\t// \tDatabaseName = \"sqlite3\"\n\t// } else if Mode == \"DEPLOY\" {\n\tDatabaseURL = os.Getenv(\"DATABASE_URL\")\n\tDatabaseName = \"postgres\"\n\t// }\n\n\tdb, err := gorm.Open(DatabaseName, DatabaseURL)\n\tif err != nil {\n\t\tpanic(\"We can't open database!(dbInit)\")\n\t}\n\t//残りのモデルはまだ入れてない。\n\tdb.AutoMigrate(&model.Post{})\n\tdb.AutoMigrate(&model.User{})\n\tdb.AutoMigrate(&model.Room{})\n\tdefer db.Close()\n}", "func initDatabase() {\n\tif dbPath == \"\" {\n\t\t// No path provided, use the default path\n\t\tdbPath = getDefaultDBPath()\n\t}\n\t// Start the database\n\tdb, err := poddata.New(dbPath)\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\tdata = db\n}", "func InitDB() {\n\tvar err error\n\tdatabase.DBConn, err = gorm.Open(sqlite.Open(\"books.db\"), &gorm.Config{})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\tfmt.Println(\"Database successfully connected\")\n\tdatabase.DBConn.AutoMigrate(&book.Book{})\n}", "func (i *API) InitDB(purge bool) error {\n\tif purge {\n\t\ti.purgeDB()\n\t}\n\treturn i.openDB()\n}", "func InitDB(dbPath string) *gorm.DB {\n\tdb, err := gorm.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdb.AutoMigrate(&GPSDataSet{})\n\n\treturn db\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 (d *DBManager) Init() (err error) {\n\tif d.db, err = initDatabase(); err != nil {\n\t\treturn err\n\t}\n\n\treturn prepareSQL(d)\n}", "func InitDb() {\n\tdbConnection.MustExec(schema)\n}", "func initDB(databaseFile string) {\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", databaseFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Initalized connection with \" + databaseFile + \"!\")\n}", "func InitDB() *DB {\n\tdb, err := gorm.Open(dbEngine, dbName)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to initialize database: \", err.Error())\n\t}\n\n\tdb.AutoMigrate(&inventory.Stock{}, &inventory.StockIn{}, &inventory.StockOut{}, &inventory.StockValue{}, &inventory.SaleReport{})\n\n\treturn &DB{db}\n}", "func InitDatabase(dsn string) error {\n\tfmt.Println(\"Init db connection\")\n\t// config := mysql.NewConfig()\n\t// config.User = username\n\t// config.Passwd = password\n\t// config.Net = protocol\n\t// config.Addr = host\n\t// config.DBName = database\n\t// config.Params = map[string]string{\n\t// \t\"charset\": charset,\n\t// \t\"parseTime\": \"True\",\n\t// }\n\tdb, err := gorm.Open(\"sqlite3\", dsn)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tDbConn = db\n\treturn nil\n}", "func (bdm *MySQLDBManager) InitDatabase() error {\n\n\tbdm.OpenConnection()\n\n\tdefer bdm.CloseConnection()\n\n\tbc, err := bdm.GetBlockchainObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = bc.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxs, err := bdm.GetTransactionsObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = txs.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tutx, err := bdm.GetUnapprovedTransactionsObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = utx.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuos, err := bdm.GetUnspentOutputsObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = uos.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tns, err := bdm.GetNodesObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ns.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdr, err := bdm.GetDataReferencesObject()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = dr.InitDB()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func InitDatabase(dbPath string, dbFile string, force bool) {\n\tif dbPath == \"\" {\n\t\tDbPath = defaultDbPath\n\t} else {\n\t\tDbPath = dbPath\n\t}\n\tif dbFile == \"\" {\n\t\tDbFile = defaultDbFile\n\t} else {\n\t\tDbFile = dbFile\n\t}\n\n\texisted, err := pathutil.DirExists(DbPath)\n\tcheckError(err)\n\tif existed {\n\t\tif force {\n\t\t\tos.RemoveAll(DbPath)\n\t\t\tlog.Info(\"Remove old dbPath and recreate: %s\", DbPath)\n\t\t\tos.MkdirAll(DbPath, os.ModePerm)\n\t\t} else {\n\t\t\tlog.Info(\"Database directory (%s) existed. Nothing happended. Use --force to reinit\", DbPath)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tos.MkdirAll(DbPath, os.ModePerm)\n\t}\n}", "func InitDb(appConfig *AppConfig) {\n\tlog.Info(\"Initialize database connection\")\n\tDbs = fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s\",\n\t\tappConfig.Db.Host,\n\t\tappConfig.Db.Port,\n\t\tappConfig.Db.User,\n\t\tappConfig.Db.Password,\n\t\tappConfig.Db.DbName,\n\t\tappConfig.Db.SSLMode,\n\t)\n\tlog.Info(\"Successfully initialize database connection\")\n\tdb := GetDB()\n\tlog.Info(\"Start table migrations\")\n\tdb.AutoMigrate(\n\t\t&Session{},\n\t)\n\tlog.Info(\"Table migrations achieved\")\n}", "func InitDb() *gorm.DB {\n\t// Openning file\n\tdb, err := gorm.Open(\"sqlite3\", \"./data.db\")\n\t// Display SQL queries\n\tdb.LogMode(true)\n\n\t// Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Creating the table\n\tif !db.HasTable(&Users{}) {\n\t\tdb.CreateTable(&Users{})\n\t\tdb.Set(\"gorm:table_options\", \"ENGINE=InnoDB\").CreateTable(&Users{})\n\t}\n\n\treturn db\n}", "func Initialize() error {\n\tpath := filepath.Join(config.DataDir(), \"mud.db\")\n\n\tvar err error\n\tdb, err = bolt.Open(path, 0644, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error opening database file %q: %s\", path, err)\n\t}\n\treturn nil\n}", "func InitDB(path string) error {\n\tdb, err := sql.Open(\"sqlite3\", path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\tfor _, tableSQL := range SQLCreateTables() {\n\t\tif _, err := db.Exec(tableSQL); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Use Write Ahead Logging which improves SQLite concurrency.\n\t// Requires SQLite >= 3.7.0\n\tif _, err := db.Exec(\"PRAGMA journal_mode = WAL\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Check if the WAL mode was set correctly\n\tvar journalMode string\n\tif err = db.QueryRow(\"PRAGMA journal_mode\").Scan(&journalMode); err != nil {\n\t\tlog.Fatalf(\"Unable to determine sqlite3 journal_mode: %v\", err)\n\t}\n\tif journalMode != \"wal\" {\n\t\tlog.Fatal(\"SQLite Write Ahead Logging (introducted in v3.7.0) is required. See http://perkeep.org/issue/114\")\n\t}\n\n\t_, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))\n\treturn err\n}", "func InitDatabase(db *sql.DB) {\n\tcreateLinksTableSQL := `CREATE TABLE IF NOT EXISTS links (\n\t\t\"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n\t\t\"url\" TEXT,\n\t\t\"created_at\" TEXT\n\t);`\n\n\tstatement, err := db.Prepare(createLinksTableSQL)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating links table: %v\\n\", err)\n\t}\n\tstatement.Exec()\n}", "func (st *Store) initDB() error {\n\n\tvar err error\n\n\tver, err := st.schemaVersion()\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch ver {\n\tcase 0:\n\t\t// starting from scratch\n\t\tschema := `\nCREATE TABLE url (\n\tid INTEGER PRIMARY KEY,\n\turl TEXT NOT NULL,\n\thash TEXT NOT NULL,\n\tpage_id INTEGER NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\nCREATE TABLE page (\n\tid INTEGER PRIMARY KEY,\n\tcanonical_url TEXT NOT NULL,\n\ttitle TEXT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\n);\n\nCREATE TABLE warning (\n\tid INTEGER PRIMARY KEY,\n\tpage_id INTEGER NOT NULL,\n\tkind TEXT NOT NULL,\n\tquant INT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\n\nCREATE TABLE version (\n\tver INTEGER NOT NULL );\n\nINSERT INTO version (ver) VALUES (1);\n`\n\t\t//\t\t`CREATE INDEX article_tag_artid ON article_tag(article_id)`,\n\t\t//\t\t`CREATE INDEX article_url_artid ON article_url(article_id)`,\n\n\t\t_, err = st.db.Exec(schema)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\tcase 1: // all good. this is what we're expecting\n\t\tbreak\n\tdefault:\n\t\treturn fmt.Errorf(\"Bad db schema version (expected 1, got %d)\", ver)\n\t}\n\n\treturn nil\n}", "func InitDB(driver, connectionstring string) error {\n\tdb, err := gorm.Open(driver, connectionstring)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsetDB(db)\n\treturn nil\n}", "func InitDb(conf config.Config, reset bool) error {\n\tif !IsOpen() {\n\t\tif err := openAdapter(conf); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn adp.CreateDb(reset)\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 (d *DB) Init(c *Controller, dbFile string) error {\n\td.c = c\n\tdb, err := sql.Open(\"sqlite3\", dbFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\td.db = db\n\t//defer d.db.Close()\n\n\t_, err = d.db.Exec(`\n create table if not exists articles(\n\t\t\tid integer not null primary key,\n\t\t\tfeed text,\n\t\t\ttitle text,\n\t\t\tcontent text,\n\t\t\tlink text,\n\t\t\tread bool,\n\t\t\tdisplay_name string,\n\t\t\tdeleted bool,\n\t\t\tpublished DATETIME\n\t\t);`)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *bankCase) Initialize(ctx context.Context, db *sql.DB) error {\n\tlog.Infof(\"[%s] start to init...\", c)\n\tdefer func() {\n\t\tlog.Infof(\"[%s] init end...\", c)\n\t}()\n\tfor i := 0; i < c.cfg.Tables; i++ {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t\terr := c.initDB(ctx, db, i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Init() *gorm.DB {\n\tdb, err := gorm.Open(\"sqlite3\", \"test.db\")\n\tif err != nil {\n\t\tfmt.Println(\"db err: \", err)\n\t}\n\tdb.DB().SetMaxIdleConns(10)\n\tdb.LogMode(true)\n\tDB = db\n\treturn DB\n}", "func InitDB() {\n\tvar err error\n\tvar connectionString = fmt.Sprintf(\"%v:%v@%v/%v\", dbUser, dbPassword, dbHost, dbName)\n\tlog.Println(\"Connection String: \" + connectionString)\n\tdb, err = sql.Open(\"mysql\", connectionString)\n\tdbmap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{Engine: \"InnoDB\", Encoding: \"UTF8\"}}\n\tdbmap.TraceOn(\"[gorp]\", log.New(os.Stdout, \"myapp:\", log.Lmicroseconds))\n\tif err != nil {\n\t\tlog.Println(\"Failed to connect to database: \")\n\t\tlog.Panic(err)\n\t} else {\n\t\terr = db.Ping()\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed to ping database: \")\n\t\t\tlog.Panic(err)\n\t\t} else {\n\t\t\tlog.Println(\"Database connected.\")\n\t\t}\n\t}\n\n\t_ = dbmap.AddTableWithName(Article{}, \"flat_articles\").SetKeys(false, \"ID\")\n\tdbmap.CreateTablesIfNotExists()\n}", "func InitDB(dbfile string) error {\n\tif _, err := os.Stat(dbfile); os.IsNotExist(err) {\n\t\terr := createDB(dbfile)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"unable to create db\")\n\t\t}\n\t} else if err != nil {\n\t\treturn errors.Wrap(err, \"unexpected error looking for sqlite3 db file\")\n\t} else {\n\t\tlog.Printf(\"%s found\", dbfile)\n\t}\n\n\treturn nil\n}", "func InitDatabase(database *models.Database) error {\n\tdb, err := getDatabase(database)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Registering database: %s\", db.String())\n\tif err := db.Register(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Register database completed\")\n\treturn nil\n}", "func InitDB() {\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"../../resources/imgtag.db\")\n\tif err != nil {\n\t\tlog.Fatal(\"can't open db\", err)\n\t}\n}", "func (this *DBHandler) Init() {\n\tvar derr error\n\tthis.db, derr = sql.Open(\"sqlite3\", DB_FILE_NAME)\n\tif derr != nil {\n\t\tfmt.Println(derr)\n\t}\n\tthis.createNewTable(TABLE_WPA)\n\tthis.createNewTable(TABLE_WORDLISTS)\n\tthis.createNewTable(TABLE_RUNS)\n}", "func initDB(dbFile string) (*sql.DB, error) {\n\n\tDB, err := sql.Open(\"sqlite3\", dbFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening Database connection: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn DB, nil\n}", "func InitDB() *sql.DB {\n\tdb, err := sql.Open(\"sqlite3\", \"./angebote.db\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif db == nil {\n\t\tpanic(\"db nil\")\n\t}\n\n\treturn db\n}", "func InitDatabase(redisClient *redis.Client, logger log.Logger) (err error) {\n\t// Checking if database is already exists.\n\tok := false\n\tif ok, err = databaseCheck(redisClient, logger); ok || (err != nil) {\n\t\treturn\n\t}\n\t// Getting list of girls.\n\tlogger.Info(\"Updating database.\")\n\treturn parseMGEWiki(redisClient, logger)\n}", "func initializeDB() *gorm.DB {\n\t// load Env Variables\n\tHOST := os.Getenv(\"HOST\")\n\tDB_PORT := os.Getenv(\"DB_PORT\")\n\tUSER := os.Getenv(\"USER\")\n\tNAME := os.Getenv(\"NAME\")\n\tPASSWORD := os.Getenv(\"PASSWORD\")\n\n\t// Data connection string\n\tDB_URI := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=disable password=%s port=%s\", HOST, USER, NAME, PASSWORD, DB_PORT)\n\t\n\t// Open DB\n\tdb, err := gorm.Open(postgres.Open(DB_URI), &gorm.Config{})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tfmt.Println(\"DB Connected successfully\")\n\t}\n\n\tdb.AutoMigrate(&models.Person{})\n\tdb.AutoMigrate(&models.Book{})\n\n\treturn db\n}", "func InitDB() (*gorm.DB, error) {\n\t// attempt to open a new connection to the db\n\tglog.Info(\"Opening a new connection to the db...\")\n\tconnStr := fmt.Sprintf(\n\t\t\"%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local\", \n\t\tconfig.DbUsername, config.DbPassword, config.DbHostName, config.DbName,\n\t)\n\tdb, err := gorm.Open(config.DbDriver, connStr);\n\tif err != nil {\n\t\treturn db, err\n\t}\n\treturn db, err\n}", "func (d *database) Initialize() error {\n\terr := d.createTable(sqlCreateGeneralLedgerTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.createTable(sqlCreateJournalEntriesTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InitDB() (*gorm.DB, error) {\n\tdb, err := gorm.Open(\"sqlite3\", \"./url.db\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb.LogMode(true)\n\tmodels.Migrate(db)\n\treturn db, err\n}", "func DbInit() {\n\tsqlStatement := `\n\t\tCREATE TABLE benutzer (\n\t\t\tfdNummer VARCHAR(256) PRIMARY KEY, \n\t\t\tVorname VARCHAR(256) NOT NULL, \n\t\t\tNachname VARCHAR(256) NULL,\n\t\t\tAge TINYINT NULL,\n\t\t\tStudiengang VARCHAR(256) NULL,\n\t\t\tSemester TINYINT NULL\n\t\t\t);\n\n\t\tCREATE TABLE nachrichten (\n\t\t\tNachrichtID INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tfdNummer VARCHAR(256) NOT NULL,\n\t\t\tGroupID INTEGER NOT NULL,\n\t\t\tmessage VARCHAR(256) NOT NULL,\n\t\t\tgesendeteUhrzeit DEFAULT CURRENT_TIMESTAMP\n\t\t\t);\n\n\t\tCREATE TABLE chatgroup (\n\t\t\tGroupID INTEGER PRIMARY KEY,\n\t\t\tGroupName VARCHAR(256) NOT NULL\n\t\t\t);\n\t`\n\n\tCreate(sqlStatement)\n}", "func InitDB(dbPath string) error {\n\tvar err error\n\n\tdb, err = bolt.Open(\n\t\tdbPath, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists(taskBucket)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"create bucket: %s\", err)\n\t\t}\n\t\treturn nil\n\t})\n}", "func InitDB(cfg abcconfig.DBConfig) error {\n\t// No username provided is a signal to skip database usage\n\tif len(cfg.User) == 0 {\n\t\treturn nil\n\t}\n\n\tconnStr, err := abcdatabase.GetConnStr(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDB, err = sql.Open(cfg.DB, connStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := DB.Ping()\n\tif p != nil {\n\t\treturn p\n\t}\n\n\treturn nil\n}", "func InitDB() *sql.DB {\n\t__db, err := sql.Open(\"sqlite3\", \"../realdb.db\")\n\tif err != nil { panic(err) }\n if __db == nil { panic(\"db nil\") }\n\n\treturn __db\n}", "func InitializeDB(dynamoInitChan chan struct{}) chan struct{} {\n\tdbInitChan := make(chan struct{})\n\tgo func() {\n\n\t\t<-dynamoInitChan\n\n\t\t// Create all tables\n\t\tvar c Complex\n\t\tif err := dynahelpers.CreateTable(c); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// chatbot.RegisterType(c)\n\n\t\tvar pd ParkingDeck\n\t\tif err := dynahelpers.CreateTable(pd); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// chatbot.RegisterType(pd)\n\n\t\tvar ps ParkingSpace\n\t\tif err := dynahelpers.CreateTable(ps); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// chatbot.RegisterType(ps)\n\n\t\tvar r Residence\n\t\tif err := dynahelpers.CreateTable(r); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// chatbot.RegisterType(r)\n\n\t\tvar rsdnt Resident\n\t\tif err := dynahelpers.CreateTable(rsdnt); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// chatbot.RegisterType(rsdnt)\n\n\t\tdbInitChan <- struct{}{}\n\t}()\n\treturn dbInitChan\n}", "func (d *DB) InitDB() {\n\tdb, err := gorm.Open(\"mysql\", \"root@/users?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tpanic(\"failed to connect to the database :(\")\n\t}\n\t// defer db.Close()\n\n\tdb.AutoMigrate(&User{})\n\n\td.db = db\n\td.CodeMap = make(map[string]CodeItem)\n\td.CodeMap[\"\"] = CodeItem{Code: -1}\n}", "func DBInit(conStr string) {\n\tif db == nil {\n\t\tvar err error\n\t\tdbConnection, err := gorm.Open(\"mysql\", conStr+\"?charset=utf8&parseTime=True&loc=Local\")\n\t\t// db connection will be closed if there's no request for a while\n\t\t// which would cause 500 error when a new request comes.\n\t\t// diable pool here to avoid this problem.\n\t\tdbConnection.DB().SetMaxIdleConns(0)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t}).Fatal(\"Faile to create db connection pool\")\n\t\t} else {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"message\": dbConnection.GetErrors(),\n\t\t\t\t\"db\": conStr,\n\t\t\t}).Info(\"connected to mysql\")\n\t\t}\n\t\tdb = &DB{dbConnection}\n\t}\n\tdb.dbConnect.SetLogger(log.StandardLogger())\n\t// db.Debug message will be logged be logrug with Info level\n\tdb.dbConnect.Debug().AutoMigrate(&Todo{})\n}", "func (p *Oracle) InitDB(connectionString string) error {\n\tdb, err := InitDatabase(\"goracle\", connectionString)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.db = db\n\treturn nil\n}", "func (s *Server) InititalizeEmptyDatabase() error {\n\tctx := context.Background()\n\tdefer ctx.Done()\n\ttx, err := s.Database.BeginTx(ctx, &sql.TxOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar count int\n\terr = tx.QueryRow(\"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users';\").Scan(&count)\n\tif err != nil || count == 1 {\n\t\ttx.Rollback()\n\t\treturn errors.New(\"Database already initialized\")\n\t}\n\t_, err = tx.Exec(`CREATE TABLE users (\n username VARCHAR(255) NOT NULL,\n\t\tpassword VARCHAR(1024) NOT NULL,\n\t\tPRIMARY KEY (username)\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(`CREATE TABLE sessions (\n username VARCHAR(255) NOT NULL,\n\t\tsession VARCHAR(255) NOT NULL,\n\t\tPRIMARY KEY (username,session)\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(`CREATE TABLE permissions (\n username VARCHAR(255) NOT NULL,\n\t\tscope VARCHAR(64) NOT NULL,\n\t\tpermission VARCHAR(64) NOT NULL,\n\t\tPRIMARY KEY (username,scope),\n\t\tCONSTRAINT FK_UserPermission FOREIGN KEY (username) REFERENCES username\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func InitDb() {\n\tconfig, err := dbConfig()\n\tif err != nil {\n\t\tglog.Fatalln(err)\n\t}\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%s user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\",\n\t\tconfig[dbhost], config[dbport],\n\t\tconfig[dbuser], config[dbpass], config[dbname])\n\n\tDb, err = sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tglog.Fatalln(err)\n\t}\n\terr = Db.Ping()\n\tif err != nil {\n\t\tglog.Fatalln(err)\n\t}\n\tglog.Infoln(\"Successfully connected to Database!\")\n\t// Create table in database if not present\n\tcreateTable()\n}", "func initdb() {\n\tdir, _ := os.Getwd()\n\tdatabasepath := filepath.Join(dir, \"tasks.db\")\n\tdbrepository.InitDatabase(databasepath)\n}", "func Initialize(dbDriver *sql.DB) {\n\tstatement, driverError := dbDriver.Prepare(trainTable)\n\tif driverError != nil {\n\t\tlog.Println(driverError)\n\t}\n\tstatement.Exec()\n\tstatement, _ = dbDriver.Prepare(stationTable)\n\tstatement.Exec()\n\tstatement, _ = dbDriver.Prepare(scheduleTable)\n\tstatement.Exec()\n\tlog.Println(\"All tables created/initialized successfully!\")\n}", "func InitTestDB() error {\n\tif db == nil {\n\t\treturn errors.New(\"database not initialized\")\n\t}\n\n\tfor i := 0; i < 1000; i++ {\n\t\tkey := intToByteArray(i)\n\t\tvalue := GetByteArray(\"hello from \"+strconv.Itoa(i), \"string\")\n\t\terr := Insert(key, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Initialize() {\n\tfmt.Println(\"inited DB\")\n\tvar err error\n\tclient, err = mongo.Connect(bg(), options.Client().ApplyURI(config.DatabaseURL))\n\tif err != nil {\n\t\tlog.Fatalf(\"%+v\\n\", err)\n\t}\n\n\tdb = client.Database(config.DatabaseName)\n}", "func (p *Pool) initDB() error {\n\t// Create and open the database.\n\tdb, err := database.OpenDB(p.cfg.DBFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.db = db\n\terr = database.CreateBuckets(p.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check if the pool mode changed since the last run.\n\tvar switchMode bool\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tpbkt := tx.Bucket(database.PoolBkt)\n\t\tif pbkt == nil {\n\t\t\treturn err\n\t\t}\n\n\t\tv := pbkt.Get(database.SoloPool)\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tspMode := binary.LittleEndian.Uint32(v) == 1\n\t\tif p.cfg.SoloPool != spMode {\n\t\t\tswitchMode = true\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the pool mode changed, backup the current database and purge all data\n\t// for a clean slate with the updated pool mode.\n\tif switchMode {\n\t\tpLog.Info(\"Pool mode changed, backing up database before purge.\")\n\t\terr := database.Backup(p.db)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = database.Purge(p.db)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// If the pool mode did not change, upgrade the database if there is a\n\t// pending upgrade.\n\tif !switchMode {\n\t\terr = database.Upgrade(p.db)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func InitDatabase(driverName, dataSourceName string, numRetries int, sleepDuration time.Duration) *sql.DB {\n\tvar err error\n\tvar db *sql.DB\n\tfor i := 0; i < numRetries; i++ {\n\t\tdb, err = sql.Open(driverName, dataSourceName)\n\t\tif err == nil {\n\t\t\tlog.Println(\"DB connection initialized...\")\n\t\t\tbreak\n\t\t}\n\t\tlog.Println(\"DB connection failed to initialize... Sleeping...\")\n\t\ttime.Sleep(sleepDuration)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tlog.Printf(\"Successfully connected to DB: %s\\n\", dataSourceName)\n\t}\n\treturn db\n}", "func (programRepo *mockProgramRepo) Initialize(ctx context.Context, db *sql.DB) {}", "func Initialize() {\n\tdatabaseHost := os.Getenv(\"DB_HOST\")\n\tdatabasePort := os.Getenv(\"DB_PORT\")\n\tdatabaseUser := os.Getenv(\"DB_USER\")\n\tdatabasePass := os.Getenv(\"DB_PASS\")\n\tdatabaseName := os.Getenv(\"DB_NAME\")\n\n\tpostgresConnectionURL := fmt.Sprintf(\"postgres://%s:%s@%s:%s/%s?sslmode=disable\", databaseUser, databasePass, databaseHost, databasePort, databaseName)\n\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", postgresConnectionURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t//defer db.Close()\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmaxOpenConn, err := strconv.Atoi(os.Getenv(\"DB_MAX_OPEN_CONN\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmaxIdleConn, err := strconv.Atoi(os.Getenv(\"DB_MAX_IDLE_CONN\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb.SetMaxOpenConns(maxOpenConn)\n\tdb.SetMaxIdleConns(maxIdleConn)\n\n\tfmt.Println(\"Database connected!\")\n\n}", "func (Server *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) {\n\n\tvar err error\n\tDBURL := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local\", DbUser, DbPassword, DbHost, DbPort, DbName)\n\tServer.DBServer, err = gorm.Open(Dbdriver, DBURL)\n\tif err != nil {\n\t\tfmt.Printf(\"Cannot connect to %s database\", Dbdriver)\n\t\tlog.Fatal(\"This is the error:\", err)\n\t} else {\n\t\tfmt.Printf(\"We are connected to the %s database\", Dbdriver)\n\t}\n\n\tServer.DBServer.Debug().AutoMigrate(&Data{})\n}", "func InitializeDB() *gorm.DB {\n\tdb, err := gorm.Open(\"mysql\", \"root:root@tcp(127.0.0.1:3306)/referee?parseTime=true&readTimeout=1s&writeTimeout=1s&timeout=1s\")\n\tCheck(err)\n\n\treturn db\n}", "func InitDB() {\n\tos.Remove(\"./threat_analyser.db\")\n\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"./threat_analyser.db\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcreateCmd := `\n\tcreate table ip (ip_address TEXT PRIMARY KEY,\n\t\t\t\t\t uuid TEXT,\n\t\t\t\t\t created_at DATETIME,\n\t\t\t\t\t updated_at DATETIME,\n\t\t\t\t\t response_code TEXT);\n\t`\n\t_, err = db.Exec(createCmd)\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating DB table\", err)\n\t\treturn\n\t}\n}", "func Init() {\n\tvar err error\n\tdb, err = sql.Open(\"sqlite3\", \"db-data/app.db\")\n\tif err != nil {\n\t\tlog.Fatal(\"failed to open db: \", err)\n\t}\n\n\tif _, err := db.Exec(createStmt); err != nil {\n\t\tlog.Fatal(\"failed to initialize db: \", err)\n\t}\n}", "func Init(dbpath string) {\n\tdatabase.db, err = sql.Open(\"sqlite3\", dbpath+\"?loc=auto&parseTime=true\")\n\t// database.db, err = sql.Open(\"mysql\", \"Username:Password@tcp(Host:Port)/standardnotes?parseTime=true\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif database.db == nil {\n\t\tlog.Fatal(\"db nil\")\n\t}\n\tdatabase.createTables()\n}", "func InitDB(setting *domain.GlobalConfig) {\n\tsource := \"\"\n\tswitch setting.DBType {\n\tcase domain.SQLITE3:\n\t\tlogrus.Info(\"InitDB has done when new client, skip.\")\n\t\treturn\n\tcase domain.MYSQL:\n\t\tsource = fmt.Sprintf(\"%s:%s@tcp(%s:%s)/\",\n\t\t\tsetting.DBUser, setting.DBPassword, setting.DBHost, setting.DBPort)\n\tdefault:\n\t\tsource = fmt.Sprintf(\"%s:%s@tcp(%s:%s)/\",\n\t\t\tsetting.DBUser, setting.DBPassword, setting.DBHost, setting.DBPort)\n\t}\n\n\tdb, err := sql.Open(setting.DBType, source)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"connection to db error: %s\", err)\n\t}\n\tdefer db.Close()\n\n\tsql := \"CREATE DATABASE IF NOT EXISTS \" + setting.DBName + \";\"\n\t_, err = db.Exec(sql)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"create db %s error: %v\", setting.DBName, err)\n\t}\n}", "func InitDB(init bool) {\n\tif init {\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS kv (\n\t\t\tk TEXT PRIMARY KEY,\n\t\t\tv TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- 'data' or 'computed'\n\t\t\ttype TEXT,\n\t\t\tdata_type TEXT,\n\t\t\tmetadata TEXT DEFAULT '',\n\t\t\t-- only set if computed\n\t\t\thash TEXT,\n\t\t\tdone INTEGER DEFAULT 1\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS annotate_datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tdataset_id INTEGER REFERENCES datasets(id),\n\t\t\tinputs TEXT,\n\t\t\ttool TEXT,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_archs (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_components (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_nodes (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\top TEXT,\n\t\t\tparams TEXT,\n\t\t\tparents TEXT,\n\t\t\tworkspace TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_ds_refs (\n\t\t\tnode_id INTEGER,\n\t\t\tdataset_id INTEGER,\n\t\t\tUNIQUE(node_id, dataset_id)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS workspaces (\n\t\t\tname TEXT PRIMARY KEY\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS ws_datasets (\n\t\t\tdataset_id INTEGER,\n\t\t\tworkspace TEXT,\n\t\t\tUNIQUE(dataset_id, workspace)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS jobs (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- e.g. 'execnode'\n\t\t\ttype TEXT,\n\t\t\t-- how to process the job output and render the job\n\t\t\top TEXT,\n\t\t\tmetadata TEXT,\n\t\t\tstart_time TIMESTAMP,\n\t\t\tstate TEXT DEFAULT '',\n\t\t\tdone INTEGER DEFAULT 0,\n\t\t\terror TEXT DEFAULT ''\n\t\t)`)\n\n\t\t// add missing pytorch components\n\t\tcomponentPath := \"python/skyhook/pytorch/components/\"\n\t\tfiles, err := ioutil.ReadDir(componentPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(componentPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_components (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add missing pytorch archs\n\t\tarchPath := \"exec_ops/pytorch/archs/\"\n\t\tfiles, err = ioutil.ReadDir(archPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(archPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_archs (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add default workspace if it doesn't exist\n\t\tvar count int\n\t\tdb.QueryRow(\"SELECT COUNT(*) FROM workspaces WHERE name = ?\", \"default\").Scan(&count)\n\t\tif count == 0 {\n\t\t\tdb.Exec(\"INSERT INTO workspaces (name) VALUES (?)\", \"default\")\n\t\t}\n\t}\n\n\t// now run some database cleanup steps\n\n\t// mark jobs that are still running as error\n\tdb.Exec(\"UPDATE jobs SET error = 'terminated', done = 1 WHERE done = 0\")\n\n\t// delete temporary datasetsTODO\n}", "func InitDB(ctx *cli.Context) error {\n\tchainID := ctx.String(\"chainID\")\n\tregDb := ConnectToDB(ctx.String(\"dataport\"), ctx.String(\"passwd\"), ctx.Int(\"database\"))\n\tif Exists(regDb, \"chainConfig\") {\n\t\tresult := Get(regDb, \"chainConfig\")\n\t\tchainConfig := new(Identity)\n\t\tif err := json.Unmarshal([]byte(result), &chainConfig); err != nil {\n\t\t\tutils.Fatalf(\"Failed to initialise database: %v\", err)\n\t\t}\n\t\tif chainConfig.ID == chainID {\n\t\t\tfmt.Println(\"Database has been initialised by chainID\", chainID, \"sometimes before\")\n\t\t} else {\n\t\t\tutils.Fatalf(\"Database has been initialised by chainID \" + chainConfig.ID)\n\t\t}\n\t} else {\n\t\terr := Set(regDb, \"chainConfig\", &Identity{\n\t\t\tName: \"\",\n\t\t\tID: chainID,\n\t\t\tHashky: \"\",\n\t\t\tExtInfo: \"\",\n\t\t})\n\t\tif err != nil {\n\t\t\tutils.Fatalf(\"Failed to initialise database: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (_m *Database) Init() {\n\t_m.Called()\n}", "func TestDBInit() *Sqlite {\n\ttestdb := &Sqlite{}\n\ttestdb.OpenDB(\"./../gorm_test.db\")\n\ttestdb.setMaxIdleConns(3)\n\ttestdb.logMode(true)\n\treturn testdb\n}", "func (driver *SQLDriver) Initialize() error {\n\t// Parse the DSN and create a database object\n\tdb, err := sql.Open(env.Get(\"STORAGE_SQL_DRIVER\", \"sqlite3\"), env.Get(\"STORAGE_SQL_DSN\", \"./db\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ping the database\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Migrate the database\n\ttable := env.Get(\"STORAGE_SQL_TABLE\", \"pasty\")\n\t_, err = db.Exec(`\n\t\tCREATE TABLE IF NOT EXISTS ? (\n\t\t\tid varchar NOT NULL PRIMARY KEY,\n\t\t\tcontent varchar NOT NULL,\n\t\t\tsuggestedSyntaxType varchar NOT NULL,\n\t\t\tdeletionToken varchar NOT NULL,\n\t\t\tcreated bigint NOT NULL,\n\t\t\tautoDelete bool NOT NULL\n\t\t);\n `, table)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the database object and table name of the SQL driver\n\tdriver.database = db\n\tdriver.table = table\n\treturn nil\n}", "func (d *Database) Init() {\n\t//initialize Directory\n\td.Directory.Param = d.Param\n\td.Directory.Init()\n}", "func (c *ConsulDB) InitializeDatabase() error {\n\tif os.Getenv(\"DATABASE_IP\") == \"\" {\n\t\treturn pkgerrors.New(\"DATABASE_IP environment variable not set.\")\n\t}\n\tconfig := consulapi.DefaultConfig()\n\tconfig.Address = os.Getenv(\"DATABASE_IP\") + \":8500\"\n\n\tclient, err := consulapi.NewClient(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.consulClient = client\n\treturn nil\n}", "func InitDB() {\n\tvar err error\n\tvar dsn = os.Getenv(\"REVELAPP_DBUSER\") +\n\t\t\":\" + os.Getenv(\"REVELAPP_DBPASSWD\") +\n\t\t\"@\" + os.Getenv(\"REVELAPP_DBHOSTNAME\") +\n\t\t\"/\" + os.Getenv(\"REVELAPP_DBNAME\") +\n\t\t\"?parseTime=true&loc=Asia%2FTokyo\"\n\t// open db\n\tGdb, err = gorm.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tprintln(\"FATAL\", err)\n\t\tpanic(err)\n\t}\n\tautoMigrate()\n\t// unique index if need\n\t//Gdb.Model(&models.User{}).AddUniqueIndex(\"idx_user_name\", \"name\")\n}", "func (app *App) Initialize() error {\n\tapp.store = db.StoreInstance\n\n\tif err := app.store.CreateTable(db.Things{}); err != nil {\n\t\treturn err\n\t}\n\tlog.Debugf(\"table %s has been created successfully\", db.Things{})\n\n\tif count, err := app.store.ThingsCount(); err == nil && count == 0 {\n\t\tapp.store.ThingsBulkInsert(generateData())\n\t}\n\n\tlog.Info(\"application is ready to run\")\n\treturn nil\n}", "func initDB(dbName string) (dbType, error) {\n\th, err := sql.Open(dbDriver, dbName)\n\treturn dbType{handle: h}, err\n}", "func Initialize(conf *config.DatabaseConfig) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tif database != nil {\n\t\treturn fmt.Errorf(\"Database already initialized\")\n\t}\n\n\tlog.Log.Debug().Msg(\"initializing database connection\")\n\n\tdsn := fmt.Sprintf(\"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=%s\",\n\t\tconf.Host, conf.Username, conf.Password, conf.DatabaseName, conf.Port, conf.Timezone)\n\tdb, err := connect(dsn)\n\n\t// TODO: better handling to wait for DB up\n\tif err != nil && isConnectionError(err) && conf.ConnectRetries > 0 {\n\t\tdb, err = connectRetry(dsn, conf.ConnectRetries, conf.ConnectBackoff)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdatabase = db\n\tlog.Log.Debug().Msg(\"database initialized\")\n\n\treturn nil\n}", "func InitDB() {\n\tDBOnce.Do(func() {\n\t\tvar err error\n\t\tDBReader, err = gorm.Open(\"mysql\", Config.DB.MysqlServerRead)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Init DB error : %v\", err)\n\t\t\treturn\n\t\t}\n\t\tDBReader.LogMode(Config.DB.LogFlag)\n\t\tDBWriter, err = gorm.Open(\"mysql\", Config.DB.MysqlServerWrite)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Init DB error : %v\", err)\n\t\t\treturn\n\t\t}\n\t\tDBReader.LogMode(Config.DB.LogFlag)\n\t\tDBWriter.LogMode(Config.DB.LogFlag)\n\t})\n\n}", "func InitDatabase() *Database {\n\t// eg. \"postgres://postgres:postgres@localhost/postgres?sslmode=disable\"\n\t// TODO: enable SSL on DB\n\tconn, err := sql.Open(\"postgres\", os.Getenv(\"PG_CONNECTION_STRING\"))\n\tif err != nil {\n\t\tlog.Fatal(err) // kill server if we can't use DB on startup\n\t}\n\treturn &Database{\n\t\tconn: conn,\n\t}\n}", "func (uts *UnapprovedTransactions) InitDB() error {\n\treturn uts.DB.CreateTable(uts.getTableName(), \"VARBINARY(100)\", \"LONGBLOB\")\n}", "func InitDB(schema *memdb.DBSchema) (DB, error) {\n\tif schema == nil {\n\t\tpanic(\"cannot initialize database: missing schema\")\n\t}\n\n\tconn, err := memdb.NewMemDB(schema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn DB{conn}, nil\n}", "func Init() error {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\tif !isInitialized {\n\t\tvar e error\n\t\textDB = make(map[string]string)\n\n\t\tif !isInitialized {\n\t\t\te = loadDB()\n\t\t}\n\t\tisInitialized = true\n\t\treturn e\n\t}\n\treturn nil\n}", "func Dbinitialize() (bool, string) {\n\tif _, err := os.Stat(dblocation); err == nil {\n\t\treturn false, \"DB file already exists\"\n\t}\n\n\tos.Create(dblocation)\n\tdb, err := sql.Open(\"sqlite3\", dblocation)\n\tif err != nil {\n\t\treturn false, \"Could not create and open \" + dblocation\n\t}\n\n\tcreatestmt := `CREATE TABLE roles(\n\t\t\t\tid INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT ,\n\t\t\t\thost_regex VARCHAR(200) NOT NULL ,\n\t\t\t\trole VARCHAR(200) NOT NULL ,\n\t\t\t\tcomment VARCHAR(2000) NULL \n\t\t\t);`\n\n\t_, err = db.Exec(createstmt)\n\tif err != nil {\n\t\treturn false, \"Could not create table\"\n\t}\n\n\tinsertstmt := `INSERT INTO roles(host_regex, role, comment)\n\t\t\tVALUES(?,?,?)\n\t\t\t;`\n\tstmt, err := db.Prepare(insertstmt)\n\tif err != nil {\n\t\treturn false, \"Could not prepare SQL insert statement\"\n\t}\n\t_, err = stmt.Exec(\"(.*)\", \"default\", \"Default role matching everything\")\n\tif err != nil {\n\t\treturn false, \"Could not insert default role\"\n\t}\n\n\tdb.Close()\n\n\treturn true, \"OK\"\n}", "func initDB(filepath string) *sql.DB {\n\tdb, err := sql.Open(\"sqlite3\", filepath) // Open connection to DB\n\tcheckErr(err)\t\t// Here we check for any db errors then exit\n\n\t// If we don't get any errors but somehow still don't get a db connection\n\t// we exit as well\n\tif db == nil {\n\t\tpanic(\"db nil\")\n\t}\n\treturn db\n}", "func (s *Device) InitDB(ctx context.Context, req *device.InitDBRequest, rsp *device.InitDBResponse) error {\n\trsp.Result = new(device.Result)\n\tif len(req.DatabaseUrl) > 0 {\n\t\tmodel.UseingDB(req.DatabaseUrl)\n\t\trsp.Result.Id = \"InitDB\"\n\t\trsp.Result.Code = 200\n\t\trsp.Result.Detail = \"InitDB OK\"\n\t\trsp.Result.Status = \"ok\"\n\t\treturn nil\n\t}else {\n\t\trsp.Result.Id = \"InitDB\"\n\t\trsp.Result.Code = 500\n\t\trsp.Result.Detail = \"InitDB err\"\n\t\trsp.Result.Status = \"err\"\n\t\treturn errors.New(\"InitDB\", \"DatabaseUrl is null\", 404)\n\t}\n}", "func InitDb() *DBWrapper {\n\tdb, err := sql.Open(\"sqlite3\", \"./docs.db\")\n\tif err != nil {\n\t\tfmt.Println(\"Couldn't open DB\")\n\t\tlog.Fatal(err)\n\t}\n\tstatement, err := db.Prepare(\"CREATE TABLE IF NOT EXISTS docs (id INTEGER PRIMARY KEY, index_name VARCHAR(255), title TEXT, contents TEXT)\")\n\tstatement.Exec()\n\tif err != nil {\n\t\tfmt.Println(\"Couldn't create table\")\n\t\tlog.Fatal(err)\n\t}\n\treturn &DBWrapper{db}\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}" ]
[ "0.7580946", "0.75040793", "0.7301234", "0.7272172", "0.72496927", "0.7234495", "0.7216813", "0.7184065", "0.7155304", "0.71528757", "0.71380204", "0.713725", "0.7121874", "0.71132773", "0.7094605", "0.7083422", "0.7081965", "0.70812815", "0.7074524", "0.707253", "0.70643544", "0.7055816", "0.70420873", "0.7032974", "0.69992113", "0.69972456", "0.69809014", "0.69794613", "0.69778514", "0.6976139", "0.6971899", "0.69594586", "0.6945752", "0.6942087", "0.6939569", "0.693825", "0.6917103", "0.69149184", "0.69124085", "0.6905227", "0.69051033", "0.69003195", "0.6894077", "0.68924403", "0.6879043", "0.6872185", "0.686872", "0.6866076", "0.6850532", "0.6840582", "0.68384063", "0.6834892", "0.6834791", "0.6814918", "0.6813998", "0.68082327", "0.6794185", "0.6794147", "0.6792832", "0.6761342", "0.6759879", "0.6757195", "0.67393094", "0.6734898", "0.67322826", "0.671873", "0.6715968", "0.6711628", "0.67048126", "0.67020845", "0.6694843", "0.66933244", "0.66881585", "0.6686463", "0.66850895", "0.6684527", "0.66796565", "0.66659063", "0.66644365", "0.66607815", "0.6659744", "0.6658206", "0.6655025", "0.6653161", "0.6650746", "0.6649477", "0.6646105", "0.66438794", "0.6640522", "0.6625777", "0.662031", "0.6614806", "0.6614701", "0.6609458", "0.6604137", "0.6602116", "0.65908056", "0.65901744", "0.65881455", "0.6578883" ]
0.7391887
2
Connect2DB establishes the database connection
func Connect2DB() *gorm.DB { var connection, err = gorm.Open(dbDriver, dbConnectionOpts) if err != nil { mid.LogFatal(err) } dbConnection = connection mid.LogInfo("database connection established") return connection }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func connect2Db() *sql.DB {\n\tdb, err := sql.Open(\"sqlite3\", \"sq3_database.db\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif db == nil {\n\t\tpanic(\"db nil\")\n\t}\n\tCreateTable(db)\n\treturn db\n}", "func connectToDB() {\n\tconnectString := fmt.Sprintf(\"dbname=%s sslmode=disable\", viper.GetString(\"DB.Name\"))\n\tif viper.GetString(\"DB.User\") != \"\" {\n\t\tconnectString += fmt.Sprintf(\" user=%s\", viper.GetString(\"DB.User\"))\n\t}\n\tif viper.GetString(\"DB.Password\") != \"\" {\n\t\tconnectString += fmt.Sprintf(\" password=%s\", viper.GetString(\"DB.Password\"))\n\t}\n\tif viper.GetString(\"DB.Host\") != \"\" {\n\t\tconnectString += fmt.Sprintf(\" host=%s\", viper.GetString(\"DB.Host\"))\n\t}\n\tif viper.GetString(\"DB.Port\") != \"5432\" {\n\t\tconnectString += fmt.Sprintf(\" port=%s\", viper.GetString(\"DB.Port\"))\n\t}\n\tmodels.DBConnect(viper.GetString(\"DB.Driver\"), connectString)\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 dbConnect() (*sql.DB, error) {\n\tdb, err := sql.Open(\"mysql\", getDataSource())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// use the library_api database\n\t_, err = db.Exec(`USE library_api`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func ConnectDB() {\n\ttcpString := \"@tcp(\" + Config.mysql + \")\"\n\tdb, err := sql.Open(\"mysql\", \"root:\"+tcpString+\"/\"+Config.dbName)\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tConnection.Db = db\n\n\terr = Connection.Db.Ping()\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func (o *Repo) connectDB() {\n\tvar once sync.Once\n\tif o.db1 == nil {\n\t\tonce.Do(func() {\n\t\t\tvar err error\n\t\t\to.db1, err = sql.Open(\"sqlite3\", \"e:/repo/repo.db\")\n\t\t\tMustOK(err)\n\t\t})\n\t}\n}", "func ConnectDB() *sql.DB {\n\thost := viper.GetString(\"db.host\")\n\tport := viper.GetString(\"db.port\")\n\tuser := viper.GetString(\"db.user\")\n\tpass := viper.GetString(\"db.pass\")\n\tdsn := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", user, pass, host, port, user)\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error connecting to db: %s\\n\", err.Error())\n\t}\n\treturn db\n}", "func initDBConnection(dbUser, dbPass, dbURL, dbNAME string) (err error) {\n\t/*\n\t\tVariables defined here\n\t*/\n\tvar user, pass, url, name string\n\n\t/*\n\t\tverify that all variables exists\n\t*/\n\tif len(dbUser) == 0 || len(dbURL) == 0 || len(dbPass) == 0 || len(dbNAME) == 0 {\n\t\terr = errors.New(\"Missing DB Credentails. Please Check\")\n\t\treturn\n\t}\n\n\t/*\n\t\tverify the varibles and set values after remove spaces\n\t*/\n\tif len(dbUser) > 0 && len(dbPass) > 0 && len(dbURL) > 0 && len(dbNAME) > 0 {\n\t\tuser = strings.TrimSpace(dbUser)\n\t\tpass = strings.TrimSpace(dbPass)\n\t\turl = strings.TrimSpace(dbURL)\n\t\tname = strings.TrimSpace(dbNAME)\n\t}\n\n\t/*\n\t\tPrepares the connection string\n\t*/\n\tconnString := fmt.Sprintf(\"postgres://%s:%s@%s/%s?sslmode=require\", user, pass, url, name)\n\tfmt.Printf(\"connecting to database: %s\\n\", url)\n\n\t/*\n\t\tconnects the database with the provided values, in case of any issue error will be raise\n\t*/\n\tdb, err = sql.Open(\"postgres\", connString)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Database refused connection: %s\", err.Error())\n\t\treturn\n\t}\n\n\treturn\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 Connect(ctx context.Context, dbName string) (*sql.DB, error) {\n\tdbusername := os.Getenv(\"MARIA_USERNAME\")\n\tdbpassword := os.Getenv(\"MARIA_PASSWORD\")\n\n\tdb, err := sql.Open(\"mysql\", dbusername+\":\"+dbpassword+\"@tcp(127.0.0.1:3306)/\"+dbName)\n\tif err != nil {\n\t\tlogger.Error.Println(logger.GetCallInfo(), err.Error())\n\t\treturn nil, err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tlogger.Error.Println(\"Error:\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect2(user, pwd, host, mirrorHost, database string) (*Conn, error) {\n\treturn connectWithCredentials(&credentials{user: user, pwd: pwd, host: host, database: database, mirrorHost: mirrorHost})\n}", "func InitDatabase() *sql.DB {\n\tlog.Println(\"connecting database.\")\n\n\tquery := url.Values{}\n\tquery.Add(\"database\", \"Company\")\n\n\tu := &url.URL{\n\t\tScheme: \"sqlserver\",\n\t\tUser: url.UserPassword(\"sa\", \"1234\"),\n\t\tHost: fmt.Sprintf(\"%s:%d\", \"localhost\", 1433),\n\t\t// Path: instance, // if connecting to an instance instead of a port\n\t\tRawQuery: query.Encode(),\n\t}\n\n\tlog.Println(u.String())\n\n\tcondb, err := sql.Open(\"sqlserver\", u.String())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"test ping database.\")\n\tif err = condb.Ping(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn condb\n}", "func InitDB(driverName, dataSourceName string) (*sql.DB) {\n conn, err := sql.Open(driverName, dataSourceName)\n \n log.Println(\"open main db conn\")\n \n if err != nil {\n log.Fatal(\"DB is not connected\")\n }\n \n if err = conn.Ping(); err != nil {\n log.Fatal(\"DB is not responded\")\n }\n \n return conn\n}", "func connect_db() {\n\tdb, err = sql.Open(\"mysql\", \"root:jadir123@tcp(127.0.0.1:3306)/go_db\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func connectToDatabase(app *app) error {\n\tlog.Info().Msg(\"connection to database...\")\n\n\tdb, err := sqlx.Connect(\"postgres\", app.config.Database)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info().Msg(\"successfully connected!\")\n\tapp.repo = repo.New(db)\n\n\treturn nil\n}", "func connect() {\n\tconn, err := http.NewConnection(http.ConnectionConfig{\n\t\tEndpoints: []string{hlp.Conf.DB.URL},\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create HTTP connection: %v\", err)\n\t}\n\n\tclient, err := driver.NewClient(driver.ClientConfig{\n\t\tConnection: conn,\n\t\tAuthentication: driver.BasicAuthentication(\n\t\t\thlp.Conf.DB.User,\n\t\t\thlp.Conf.DB.Pass,\n\t\t),\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create new client: %v\", err)\n\t}\n\n\tctx := context.Background()\n\tdb, err := client.Database(ctx, \"cardo_dev\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to open database: %v\", err)\n\t}\n\n\tDatabase = db\n}", "func connectDB() error {\n\t// define login variables\n\thost := config.Get(\"postgresql\", \"host\")\n\tport := config.Get(\"postgresql\", \"port\")\n\tssl := config.Get(\"postgresql\", \"ssl\")\n\tdatabase := config.Get(\"postgresql\", \"database\")\n\tusername := config.Get(\"postgresql\", \"username\")\n\tpassword := config.Get(\"postgresql\", \"password\")\n\n\t// connect and return error\n\treturn db.Connect(host, port, ssl, database, username, password)\n}", "func ConnectDB(wrappers ...DriverWrapper) (*sql.DB, error) {\n\tif debug := viper.GetBool(\"database.debug\"); debug {\n\t\twrappers = append(wrappers, WithInstrumentedSQL())\n\t}\n\n\tdb, err := OpenConnection(ConnectionConfig{\n\t\tDriverWrappers: wrappers,\n\t\tUser: viper.GetString(\"database.user\"),\n\t\tPassword: viper.GetString(\"database.password\"),\n\t\tHost: viper.GetString(\"database.host\"),\n\t\tName: viper.GetString(\"database.name\"),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxConn := viper.GetInt(\"database.max_open_conn\")\n\tdb.SetMaxOpenConns(maxConn)\n\tdb.SetMaxIdleConns(maxConn)\n\n\tretries, period := viper.GetInt(\"database.connection_retries\"), viper.GetDuration(\"database.retry_period\")\n\tfor i := 0; i < retries; i++ {\n\t\terr = db.Ping()\n\t\tif err == nil {\n\t\t\tlogrus.Debug(\"Connected to the database\")\n\t\t\treturn db, nil\n\t\t}\n\t\ttime.Sleep(period)\n\t\tlogrus.WithError(err).Debug(\"DB connection error. Retrying...\")\n\t}\n\treturn nil, fmt.Errorf(\"failed to open DB connection\")\n}", "func Connect() *sql.DB {\n\tdb, err := sql.Open(\"mysql\", \"root:@tcp(localhost:3306)/task_database\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Connected to the database\")\n\t// CreateDatabase(db) // uncomment to create database and reset table\n\tcon = db\n\treturn db\n}", "func connectToDatabase() error {\n\tvar databaseConnectionErr error\n\tconnection, databaseConnectionErr = sqlx.Connect(\"mysql\", config.GetConfig().DbConnectionString)\n\tif databaseConnectionErr != nil {\n\t\tfmt.Println(\"connectToDatabase\")\n\t\tfmt.Println(databaseConnectionErr.Error())\n\t\treturn databaseConnectionErr\n\t}\n\n\treturn nil\n}", "func DbConnect() {\n\tpostgresHost, _ := os.LookupEnv(\"CYCLING_BLOG_DB_SERVICE_SERVICE_HOST\")\n\tpostgresPort := 5432\n\tpostgresUser, _ := os.LookupEnv(\"POSTGRES_USER\")\n\tpostgresPassword, _ := os.LookupEnv(\"PGPASSWORD\")\n\tpostgresName, _ := os.LookupEnv(\"POSTGRES_DB\")\n\n\tenv := ENV{Host: postgresHost, Port: postgresPort, User: postgresUser, Password: postgresPassword, Dbname: postgresName}\n\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", env.Host, env.Port, env.User, env.Password, env.Dbname)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tlog.Panic(\"DbConnect: unable to connect to database\", err)\n\t}\n\tDB = db\n\tfmt.Println(\"Successfully connected!\")\n}", "func ConnectDB() {\n\tvar err error\n\tp := config.Config(\"DB_PORT\")\n\tport, err := strconv.ParseUint(p, 10, 32)\n\n\tif err != nil {\n\t\tpanic(\"failed to parse database port\")\n\t}\n\n\tdsn := fmt.Sprintf(\n\t\t\"host=db port=%d user=%s password=%s dbname=%s sslmode=disable\",\n\t\tport,\n\t\tconfig.Config(\"DB_USER\"),\n\t\tconfig.Config(\"DB_PASSWORD\"),\n\t\tconfig.Config(\"DB_NAME\"),\n\t)\n\tDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tfmt.Println(\"Connection Opened to Database\")\n\tDB.AutoMigrate(&model.Product{}, &model.User{})\n\tfmt.Println(\"Database Migrated\")\n}", "func OpenDB(o ServerOptions) error {\n\tvar err = (error)(nil)\n\n\tif o.DBTlsKeyName != \"\" && o.DBTlsServerHostName != \"\" && o.DBTlsServerCAPem != \"\" && o.DBTlsClientCertPem != \"\" && o.DBTlsClientKeyPem != \"\" {\n\t\tserverCAPem, err := base64.StdEncoding.DecodeString(o.DBTlsServerCAPem)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to decode server ca PEM value\")\n\t\t}\n\t\tclientCertPem, err := base64.StdEncoding.DecodeString(o.DBTlsClientCertPem)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to decode client certificate PEM value\")\n\t\t}\n\t\tclientKeyPem, err := base64.StdEncoding.DecodeString(o.DBTlsClientKeyPem)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to decode client key PEM value\")\n\t\t}\n\n\t\trootCertPool := x509.NewCertPool()\n\t\tif ok := rootCertPool.AppendCertsFromPEM(serverCAPem); !ok {\n\t\t\treturn fmt.Errorf(\"Failed to append server CA PEM\")\n\t\t}\n\n\t\tclientCert := make([]tls.Certificate, 0, 1)\n\t\tcerts, err := tls.X509KeyPair(clientCertPem, clientKeyPem)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclientCert = append(clientCert, certs)\n\t\terr = mysql.RegisterTLSConfig(o.DBTlsKeyName, &tls.Config{\n\t\t\tRootCAs: rootCertPool,\n\t\t\tCertificates: clientCert,\n\t\t\tServerName: o.DBTlsServerHostName,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdb, err = sql.Open(o.DBDriverName, o.DBDataSourceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize memory cache\n\toriginCache, err = lru.NewARC(10)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func connectDB(dsn string) (dbh *sql.DB, err error) {\n\tdbh, err = sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Set really low limits, this application is only meant to do quick serialized SQL queries\n\tdbh.SetMaxOpenConns(1)\n\tdbh.SetConnMaxLifetime(time.Second)\n\n\treturn\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 connectToDatabase(conf base.Configuration) *sql.DB {\n\tdataSourceName := fmt.Sprintf(\"host=%s port=%s dbname=%s sslmode=%s user=%s password=%s\",\n\t\tconf.DbHost, conf.DbPort, conf.DbName, conf.DbSSLMode, conf.DbUser, conf.DbPassword)\n\tdb, err := sql.Open(\"postgres\", dataSourceName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn db\n}", "func (dbi *DBInstance) ConnectDB() error {\n\tsess, err := sql.Open(dbi.DBType, dbi.DBURL)\n\tif err != nil {\n\t\treturn errors.New(\"can not connect to database: \" + err.Error())\n\t}\n\tdbi.SQLSession = sess\n\tdbi.SQLSession.SetMaxOpenConns(1) // make sure there is only one session open with database at a time\n\treturn nil\n}", "func (dbi *DBInstance) ConnectDB() error {\n\tsess, err := sql.Open(dbi.DBTYPE, dbi.DBURL)\n\tif err != nil {\n\t\treturn errors.New(\"can not connect to database: \" + err.Error())\n\t}\n\tdbi.SQLSession = sess\n\tdbi.SQLSession.SetMaxOpenConns(1) // make sure there is only one session open with database at a time\n\treturn nil\n}", "func (d *DBGenerator) connect(ctx context.Context) error {\n\tif d.Conn == nil {\n\t\tconnStr := fmt.Sprintf(\"vertica://%s:%s@%s:%d/%s?tlsmode=%s\",\n\t\t\td.Opts.User, d.Opts.Password, d.Opts.Host, d.Opts.Port, d.Opts.DBName, d.Opts.TLSMode,\n\t\t)\n\t\tconn, err := sql.Open(\"vertica\", connStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.Conn = conn\n\t}\n\n\treturn d.Conn.PingContext(ctx)\n}", "func (dbi *dbInfo) connect() (*sql.DB, error) {\n\t// Set MySQL driver parameters\n\tdbParameters := \"charset=\" + dbi.charset\n\n\t// Append cleartext and tls parameters if TLS is specified\n\tif dbi.tls == true {\n\t\tdbParameters = dbParameters + \"&allowCleartextPasswords=1&tls=skip-verify\"\n\t}\n\n\tdb, err := sql.Open(\"mysql\", dbi.user+\":\"+dbi.pass+\"@tcp(\"+dbi.host+\":\"+dbi.port+\")/?\"+dbParameters)\n\tcheckErr(err)\n\n\t// Ping database to verify credentials\n\terr = db.Ping()\n\n\treturn db, err\n}", "func DBConnect() (err error) {\n\turi := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%s/archive?sslmode=disable\",\n\t\tos.Getenv(\"POSTGRES_USER\"),\n\t\tos.Getenv(\"POSTGRES_PASSWORD\"),\n\t\tos.Getenv(\"POSTGRES_HOST\"),\n\t\tos.Getenv(\"POSTGRES_PORT\"),\n\t)\n\tdb, err = sql.Open(\"postgres\", uri)\n\treturn err\n}", "func initializeMysqlConn() {\n\tdbConn, err := sql.Open(\"mysql\", \"admin:admin@tcp(y2search_mysql:3306)/y2search_db?collation=utf8mb4_unicode_ci\")\n\tdb = *dbConn\n\tif err != nil {\n\t\tlog.Panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic\n\t}\n\n\t// Open doesn't open a connection. Validate DSN data:\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Panic(err.Error()) // proper error handling instead of panic in your app\n\t}\n}", "func (client *DatabaseClient) Connect() error {\n var err error\n database, err = gorm.Open(\"mysql\", client.buildDatabaseDSN())\n if err != nil {\n return errors.DatabaseConnectionError.ToError(err)\n }\n client.autoMigrate()\n return nil\n}", "func (r *Resolver) ConnectDB(ctx context.Context) {\n\tif r.db != nil {\n\t\tfmt.Printf(\"ConnectDB connection already open\\n\")\n\t\treturn\n\t}\n\n\tfmt.Printf(\"ConnectDB connecting...\\n\")\n\tconn, err := pgx.Connect(ctx, os.Getenv(\"DATABASE_URL\"))\n\t// defer conn.Close(ctx) // can't do this, keep the connection open then?\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tr.db = conn\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 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}", "func ConnectDatabase() *sql.DB {\n\tinstance, err := sql.Open(\"mysql\", \"root:root@(127.0.0.1:3306)/movingmanager\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn instance\n}", "func connect(DSN string, timeout time.Duration) *sql.DB {\n\tticker := time.NewTicker(1 * time.Second)\n\ttimer := time.After(timeout)\n\tconn, _ := sql.Open(\"mysql\", DSN)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\terr := conn.Ping()\n\t\t\tif err == nil {\n\t\t\t\treturn conn\n\t\t\t}\n\t\tcase <-timer:\n\t\t\tlog.Fatalf(\"Timeout trying To connect To %s after %d seconds. Forgot To run `make db_up`?\", DSN, timeout/1e9)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func dbConnect(dbConnParams string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", dbConnParams) // this opens a connection and adds to the pool\n\terrMsgHandler(fmt.Sprintf(\"Failed to connect to the database\"), err)\n\n\t// connect to the database\n\terr = db.Ping() // this validates that the opened connection \"db\" is actually working\n\terrMsgHandler(fmt.Sprintf(\"The database connection is no longer open\"), err)\n\n\tfmt.Println(\"Successfully connected to the database\")\n\treturn db\n}", "func Connect(path string) (*sql.DB, error){\n\t//TODO: Commit feature\n\tlog.Println(\"INFO: Connecting to the DB\")\n\tdb, err := sql.Open(\"mysql\", path)\n\tlog.Println(\"INFO: Connected to the DB\")\n\treturn db, err\n}", "func Connect() (*sql.DB, error) {\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", host, port, user, password, dbname)\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// defer db.Close()\n\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\tfmt.Println(\"Connection to database was successful\")\n\treturn db, err\n}", "func Connect() *DB {\n\n\tif db2 == nil {\n\n\t\t// Singleton the bank has to close every call,\n\t\t// save, update, get etc ..\n\t\t//\n\t\t// Testing and verifying if there is a directory\n\t\t// and file of our bucket, if it does not exist\n\t\t// it creates the directory and the file so that\n\t\t// we can manipulate all our bucket.\n\t\t//\n\t\t// Remember that boltdb with the open function also creates.\n\t\tif err := DataBaseTest(PathDb); err != nil {\n\n\t\t\tlog.Fatal(\"Error Test database\", err)\n\t\t}\n\n\t\t// Here is the object responsible for\n\t\t// allowing calls to the methods, such as Get, Save, etc.\n\t\tdbbolt, err = bolt.Open(PathDb, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\n\t\tif err != nil {\n\n\t\t\tlog.Fatal(\"connect error: \", err)\n\t\t}\n\n\t\t// We create a new reference\n\t\t// just to facilitate\n\t\t// understanding and syntax\n\t\tdb2 = &DB{dbbolt}\n\t}\n\n\treturn db2\n}", "func Connect(ctx context.Context, host string, port int, dbName, user, password string) (*DB, error) {\n\tconfig := mysql.Config{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", host, port),\n\t\tNet: \"tcp\",\n\t\tUser: user,\n\t\tPasswd: password,\n\t\tDBName: dbName,\n\t\tMultiStatements: true,\n\t}\n\tctxLogger := logger.FromContext(ctx)\n\tctx = logger.NewContext(ctx, ctxLogger.(logger.WithLogger).With(\"host\", host, \"dbName\", dbName, \"user\", user, \"port\", port))\n\n\tdb := &DB{\n\t\tCtx: ctx,\n\t\tLogger: logger.FromContext(ctx),\n\t}\n\tdb.Logger.Info(\"dsn\", config.FormatDSN(), \"msg\", \"Connecting\")\n\tif myLogger, ok := db.Logger.(logger.PrintLogger); ok {\n\t\tif myWithLogger, okWith := db.Logger.(logger.WithLogger); okWith {\n\t\t\tmyLogger = myWithLogger.With(\"package\", \"mysql\").(logger.PrintLogger)\n\t\t}\n\t\tmysql.SetLogger(myLogger)\n\t}\n\tcon, err := sql.Open(\"mysql\", config.FormatDSN())\n\tif err != nil {\n\t\treturn db, err\n\t}\n\terr = con.PingContext(ctx)\n\tif err != nil {\n\t\treturn db, err\n\t}\n\tdb.Database = goqu.New(\"mysql\", con)\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 connectToDatabase() {\n\tvar err error\n\tdb, err = sql.Open(\"mysql\", \"root:root@(172.18.0.2)/cpjudge_webserver_development\")\n\tif err != nil {\n\t\tlog.Println(\"Error while trying to open\", err.Error())\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(\"Error while trying to ping\", err.Error())\n\t}\n}", "func (s *bookingServiceServer) connect(ctx context.Context) (*sql.Conn, error) {\n\tc, err := s.db.Conn(ctx)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to connect to database-> \"+err.Error())\n\t}\n\treturn c, nil\n}", "func ConnectToDatabase() {\n\tDb, err = gorm.Open(\"mysql\", os.Getenv(\"DATABASE_USERNAME\")+\":\"+os.Getenv(\"DATABASE_PASSWORD\")+\"@tcp(\"+os.Getenv(\"DATABASE_HOST\")+\":\"+\n\t\tos.Getenv(\"DATABASE_PORT\")+\")/\"+os.Getenv(\"DATABASE_NAME\")+\"?charset=utf8&parseTime=True&loc=Local&character_set_server=utf8\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tDb.LogMode(true)\n}", "func ConnectDB() *sql.DB {\n\tdb, err := sql.Open(\"mysql\", \"username:password@/dbname\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn db\n}", "func (c Connector) Connect() (db *sql.DB) {\n\tif c.db != nil {\n\t\tlevel.Info(c.log).Log(\"msg\", \"returning mysql\")\n\t\treturn db\n\t}\n\tlevel.Info(c.log).Log(\"msg\", \"connecting to mysql\")\n\tlevel.Info(c.log).Log(\"msg\", \"returning connection\")\n\t_ = c.config.dbdriver\n\tdbUser := c.config.dbUser\n\tdbHost := c.config.dbHost\n\tdbPass := c.config.dbPassword\n\tdbName := c.config.dbDatabase\n\tdbPort := c.config.dbPort\n\n\tdb, err := sql.Open(\"mysql\", dbUser+\":\"+dbPass+\"@(\"+dbHost+\":\"+dbPort+\")/\"+dbName)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tc.db = db\n\tc.db.SetMaxIdleConns(10)\n\tc.db.SetMaxOpenConns(10)\n\tc.db.SetConnMaxLifetime(time.Duration(360))\n\treturn c.db\n\n}", "func Connect() (*sql.DB, error) {\n\tdsn := buildDSN()\n\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutils.Logger.Info(\"Connecting to database...\", map[string]interface{}{\"DSN\": dsn})\n\tvar dbErr error\n\tfor i := 1; i <= 3; i++ {\n\t\tdbErr = db.Ping()\n\t\tif dbErr != nil {\n\t\t\tutils.Logger.Info(fmt.Sprintf(\"Attempt #%d failed, will retry in 10 seconds\", i), map[string]interface{}{\"Error\": dbErr})\n\t\t\tif i < 3 {\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tbreak\n\t}\n\n\tif dbErr != nil {\n\t\treturn nil, errors.New(\"can't connect to database after 3 attempts\")\n\t}\n\n\treturn db, nil\n}", "func DB(connector db.Connector, dbConns int) error {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif db.Conn != nil {\n\t\tif err := db.Conn.Ping(); err == nil {\n\t\t\t// Already connected.\n\t\t\treturn nil\n\t\t}\n\t}\n\tconn, err := connector.Connect(dbConns)\n\tdb.Conn = conn\n\tif err != nil {\n\t\treturn errors.New(\"setup: could not establish a database connection: \" + err.Error())\n\t}\n\tif err := db.Conn.Ping(); err != nil {\n\t\treturn errors.New(\"setup: could not establish a database connection: \" + err.Error())\n\t}\n\treturn PrepareAll()\n}", "func (app *App) ConnectDb() error {\n\tdb, err := sql.Open(app.Config.Database.Driver, app.Config.Database.Access)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn err\n\t}\n\tapp.Db = db\n\tfor _, statement := range sqlCreate {\n\t\t_, err = db.Exec(statement)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Connect() (*gorm.DB, error) {\n\tdb, err := gorm.Open(\"mysql\", viper.GetString(\"mysql.username\")+\":\"+viper.GetString(\"mysql.password\")+\"@(\"+viper.GetString(\"mysql.hostname\")+\":\"+viper.GetString(\"mysql.port\")+\")/\"+viper.GetString(\"mysql.database\")+\"?charset=utf8&parseTime=True&loc=Local\")\n\treturn db, err\n}", "func GormConnectDB() *gorm.DB {\n\n\thost := viper.GetString(\"db.host\")\n\tport := viper.GetString(\"db.port\")\n\tuser := viper.GetString(\"db.user\")\n\tpass := viper.GetString(\"db.pass\")\n\tdsn := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True\", user, pass, host, port, user)\n\tdb, err := gorm.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error connecting gorm to db: %s\\n\", err.Error())\n\t}\n\treturn db\n\n}", "func Connect(user string, password string, host string, port int, schema string, dsn string) (*sql.DB, error) {\n\tvar err error\n\tvar connString bytes.Buffer\n\n\tpara := map[string]interface{}{}\n\tpara[\"User\"] = user\n\tpara[\"Pass\"] = password\n\tpara[\"Host\"] = host\n\tpara[\"Port\"] = port\n\tpara[\"Schema\"] = schema\n\n\ttmpl, err := template.New(\"dbconn\").Option(\"missingkey=zero\").Parse(dsn)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"tmpl parse\")\n\t\treturn nil, err\n\t}\n\n\terr = tmpl.Execute(&connString, para)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"tmpl execute\")\n\t\treturn nil, err\n\t}\n\n\tlog.Debug().Str(\"dsn\", connString.String()).Msg(\"connect to db\")\n\tdb, err := sql.Open(\"mysql\", connString.String())\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"mysql connect\")\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect() (db *sql.DB, err error) {\n\treturn sql.Open(DBDriver, DBSource+DBParams)\n}", "func Connect() (*sql.DB, error) {\n\treturn db.Connect(*dbURI)\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 (*ConnectDB) InitDB() framework.Mssql {\n\n\tvar user = framework.SA{\n\t\tUsername: \"sdxonestop\",\n\t\tPassword: \"baiyun+=1992\",\n\t}\n\n\tdb := framework.Mssql{\n\t\tDataSource: \"BAIYUN-MOBL1\",\n\t\tDatabase: \"SdxOneStopDB\",\n\t\t// windwos: true 为windows身份验证,false 必须设置sa账号和密码\n\t\tWindows: true,\n\t\tSa: user,\n\t}\n\t// 连接数据库\n\terr := db.Open()\n\tif err != nil {\n\t\tfmt.Println(\"sql open:\", err)\n\t\treturn db\n\t} else {\n\t\tfmt.Println(\"Succeed to open DB...\")\n\t}\n\t//defer db.Close()\n\n\treturn db\n}", "func dbConnect() *sql.DB {\n\tdb, err := sql.Open(\"postgres\",\n\t\tfmt.Sprintf(\"user=%s password=%s dbname=%s host=%s port=%s sslmode=%s\",\n\t\t\tPG_USER,\n\t\t\tPG_PASSWORD,\n\t\t\tPG_DB,\n\t\t\tPG_HOST,\n\t\t\tPG_PORT,\n\t\t\tPG_SSL,\n\t\t))\n\tif err != nil {\n\t\tlog.Fatalf(\"ERROR: Error connecting to Postgres => %s\", err.Error())\n\t}\n\tlog.Printf(\"PQ Database connection made to %s\", PG_DB)\n\treturn db\n}", "func ConnectToDB() *mongo.Client {\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t\treturn client\n\t}\n\n\terr = client.Ping(context.TODO(), nil)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t\treturn client\n\t}\n\tlog.Println(\"DB Connection stablished succesfully\")\n\n\treturn client\n}", "func (dbh *DBHandler) Connect() {\n\tvar err error\n\tdbh.Connection, err = sql.Open(dbh.DriverName, dbh.DBPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (a *AppContext) ConnectToDB() error {\n\t/*\n\t * We will enable db only if the enable db env is true\n\t * We will get the db config\n\t * Connect to it\n\t * If no error then set the database connection\n\t */\n\tif os.Getenv(EnabledDB) != \"true\" {\n\t\treturn nil\n\t}\n\tc := NewDbConfig()\n\td, err := c.Connect()\n\tif err == nil {\n\t\ta.Db = d\n\t}\n\treturn err\n}", "func ConnectDb(conf *setting.Config) error {\n\tvar (\n\t\terr error\n\t\tdbType, dbName, user, pwd, host string\n\t)\n\n\tdbType = conf.Database.Type\n\tdbName = conf.Database.Name\n\tuser = conf.Database.User\n\tpwd = conf.Database.Password\n\thost = conf.Database.Host\n\n\tdb, err = gorm.Open(dbType, fmt.Sprintf(\"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local\",\n\t\tuser,\n\t\tpwd,\n\t\thost,\n\t\tdbName))\n\t// db.LogMode(true)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tdb.SingularTable(false)\n\tdb.DB().SetMaxIdleConns(10)\n\tdb.DB().SetMaxOpenConns(100)\n\treturn nil\n}", "func Connect() error {\n\tcfg := Config{}\n\tif err := env.Parse(&cfg); err != nil {\n\t\treturn fmt.Errorf(\"%+v\", err)\n\t}\n\tdsn := cfg.DbUser + \":\" + cfg.DbPassword + \"@\" + cfg.DbHost + \"/\" + cfg.\n\t\tDbName + \"?parseTime=true&charset=utf8\"\n\n\tdb, err := sql.Open(\"mysql\", dsn)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar dbErr error\n\tfor i := 1; i <= 8; i++ {\n\t\tdbErr = db.Ping()\n\t\tif dbErr != nil {\n\t\t\tif i < 8 {\n\t\t\t\tlog.Printf(\"db connection failed, %d retry : %v\", i, dbErr)\n\t\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tbreak\n\t}\n\n\tif dbErr != nil {\n\t\treturn errors.New(\"can't connect to database after 3 attempts\")\n\t}\n\n\tDbConn = db\n\n\treturn nil\n}", "func ConnectDB() (*gorm.DB, error) {\n\tconfig := config.GetConfig()\n\n\tdbURI := fmt.Sprintf(\"%s:%s@tcp(%s)/%s?charset=%s&parseTime=True\",\n\t\tconfig.Database.Username,\n\t\tconfig.Database.Password,\n\t\tconfig.Database.Host,\n\t\tconfig.Database.Name,\n\t\tconfig.Database.Charset)\n\n\tdb, err := gorm.Open(config.Database.Dialect, dbURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func Connect() *sql.DB {\n\n\tvar connStr string\n\n\tif os.Getenv(\"mode\") == \"dev\" {\n\t\tconnStr = \"root\" + \"@tcp(\" + \"127.0.0.1:3306\" + \")/\" + \"analasia\"\n\t} else {\n\t\tconnStr = os.Getenv(\"DATABASE_USER\") + \":\" + os.Getenv(\"DATABASE_PASSWORD\") + \"@tcp(\" + os.Getenv(\"DATABASE_HOST\") + \")/\" + os.Getenv(\"DATABASE_NAME\")\n\t}\n\tconn, err := sql.Open(\"mysql\", connStr)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn conn\n\n}", "func InitDB() *sql.DB {\n\n\tlog.Println(\"attempting connections\")\n\n\tvar err error\n\t\n\t// Open a SQL connection to the docker container hosting the database server\n\t// Assign the connection to the \"DB\" variable\n\t// Look at how it's done in the other microservices!\n\t// \"YOUR CODE HERE\"\n\t\n\tif err != nil {\n\t\tlog.Println(\"couldnt connect\")\n\t\tpanic(err.Error())\n\t}\n\n\terr = DB.Ping()\n\tif err != nil {\n\t\tlog.Println(\"couldnt ping\")\n\t\tpanic(err.Error())\n\t}\n\n\treturn DB\n}", "func (self *CSql) Connect(driverName string, dial string) (*sql.DB, error) {\r\n\tvar err error = nil\r\n\tself.db, err = sql.Open(driverName, dial)\r\n\tself.db.SetMaxOpenConns(20)\r\n\tself.db.SetMaxIdleConns(10)\r\n\tself.db.SetConnMaxLifetime(60 * time.Second)\r\n\treturn self.db, err\r\n}", "func ConnectDB() error {\n\tcfg := config.DB()\n\tdbSource := fmt.Sprintf(\n\t\t\"host=%s port=%d user=%s dbname=%s password=%s sslmode=disable\",\n\t\tcfg.Host,\n\t\tcfg.Port,\n\t\tcfg.Username,\n\t\tcfg.Name,\n\t\tcfg.Password,\n\t)\n\n\tc, err := gorm.Open(\"postgres\", dbSource)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tlog.Fatal(\"database connection error\")\n\t\treturn err\n\t}\n\tfmt.Println(\"successful db connection\")\n\tConn = PostgresClient{\n\t\tDB: c,\n\t}\n\t// need to pass the references of model\n\tConn.DB.AutoMigrate()\n\treturn nil\n}", "func Connect(configuration *config.Database) (*gorm.DB, error) {\n\tdsn := \"tcp://\" + configuration.Host + \":\" + configuration.Port + \"?database=\" + configuration.DB + \"&read_timeout=10\"\n\tdb, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func (p *ProviderDAO) Connect() {\n\tsession, err := mgo.Dial(p.Server)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdb = session.DB(p.Database)\n}", "func Connect() {\n\n\t//check for already open connection, close it\n\tif db != nil {\n\t\tdb.Close()\n\t}\n\n\t//if NOT using sqlx:\n\tvar err error\n\tdb, err = sql.Open(\"mysql\", \"cs361_connorsa:0400@tcp(classmysql.engr.oregonstate.edu:3306)/cs361_connorsa\")\n\t//if using sqlx:\n\t//db, err = sqlx.Open(\"mysql\", \"cs361_connorsa:0400@tcp(classmysql.engr.oregonstate.edu:3306)/cs361_connorsa\")\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//check database connection, bail out if bad\n\tif err := db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgo periodicPing()\n\n}", "func Connect(dbCfg config.DBConfig) (*sql.DB, error) {\n\t// Assemble database connection string\n\tsqlConnStr := fmt.Sprintf(\"host=%s port=%d dbname=%s user=%s \"+\n\t\t\"sslmode=disable\", dbCfg.DBHost, dbCfg.DBPort,\n\t\tdbCfg.DBName, dbCfg.DBUsername)\n\n\tif len(dbCfg.DBPassword) > 0 {\n\t\tsqlConnStr += fmt.Sprintf(\" password=%s\", dbCfg.DBPassword)\n\t}\n\n\t// Connect to database\n\tdb, err := sql.Open(\"postgres\", sqlConnStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening connection to database: %s\",\n\t\t\terr.Error())\n\t}\n\n\t// Check connection\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error checking connection: %s\", err.Error())\n\t}\n\n\treturn db, nil\n}", "func Connect(driver, db string) *sql.DB {\n\tDB, err := sql.Open(driver, db)\n\tcheckErr(err)\n\treturn DB\n}", "func connectDb() *sql.DB {\n\tconnStr := \"user=postgres dbname=postgres sslmode=disable port=5000\"\n\tdb, err := sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func ConnectDB() (db *gorm.DB, err error) {\n\tconfig := GetConfig()\n\tdbURI := fmt.Sprintf(\"host=%s port=%s user=%s dbname=%s password=%s sslmode=disable\",\n\t\tconfig.DB.Host,\n\t\tconfig.DB.Port,\n\t\tconfig.DB.Username,\n\t\tconfig.DB.Name,\n\t\tconfig.DB.Password)\n\tdb, err = gorm.Open(config.DB.Dialect, dbURI)\n\tif os.Getenv(\"ENV\") == \"prod\" {\n\t\tdb.LogMode(false)\n\t}\n\n\treturn db, err\n}", "func ConnectDB() (*DB, error) {\n\t// ?parseTime=true\n\t// https://stackoverflow.com/questions/45040319/unsupported-scan-storing-driver-value-type-uint8-into-type-time-time\n\tdb, err := sql.Open(\"mysql\", \"api:keepgrowth$@/book_report?parseTime=true\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// https://github.com/go-sql-driver/mysql/#important-settings\n\tdb.SetConnMaxLifetime(time.Minute * 3)\n\tdb.SetMaxOpenConns(10)\n\tdb.SetConnMaxIdleTime(10)\n\n\terrPing := db.Ping()\n\tif errPing != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tqb := goqu.New(\"mysql\", db)\n\n\treturn &DB{qb}, nil\n}", "func ConnectDB() *sql.DB {\n\n\tvar err error\n\n\t// Connect to the Postgres Database\n\tdb, err = sql.Open(\"postgres\", \"user=rodrigovalente password=password host=localhost port=5432 dbname=api_jwt sslmode=disable\")\n\tlogFatal(err)\n\n\treturn db\n\n}", "func (application *Application) ConnectToDatabase() {\n\t// Initialize the database\n\tdbmap, err := models.InitDB(application.Configuration.Database.ConnectionString)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to initialize the database: %v\", err)\n\t\tpanic(err)\n\t}\n\n\t// Store our session\n\tapplication.DBSession = dbmap\n}", "func (s *serviceMigration) ConnectDB(url string) error {\n\tdb, err := sql.Open(\"postgres\", url)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.DB = db\n\treturn migrations(db)\n}", "func (db *DB) Connect() error {\n\tvar dbInfo string = fmt.Sprintf(\"user=%s password=%s dbname=%s sslmode=disable\", db.user, db.password, db.name)\n\td, err := sql.Open(\"postgres\", dbInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb.db = d\n\treturn nil\n}", "func (s *cinemaServiceServer) connect(ctx context.Context) (*sql.Conn, error) {\n\tc, err := s.db.Conn(ctx)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to connect to database-> \"+err.Error())\n\t}\n\treturn c, nil\n}", "func connectDB(name, user, password string) (*sql.DB, error) {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(\"user=%s dbname=%s password=%s sslmode=disable\", user, name, password))\n\treturn db, err\n}", "func CreateConnection(requestID string) (*sql.DB, error) {\n\t// 요청된 requestID에 대한 반출 조회\n\toptionfilePath, err := checkFileExistance(requestID, \"query.json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// 데이터베이스 연결 정보 및 반출 처리 옵션 읽어오기\n\toptions, err := getOptionFile(optionfilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// 데이터베이스 연결 정보 추출\n\tconnInfo := options[\"conn\"].(map[string]interface{})\n\n\t// DSN 생성\n\tdsn := \"hdb://\" + connInfo[\"user\"].(string) + \":\" + connInfo[\"pwd\"].(string) + \"@\" + connInfo[\"host\"].(string) + \":\" + connInfo[\"port\"].(string)\n\t// 커넥터 생성\n\tconnector, err := driver.NewDSNConnector(dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// 커넥터 옵션 설정\n\tconnector.SetFetchSize(512)\n\t// 데이터베이스 객체 생성\n\tdb := sql.OpenDB(connector)\n\t// 연결 테스트\n\terr = db.Ping()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Return\n\treturn db, nil\n}", "func ConnectDB() error {\n\tvar err error\n\tSession, err = mgo.Dial(MongoURI)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDB = Session.DB(DBName)\n\treturn nil\n}", "func ConnectToDatabase(ctx context.Context, params *DatabaseConnectionParams, log *zap.Logger, models ...interface{}) (*core_database.DatabaseConn, error) {\n\tvar dbConn *core_database.DatabaseConn\n\tconnectionString := configureConnectionString(ctx, params.Host, params.User, params.Password, params.DatabaseName, params.Port)\n\n\tif dbConn = core_database.NewDatabaseConn(connectionString, \"postgres\"); dbConn == nil {\n\t\treturn nil, errors.New(\"failed to connect to merchant component database\")\n\t}\n\n\tif err := pingDatabase(ctx, dbConn); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := migrateSchemas(ctx, dbConn, log, models...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dbConn, nil\n}", "func ConnectMe() {\n\tgodotenv.Load()\n\tconnString := fmt.Sprintf(\"server=%s;user id=%s;password=%s;port=%s;database=%s;\",\n\t\tGoDotEnvVariable(\"Server\"), GoDotEnvVariable(\"user\"), GoDotEnvVariable(\"Password\"), GoDotEnvVariable(\"Port\"), GoDotEnvVariable(\"Database\"))\n\tdb, err = sql.Open(\"sqlserver\", connString)\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating connection pool: \", err.Error())\n\t} else {\n\t\tfmt.Println(\"no eerror\")\n\t}\n\tctx := context.Background()\n\terr = db.PingContext(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tfmt.Println(\"no eerror 2\")\n\t}\n\t//return db, err\n}", "func connectDatabase(connectionURL string) *sql.DB {\n\tdb, err := sql.Open(\"postgres\", connectionURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn db\n}", "func CreateDBConnection(dbName string) {\n\tvar err error\n\tDB, err = Client.EnsureDB(dbName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func DBConnection() (*sql.DB, error) {\n\n\tconfig := configuration.LoadConfiguration()\n\tdb, err := sql.Open(\"mysql\", \"\"+config.MySQLUser+\":\"+config.MySQLPass+\"@tcp(\"+config.MySQLHost+\")/\"+config.MySQLDb)\n\n\treturn db, err\n}", "func InitDatabase(driverName, dataSourceName string, numRetries int, sleepDuration time.Duration) *sql.DB {\n\tvar err error\n\tvar db *sql.DB\n\tfor i := 0; i < numRetries; i++ {\n\t\tdb, err = sql.Open(driverName, dataSourceName)\n\t\tif err == nil {\n\t\t\tlog.Println(\"DB connection initialized...\")\n\t\t\tbreak\n\t\t}\n\t\tlog.Println(\"DB connection failed to initialize... Sleeping...\")\n\t\ttime.Sleep(sleepDuration)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tlog.Printf(\"Successfully connected to DB: %s\\n\", dataSourceName)\n\t}\n\treturn db\n}", "func ConnectDB() error {\n\tsugar.Debug(\"ConnectDB\")\n\tvar err error\n\tDB, err = gorm.Open(\"sqlite3\", FileDatabasePath)\n\tif err == nil {\n\t\tif viper.GetBool(\"verbose\") {\n\t\t\tDB.LogMode(true)\n\t\t}\n\t\tsugar.Debug(\"Starting migration\")\n\t\tDB.AutoMigrate(&File{})\n\t\terr = DB.Error\n\t}\n\treturn err\n}", "func Connect(_db *sql.DB) {\n\tdb = _db\n}", "func Connect(driver, DSN string, timeout time.Duration) (*sql.DB, error) {\n\tticker := time.NewTicker(1 * time.Second)\n\tdefer ticker.Stop()\n\n\ttimeoutExceeded := time.After(timeout)\n\tfor {\n\t\tselect {\n\t\tcase <-timeoutExceeded:\n\t\t\treturn nil, fmt.Errorf(\"db connection failed after %s timeout\", timeout)\n\n\t\tcase <-ticker.C:\n\t\t\tdb, err := sql.Open(driver, DSN)\n\t\t\tif err == nil {\n\t\t\t\treturn db, nil\n\t\t\t}\n\t\t\tlog.Println(errors.Wrapf(err, \"failed to connect to db %s\", DSN))\n\t\t}\n\t}\n}", "func ConnectDB() (*gorm.DB, error) {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tfmt.Printf(\"[DB Load Env] %s\\n\", err)\n\t\tfmt.Printf(\"Attempting to load online environment...\\n\")\n\t}\n\n\thost := os.Getenv(\"PG_HOST\")\n\tusername := os.Getenv(\"PG_USER\")\n\tpass := os.Getenv(\"PG_PASSWORD\")\n\tdbname := os.Getenv(\"PG_DBNAME\")\n\tport, _ := strconv.Atoi(os.Getenv(\"PG_PORT\"))\n\tdbInfo := fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable\", host, port, username, pass, dbname)\n\n\tdb, err := gorm.Open(\"postgres\", dbInfo)\n\tif err != nil {\n\t\tfmt.Printf(\"[DB ConnectDB] %s\", err)\n\t\treturn nil, err\n\t}\n\tfmt.Printf(\"Established connection successfully to DB %s\\n\", dbname)\n\treturn db, nil\n}", "func initDB(options Options) (*mgo.Session, error) {\n\tdialInfo := &mgo.DialInfo{\n\t\tAddrs: strings.Split(options.DBHost, \",\"),\n\t\tDatabase: options.DBName,\n\t\tUsername: options.DBUser,\n\t\tPassword: options.DBPassword,\n\t\tDialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {\n\t\t\treturn tls.Dial(\"tcp\", addr.String(), &tls.Config{InsecureSkipVerify: true})\n\t\t},\n\t\tReplicaSetName: \"rs0\",\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tif !options.SSL {\n\t\tdialInfo.ReplicaSetName = \"\"\n\t\tdialInfo.DialServer = nil\n\t}\n\t// connect to the database\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn session, err\n}", "func (ar *ActiveRecord) Connect(dbtype string, url string) (err error) {\n\tif ar.DB != nil {\n\t\tar.Close()\n\t}\n\n\tif ar.DB, err = sql.Open(dbtype, url); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn nil\n\t}\n}", "func dbSQLConnect(dbType string) {\n\t// Errors\n\tvar err error\n\n\t// Getting an instance of dbConfig\n\tdbConfig := config.DataBase{}\n\n\t// Getting the DSN\n\tdsn := dbConfig.GetDSN()\n\n\t// Defining the default message\n\tmsg := fmt.Sprintf(\"Could not connect with the database [%v]\", strings.ToTitle(dbType))\n\n\tswitch {\n\tcase dbType == \"mysql\":\n\t\t// Open the connection\n\t\tDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\t\tutils.PanicMSG(err, msg)\n\tcase dbType == \"postgresql\":\n\t\t// Open the connection\n\t\tDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\t\tutils.PanicMSG(err, msg)\n\tdefault:\n\t\tlog.Fatalln(\"Database does not have support Yet! Supported Databases: [MySQL and PostgreSQL\")\n\t}\n}", "func (db *DB) Connect() error {\n\tvar dbConnection *gorm.DB\n\tvar err error\n\tif db.dbType == \"sqlite3\" {\n\t\tdbConnection, err = gorm.Open(sqlite.Open(db.dbConnectionPath), &gorm.Config{})\n\t} else if db.dbType == \"postgres\" {\n\t\tdbConnection, err = gorm.Open(postgres.Open(db.dbConnectionPath), &gorm.Config{})\n\t} else {\n\t\terr = errors.New(\"invalid dbtype\")\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize database, got error: %v\", err)\n\t}\n\tdbConnection.AutoMigrate(&Match{})\n\t//dbConnection.LogMode(true)\n\tdb.DB = dbConnection\n\treturn err\n}" ]
[ "0.757264", "0.6822824", "0.6756877", "0.67195827", "0.6654789", "0.6621728", "0.6575559", "0.65740955", "0.6547422", "0.6546234", "0.6520126", "0.6500164", "0.65001625", "0.6497988", "0.6494403", "0.6479153", "0.6477857", "0.6471021", "0.6462317", "0.6452527", "0.64446527", "0.6436814", "0.64363134", "0.6436289", "0.6421907", "0.6412287", "0.6407761", "0.6403968", "0.63788986", "0.6373125", "0.63689476", "0.6361529", "0.63493496", "0.633835", "0.6334853", "0.6328676", "0.63113207", "0.6304185", "0.6303777", "0.63004774", "0.62952", "0.6281666", "0.6281565", "0.62764746", "0.6275277", "0.6274506", "0.6267022", "0.6262622", "0.62586355", "0.6255583", "0.6249718", "0.62477237", "0.62453955", "0.62442374", "0.6225458", "0.6225115", "0.62218255", "0.62178296", "0.6214612", "0.62138766", "0.62124634", "0.6210549", "0.62050056", "0.6201409", "0.6197962", "0.61953396", "0.61943686", "0.6194204", "0.6182154", "0.61769056", "0.61698323", "0.6168597", "0.61651963", "0.61641073", "0.6163385", "0.6156759", "0.6155393", "0.61542046", "0.615295", "0.61467546", "0.6143991", "0.6142153", "0.6141139", "0.6130486", "0.6123871", "0.61188835", "0.61182106", "0.6117509", "0.61107314", "0.610868", "0.6107221", "0.6100349", "0.609586", "0.6093794", "0.6091777", "0.6087863", "0.60871845", "0.6085501", "0.6082185", "0.6081679" ]
0.7893105
0
GetDbConnection returns the shared database connection pointer
func GetDbConnection() *gorm.DB { return dbConnection }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetConnection() *gorm.DB {\n\treturn db\n}", "func GetConnection() *sqlx.DB {\n\ts := rand.NewSource(time.Now().Unix())\n\tr := rand.New(s)\n\n\treturn connectionPool[r.Intn(len(connectionPool))].db\n}", "func GetConnection() *sqlx.DB {\n\tif connection == nil {\n\t\tconnectToDatabase()\n\t}\n\treturn connection\n}", "func (extDb *Database) GetConnection() (*sql.DB, error) {\n\tif db := extDb.getDb(); db != nil {\n\t\treturn db, nil\n\t}\n\treturn nil, ErrNotInitialized\n}", "func GetDbConnection(driver string, connectionString string) *sqlx.DB {\n\tdb, err := sqlx.Connect(driver, connectionString)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to establish connection: %v\\n\", err)\n\t}\n\treturn db\n}", "func GetDBConn() *pg.DB {\n\tif dbConn != nil {\n\t\treturn dbConn\n\t}\n\tlog.Println(\"database connection not active yet\")\n\treturn nil\n}", "func (impl *Server) GetConnection() *gorm.DB {\n\treturn base.GetConnection()\n}", "func (p Driver) GetConnection() *sql.DB {\n\tdb, err := sql.Open(\"postgres\", p.Connection)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tp.db = db\n\n\tfmt.Println(\"Opening postgresql connection.....\")\n\treturn db\n}", "func GetConn() *sql.DB {\n\treturn dbConn()\n}", "func GetConnection() *gorm.DB {\n\tif gormInstance == nil {\n\t\tconn, err := InitDBMysql()\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Error Mysql Connection: %s\", err))\n\t\t}\n\t\tgormInstance = conn\n\t}\n\treturn gormInstance\n}", "func (c *container) DbConnection() *gorm.DB {\n\tvar err error\n\tif nil == c.dbConnection {\n\t\tc.dbConnection, err = db.CreateConnection(c.Config().GetDatabase())\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"Could not connect to DB: %v\", err)\n\t\t}\n\t}\n\treturn c.dbConnection\n}", "func getDatabaseConnection(c context.Context) (*sql.DB, error) {\n\t// Update the database pointer if the database settings have changed. This operation is costly, but should be rare.\n\t// Done here to ensure that a connection established with an outdated connection string is closed as soon as possible.\n\tsettings, err := settings.Get(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconnectionString := fmt.Sprintf(\"%s:%s@cloudsql(%s)/%s\", settings.Username, settings.Password, settings.Server, settings.Database)\n\n\t// If the connection string matches what we expect, the current pointer is correct so just return it.\n\tdbLock.RLock()\n\tif connectionString == dbConnectionString {\n\t\tdefer dbLock.RUnlock()\n\t\treturn db, nil\n\t}\n\tdbLock.RUnlock()\n\n\t// The connection string doesn't match so the db pointer needs to be created or updated.\n\tdbLock.Lock()\n\tdefer dbLock.Unlock()\n\n\t// Releasing the read lock may have allowed another concurrent request to grab the write lock first so it's\n\t// possible we no longer need to do anything. Check again while holding the write lock.\n\tif connectionString == dbConnectionString {\n\t\treturn db, nil\n\t}\n\n\tif db != nil {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlogging.Warningf(c, \"Failed to close the previous database connection: %s\", err.Error())\n\t\t}\n\t}\n\tdb, err = sql.Open(\"mysql\", connectionString)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open a new database connection: %s\", err.Error())\n\t}\n\n\t// AppEngine limit.\n\tdb.SetMaxOpenConns(12)\n\tdbConnectionString = connectionString\n\treturn db, nil\n}", "func (bcm *BasicConnectionManager) GetConnection(connStr string) (*sql.DB, error) {\n\tif len(connStr) == 0 {\n\t\treturn nil, fmt.Errorf(\"the connStr parameter cannot be empty\")\n\t}\n\n\t// Check if a connection already exists before lock it\n\tconn, ok := bcm.connectionPool[connStr]\n\tif ok {\n\t\t// Reuse it if already exists\n\t\treturn conn, nil\n\t}\n\n\t// Now try to lock it for double check\n\tbcm.mutex.Lock()\n\tdefer bcm.mutex.Unlock() // Release the lock after function returns\n\n\t// Check again if the connection already exists in the pool\n\tconn, ok = bcm.connectionPool[connStr]\n\tif ok {\n\t\t// Reuse it if already exists\n\t\treturn conn, nil\n\t}\n\n\t// Create a new one\n\tnewConn, err := bcm.openConnection(connStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add the new connection to the pool\n\tbcm.connectionPool[connStr] = newConn\n\treturn newConn, nil\n}", "func GetDB() *pgx.Conn {\n\treturn conn\n}", "func (db *mongoDataBase) GetConnection() interface{} {\n\treturn db.databaseConnection\n}", "func (c *Conn) GetConnection() *sql.DB {\n\treturn c.conn\n}", "func GetDbConnection() *sql.DB {\n\tdb, err := sql.Open(\"sqlite3\", databaseFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn db\n}", "func GetConnection() MongoConnection {\n\tif instance.Db == nil {\n\t\tlog.Fatal(\"Database connection has not been established\")\n\t}\n\n\treturn instance\n}", "func (c *ConnectionPool) GetConnection() (*mgo.Database, error) {\n\tsession, err := mgo.Dial(\"mongodb\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session.DB(\"testdatabase\"), nil\n}", "func GetConnection() (database *sql.DB) {\n\tdatabaseDriver := \"mysql\"\n\tdatabaseUser := \"newuser\"\n\tdatabasePass := \"newuser\"\n\tdatabaseName := \"crm\"\n\tdatabase, err := sql.Open(databaseDriver, databaseUser+\":\"+databasePass+\"@/\"+databaseName)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn database\n}", "func (impl *ServerServerGroup) GetConnection() *gorm.DB {\n\treturn base.GetConnection()\n}", "func GetConnection() (database *sql.DB) {\n\tdatabaseDriver := \"mysql\"\n\tdatabaseUser := \"newuser\"\n\tdatabasePass := \"newuser\"\n\tdatabaseName := \"crm\"\n\tdatabase, error := sql.Open(databaseDriver, databaseUser+\":\"+databasePass+\"@/\"+databaseName)\n\t// stops the execution if there is any error in connecting\n\tif error != nil {\n\t\tpanic(error.Error())\n\t}\n\treturn database\n}", "func (pgdal *PGDAL) GetConnection() (err error) {\n\terr = pgdal.GetConnectionString()\n\tif err != nil {\n\t\treturn\n\t}\n\tpgdal.pgdb, err = gorm.Open(postgres.Open(pgdal.url), &gorm.Config{})\n\treturn\n}", "func GetDBConnection(cfg *DBConfig) (conn ITransactionalDB, err error) {\n\tDSN := getDSN(cfg)\n\tdriver := cfg.Driver\n\n\tswitch driver {\n\tcase \"mysql\":\n\t\tconn, err = NewMySQLConn(DSN, cfg)\n\tcase \"postgres\":\n\t\tconn, err = NewPostgreSQLConn(\"postgres://\"+DSN, cfg)\n\tdefault:\n\t\terr = fmt.Errorf(\"Unsupported driver: %s\", driver)\n\t}\n\treturn\n}", "func GetDBConnection(dbFlag DbType) (*persistencemgr.ConnPool, *errors.Error) {\n\tswitch dbFlag {\n\tcase InMemory:\n\t\tpool, err := persistencemgr.GetDBConnection(persistencemgr.InMemory)\n\t\treturn pool, err\n\tcase OnDisk:\n\t\tpool, err := persistencemgr.GetDBConnection(persistencemgr.OnDisk)\n\t\treturn pool, err\n\tdefault:\n\t\treturn nil, errors.PackError(errors.UndefinedErrorType, \"error invalid db type selection\")\n\t}\n}", "func GetDBConnection() (localdb *sqlx.DB, err error) {\n\tif db == nil {\n\t\tdb, err = AbreConexaoComBancoDeDadosSQL()\n\t\tif err != nil {\n\t\t\tlog.Println(\"[GetDBConnection] Erro na conexao: \", err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Println(\"[GetDBConnection] Erro no ping na conexao: \", err.Error())\n\t\treturn\n\t}\n\tlocaldb = db\n\treturn\n}", "func GetConnectionDB() *sql.DB {\n\t// dsn := \"postgres://postgres:[email protected]:5432/go_api_rest?sslmode=disable\"\n\tdsn := \"postgres://vzmemnlocgrknl:ff0e6b953b864cbb9e23f46dfe47ef2e86ca389fae4a3cddbe30ba91725ed058@ec2-52-202-185-87.compute-1.amazonaws.com:5432/ddk2ombgpk8bdq\"\n\tdb, err := sql.Open(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Error al conectar BD: %s\", err))\n\t}\n\treturn db\n}", "func GetConnection(dsn string) (*sql.DB, error) {\n\tif dsn == \"\" {\n\t\tdsn = GetDSN()\n\t}\n\treturn sql.Open(\"goracle\", dsn)\n}", "func GetDB() *gorm.DB {\n\tif connection == nil {\n\t\tco, err := gorm.Open(\"postgres\", Dbs)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"Failed to open database connection\")\n\t\t}\n\n\t\tco.DB().SetMaxIdleConns(defaultMaxConnections / 5)\n\t\tco.DB().SetMaxOpenConns(defaultMaxConnections)\n\t\tconnection = co\n\t}\n\n\treturn connection\n}", "func GetDbConnection() (*sql.DB, error) {\n\tserverName := fmt.Sprintf(\"localhost:%s\", os.Getenv(dbPort))\n\tconnectionString := fmt.Sprintf(\"%s:%s@tcp(%s)/%s\",\n\t\tos.Getenv(dbUser),\n\t\tos.Getenv(dbPass),\n\t\tserverName, os.Getenv(dbName))\n\tlog.Printf(\"Trying to connect to database with %s\", connectionString)\n\treturn sql.Open(\"mysql\", connectionString)\n}", "func GetConnection() *gorm.DB {\n\tif connection != nil {\n\t\treturn connection.Session(&gorm.Session{\n\t\t\tSkipHooks: false,\n\t\t})\n\t}\n\tconnection = setup()\n\treturn connection.Session(&gorm.Session{\n\t\tSkipHooks: false,\n\t})\n}", "func (impl *IPv4Pool) GetConnection() *gorm.DB {\n\treturn base.GetConnection()\n}", "func GetDatabaseConnection() *sql.DB {\n\tdatabaseIP, err := config.GetString(\"database/host\", \"mariadb\")\n\tdatabasePort, err := config.GetInt(\"database/port\", 3306)\n\tdatabasePassword, err := config.GetString(\"database/password\", \"\")\n\tdatabaseType, err := config.GetString(\"database/type\", \"mysql\")\n\tdatabaseName, err := config.GetString(\"database/name\", \"kubeam\")\n\tdatabaseUser, err := config.GetString(\"database/user\", \"root\")\n\n\tdatabaseConn := fmt.Sprintf(\"%s:%s@tcp(%s:%d)/%s\", databaseUser,\n\t\tdatabasePassword, databaseIP, databasePort, databaseName)\n\n\tdb, err := sql.Open(databaseType, databaseConn)\n\tErrorHandler(err)\n\n\terr = db.Ping()\n\tErrorHandler(err)\n\n\treturn db\n}", "func GetDb() *sql.DB {\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn db\n}", "func GetDbInstance() *gorm.DB {\n\tdb, err := gorm.Open(configuration.DataBaseType, parseConnectParam())\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn db\n}", "func GetConnectionPoolAppDB() (*sql.DB, error) {\n\n\tif dbAppConf.InitSuccess == false {\n\t\tinitAppDB()\n\t}\n\n\treturn dbAppConf.Conn, dbAppConf.Err\n}", "func (t TenantConnectionInformation) GetConnection() (*gorm.DB, error) {\n\n\tif len(strings.TrimSpace(t.ConnectionString)) == 0 {\n\t\treturn nil, errors.New(\"Connection string was not found or was empty..\")\n\t}\n\n\tdb, err := gorm.Open(\"postgres\", t.ConnectionString)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func (r *Postgres) GetConn() (*PostgresConn, error) {\n\tp := PostgresConn{}\n\tvar err error\n\n\tp.Conn, err = r.pool.Acquire(context.Background())\n\n\treturn &p, err\n}", "func GetConnection() SQLConnector {\n\n\tconn, err := GetConnectionWithKey(DefaultConnectionName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn conn\n}", "func GetConnectionPoolLogDB() (*sql.DB, error) {\n\n\tif dbLogConf.InitSuccess == false {\n\t\tinitLogDB()\n\t}\n\n\treturn dbLogConf.Conn, dbLogConf.Err\n}", "func (fmd *FakeMysqlDaemon) GetDbConnection(dbconfigName dbconfigs.DbConfigName) (dbconnpool.PoolConnection, error) {\n\tswitch dbconfigName {\n\tcase dbconfigs.DbaConfigName:\n\t\tif fmd.DbaConnectionFactory == nil {\n\t\t\treturn nil, fmt.Errorf(\"no DbaConnectionFactory set in this FakeMysqlDaemon\")\n\t\t}\n\t\treturn fmd.DbaConnectionFactory()\n\tcase dbconfigs.AppConfigName:\n\t\tif fmd.DbAppConnectionFactory == nil {\n\t\t\treturn nil, fmt.Errorf(\"no DbAppConnectionFactory set in this FakeMysqlDaemon\")\n\t\t}\n\t\treturn fmd.DbAppConnectionFactory()\n\t}\n\treturn nil, fmt.Errorf(\"unknown dbconfigName: %v\", dbconfigName)\n}", "func (postgres *PostgreSQLReconciler) GetDatabaseConn(secretName string) (*Connect, error) {\n\tsecret, err := postgres.GetSecret(secretName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn := &Connect{\n\t\tHost: string(secret[\"host\"]),\n\t\tPort: string(secret[\"port\"]),\n\t\tPassword: string(secret[\"password\"]),\n\t\tUsername: string(secret[\"username\"]),\n\t\tDatabase: string(secret[\"database\"]),\n\t}\n\n\treturn conn, nil\n}", "func GetDB() *gorm.DB {\n\treturn singleton\n}", "func GetDB(c *gin.Context) *mgo.Database {\n\treturn c.MustGet(dbKey).(*mgo.Database)\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func GetConn() (conn redis.Conn) {\n\trepo = Get()\n\tconn = repo.Get()\n\tconn.Do(\"SELECT\", config.RerestConf.RedisDatabaseData)\n\treturn\n}", "func GetConnection() *gorm.DB {\n\tmsqlInfo := \"root:Kamath@123@tcp(127.0.0.1:3306)/golang_crud?charset=utf8mb4&parseTime=True&loc=Local\"\n\t// msqlInfo := fmt.Sprintf(\"host=%s port=%d user=%s \"+\n\t// \t\"password=%s dbname=%s sslmode=disable\",\n\t// \thost, port, user, password, dbname)\n\n\tdb, err := gorm.Open(\"mysql\", msqlInfo)\n\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tlog.Println(\"DB Connection established...\")\n\n\treturn db\n\n}", "func getDBConnection() *sql.DB {\n // Open database\n db, err := sql.Open(\"sqlite3\", \"db.sqlite3\")\n if err != nil {\n // TODO\n panic(fmt.Sprintf(\"%#v\", err))\n }\n return db\n}", "func GetDBconn() *sql.DB {\n\tdbName := \"userdb\"\n\tfmt.Println(\"conn info:\", dbName)\n\tdb, err := sql.Open(\"mysql\", \"root:manish1234@tcp(localhost:3306)/userdb\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// defer db.Close()\n\n\treturn db\n}", "func GetInstance() *gorm.DB {\n\tonce.Do(func() {\n\t\t// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details\n\t\tuser := viper.GetString(\"database.user\")\n\t\tpassword := viper.GetString(\"database.password\")\n\t\thost := viper.GetString(\"database.host\")\n\t\tport := viper.GetString(\"database.port\")\n\t\tdbname := viper.GetString(\"database.dbname\")\n\n\t\tdsn := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", user, password, host, port, dbname)\n\t\tdb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\t\tdba = db\n\t\tif err != nil {\n\t\t\tlog.Panic().Msgf(\"Error connecting to the database at %s:%s/%s\", host, port, dbname)\n\t\t}\n\t\tsqlDB, err := dba.DB()\n\t\tif err != nil {\n\t\t\tlog.Panic().Msgf(\"Error getting GORM DB definition\")\n\t\t}\n\t\tsqlDB.SetMaxIdleConns(10)\n\t\tsqlDB.SetMaxOpenConns(100)\n\n\t\tlog.Info().Msgf(\"Successfully established connection to %s:%s/%s\", host, port, dbname)\n\t})\n\treturn dba\n}", "func getDb(t *testing.T) *sql.DB {\n\t// need shared cache to allow different connections to use same in-memory db\n\tdb, err := Open(\"file::memory:?cache=shared\")\n\tif err != nil {\n\t\tt.Errorf(\"Could not open database\")\n\t}\n\treturn db\n}", "func (sql *SqlConnection) GetDB() *gorm.DB {\n\treturn sql.Db\n}", "func GetDB() *gorm.DB {\n\tif conn == nil {\n\t\tConnect()\n\t} else if err := conn.DB().Ping(); err != nil {\n\t\tconn = nil\n\t}\n\tif conn == nil {\n\t\tsig := make(chan os.Signal, 1)\n\t\tsignal.Notify(sig, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL) //nolint\n\t\tvar i int\n\treconnect:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-sig:\n\t\t\t\tbreak reconnect\n\t\t\tcase <-time.After(tryPause * time.Second):\n\t\t\t\tConnect()\n\t\t\t\ti++\n\t\t\t\tif conn != nil {\n\t\t\t\t\tbreak reconnect\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif conn == nil {\n\t\t\tlog.Panicln(fmt.Sprintf(\"Connection failed after %d tries\", i))\n\t\t}\n\t}\n\treturn conn\n}", "func (p PgxWrapper) GetConn(ctx context.Context) (*pgx.Conn, error) {\n\tconn, err := p.pool.Acquire(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not acquire connection: %w\", err)\n\t}\n\treturn conn.Conn(), nil\n}", "func Connection() *gorm.DB {\n\tonce.Do(connect)\n\n\treturn db\n}", "func GetConnToControlDB() (conn redis.Conn) {\n\trepo = Get()\n\tconn = repo.Get()\n\tconn.Do(\"SELECT\", config.RerestConf.RedisDatabaseControl)\n\treturn\n}", "func GetConnection() *gredis.Client {\n\tif connection == nil {\n\t\tvar err error\n\t\tconnection, err = newConnection()\n\t\tif err != nil {\n\t\t\t//fatal\n\t\t}\n\t}\n\treturn connection\n}", "func getConn() *gorm.DB {\n\tdsn := \"host=localhost user=hello password=hello dbname=hello port=15432 sslmode=disable TimeZone=Asia/Shanghai\"\n\tdb, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\n\treturn db\n\t// sqlDB, err := db.DB()\n\n\t// // SetMaxIdleConns 设置空闲连接池中连接的最大数量\n\t// sqlDB.SetMaxIdleConns(10)\n\t// // SetMaxOpenConns 设置打开数据库连接的最大数量。\n\t// sqlDB.SetMaxOpenConns(100)\n\n\t// // SetConnMaxLifetime 设置了连接可复用的最大时间。\n\t// sqlDB.SetConnMaxLifetime(time.Hour)\n}", "func GetDB(logger logrus.FieldLogger, config *viper.Viper, dbOrNil pginterfaces.DB, dbCtxOrNil pginterfaces.CtxWrapper) (*pg.Client, error) {\n\tl := logger.WithFields(logrus.Fields{\n\t\t\"operation\": \"configureDatabase\",\n\t\t\"host\": config.GetString(\"extensions.pg.host\"),\n\t\t\"port\": config.GetString(\"extensions.pg.port\"),\n\t})\n\tl.Debug(\"connecting to DB...\")\n\tclient, err := pg.NewClient(\"extensions.pg\", config, dbOrNil, nil, dbCtxOrNil)\n\tif err != nil {\n\t\tl.WithError(err).Error(\"connection to database failed\")\n\t\treturn nil, err\n\t}\n\tif dbOrNil != nil {\n\t\tclient.DB = dbOrNil\n\t}\n\tl.Info(\"successfully connected to database\")\n\treturn client, nil\n}", "func GetDatabaseConnection(env string) string {\n\tswitch env {\n\tcase \"development\":\n\t\treturn developmentDBConString\n\tcase \"test\":\n\t\treturn testDBString\n\tdefault:\n\t\treturn developmentDBConString\n\t}\n}", "func (this *dataStore) GetConnPool() *ConnPool {\r\n\treturn this.connPool\r\n}", "func GetDBConnection(databaseURL string) (*sql.DB, error) {\n var db *sql.DB\n appEnv, err := cfenv.Current()\n if err != nil {\n db, err = sql.Open(\"mysql\", databaseURL+\"?parseTime=true\")\n if err != nil {\n return nil, err\n }\n } else {\n mysqlEnv, err := appEnv.Services.WithName(\"hero-mysql\")\n if err != nil {\n return nil, err\n }\n mysqlPort := \"\"\n if val, ok := mysqlEnv.Credentials[\"port\"].(string); ok {\n mysqlPort = val\n } else {\n mysqlPort = strconv.FormatFloat(mysqlEnv.Credentials[\"port\"].(float64), 'f', -1, 64)\n }\n db, err = sql.Open(\"mysql\", mysqlEnv.Credentials[\"username\"].(string)+\":\"+mysqlEnv.Credentials[\"password\"].(string)+\"@tcp(\"+mysqlEnv.Credentials[\"hostname\"].(string)+\":\"+mysqlPort+\")/\"+mysqlEnv.Credentials[\"name\"].(string)+\"?parseTime=true\")\n if err != nil {\n return nil, err\n }\n }\n\n err = db.Ping()\n if err != nil {\n db.Close()\n return nil, err\n }\n\n return db, nil\n}", "func OpenDBConnection(connStr string, config gorm.Config) (*gorm.DB, error) {\n\tvar err error\n\tonce.Do(func() {\n\t\tdb, err := gorm.Open(mysql.Open(connStr), &config)\n\t\tif err == nil {\n\t\t\tsingleton = db\n\t\t}\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn singleton, nil\n}", "func GetDB() *sql.DB {\n\t//:databaselocked.sqlite?cache=shared&mode=rwc\n\tdatabase, err := sql.Open(\"sqlite3\", \"./rpg.db\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn database\n}", "func (api *MysqlAPI) GetConnectionPool(dbURI string) *sql.DB {\n\tif api.connection == nil {\n\t\tpool, err := sql.Open(\"mysql\", dbURI)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t}\n\t\t// 3 minutes unused connections will be closed\n\t\tpool.SetConnMaxLifetime(3 * time.Minute)\n\t\tpool.SetMaxIdleConns(3)\n\t\tpool.SetMaxOpenConns(10)\n\t\tapi.connection = pool\n\t}\n\treturn api.connection\n}", "func (bdm *MySQLDBManager) getConnection() (*sql.DB, error) {\n\n\tif !bdm.openedConn {\n\t\treturn nil, errors.New(\"Connection was not inited\")\n\t}\n\n\tif bdm.conn != nil {\n\t\treturn bdm.conn, nil\n\t}\n\n\tdb, err := sql.Open(\"mysql\", bdm.Config.GetMySQLConnString())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//db.SetMaxOpenConns(2)\n\tdb.SetMaxIdleConns(2)\n\n\tbdm.conn = db\n\n\treturn db, nil\n}", "func GetDatabase() *gorm.DB {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Fatalln(\"Error loading .env file\")\n\t}\n\tdatabaseUrl := os.Getenv(\"DATABASE_URL\")\n\tdatabase := \"postgres\"\n\tconnection, err := gorm.Open(database, databaseUrl)\n\tif err != nil {\n\t\tlog.Fatalln(\"wrong database url\")\n\t}\n\tsqldb := connection.DB()\n\terr = sqldb.Ping()\n\tif err != nil {\n\t\tlog.Fatalln(\"database connection error\")\n\t}\n\tfmt.Println(\"connected to database\")\n\treturn connection\n}", "func GetMongoDbConnection() (*mongo.Client, error) {\n\n\tclient, err := mongo.Connect(context.Background(), options.Client().ApplyURI(\"\"))\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = client.Ping(context.Background(), readpref.Primary())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn client, nil\n}", "func ReturnDbInstance() *sql.DB {\n\treturn db\n}", "func GetDB() (*gorm.DB, error) {\n\tdbConf := confbz.GetDBConf()\n\tdsn := fmt.Sprintf(\"host=%s port=%s user=%s dbname=%s sslmode=disable password=%s\", dbConf.Host, dbConf.Port, dbConf.User, dbConf.DBName, dbConf.Password)\n\tDB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\treturn DB, err\n}", "func GetDB() *sqlx.DB {\n\tif database == nil {\n\t\tlog.Log.Warn().Msg(\"database accessed before initialization\")\n\t}\n\treturn database\n}", "func (extDb *Database) getDb() *sql.DB {\n\textDb.access.RLock()\n\tdb := extDb.db\n\textDb.access.RUnlock()\n\treturn db\n}", "func GetDB() *pg.DB {\n\treturn db\n}", "func DbConn() (db *sql.DB) {\n\t//var host = \"tcp(192.168.0.14)\"\n\tvar host = \"tcp(192.168.0.12)\"\n\t// var host = \"tcp(127.0.0.1)\"\n\tdbname := \"dbaexperience\"\n\tdb, err := sql.Open(config.DbDriver, fmt.Sprintf(\"%s:%s@%s/%s\", config.DbUser, config.DbPass, host, dbname))\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn db\n}", "func getDbClient(connectionInfo string) *sqlx.DB {\n\n\t// dataSource := fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", dbUser, dbPasswd, dbAddr, dbPort, dbName)\n\n\tclient, err := sqlx.Open(\"mysql\", connectionInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = client.Ping(); err != nil {\n\t\tpanic(err)\n\t}\n\t// See \"Important settings\" section.\n\tclient.SetConnMaxLifetime(time.Minute * 3)\n\tclient.SetMaxOpenConns(10)\n\tclient.SetMaxIdleConns(10)\n\treturn client\n}", "func GetDb() (*mongo.Client, context.Context) {\n\tclient, err := mongo.NewClient(options.Client().ApplyURI(\"mongodb+srv://Nivolves:[email protected]/hospital-crm\"))\n if err != nil {\n log.Fatal(err)\n\t}\n\t\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n err = client.Connect(ctx)\n if err != nil {\n log.Fatal(err)\n }\n\t\n\treturn client, ctx;\n}", "func (app *application) GetDB() *components.Database {\n\treturn app.GetDBInterface().(*components.Database)\n}", "func DB() *Connection {\n\treturn defaultConnection\n}", "func GetDB() *gorm.DB {\n\n\tif db != nil {\n\t\treturn db\n\t}\n\n\tcreateDatabaseConnection()\n\treturn db\n}", "func (fmd *FakeMysqlDaemon) GetAppConnection(ctx context.Context) (*dbconnpool.PooledDBConnection, error) {\n\treturn fmd.appPool.Get(ctx)\n}", "func GetDB() *sql.DB {\n\treturn db\n}", "func GetConn() *mongo.Client {\n\tif Client == nil {\n\t\tCreateConnection(nil)\n\t}\n\treturn Client\n}", "func (pg *postgresDatabase) Connection() *gorm.DB {\n\treturn pg.db\n}", "func GetDBInstance() (*sql.DB, error) {\n\tdbPort := os.Getenv(\"DB_PORT\")\n\tif dbPort == \"\" {\n\t\tdbPort = \"3030\"\n\t}\n\n\tport, _ := strconv.Atoi(dbPort)\n\n\tconn := &database.Model{\n\t\tDatabase: os.Getenv(\"DB_DATABASE\"),\n\t\tEngine: os.Getenv(\"DB_CONNECTION\"),\n\t\tPort: port,\n\t\tPassword: os.Getenv(\"DB_PASSWORD\"),\n\t\tUser: os.Getenv(\"DB_USERNAME\"),\n\t\tServer: os.Getenv(\"DB_HOST\"),\n\t}\n\n\treturn conn.NewConnection()\n}", "func GetDB(host string, user string, port int, sslmode string, dbName string, password string) (interfaces.Database, error) {\n\tif _db == nil {\n\t\tvar err error\n\t\t_db, err = InitDb(host, user, port, sslmode, dbName, password)\n\t\tif err != nil {\n\t\t\t_db = nil\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn _db, nil\n}", "func (d *DB) Conn() *sql.DB { return d.conn }", "func acquireDb() (*postgres.DB, func()) {\n\treturn pool.AcquireDb()\n}", "func GetDB(config JSONConfigurationDB) (*gorm.DB, error) {\n\t// Generate DB connection string\n\tpostgresDSN := fmt.Sprintf(\n\t\tDBString, config.Host, config.Port, config.Name, config.Username, config.Password)\n\t// Connect to DB\n\tdb, err := gorm.Open(DBDialect, postgresDSN)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Performance settings for DB access\n\tdb.DB().SetMaxIdleConns(config.MaxIdleConns)\n\tdb.DB().SetMaxOpenConns(config.MaxOpenConns)\n\tdb.DB().SetConnMaxLifetime(time.Second * time.Duration(config.ConnMaxLifetime))\n\n\treturn db, nil\n}", "func (fmd *FakeMysqlDaemon) GetDbaConnection(ctx context.Context) (*dbconnpool.DBConnection, error) {\n\treturn dbconnpool.NewDBConnection(ctx, fmd.db.ConnParams())\n}", "func (p *DBPool) GetDB() *bolt.DB {\n\treturn <-p.ch\n}", "func GetSimpleConnection() *sql.DB {\n\ts := rand.NewSource(time.Now().Unix())\n\tr := rand.New(s)\n\n\treturn connectionPool[r.Intn(len(connectionPool))].simpleDb\n}", "func GetDB() *gorm.DB {\n\t// Making connection to the database\n\tdb, err := gorm.Open(dbDriver, dbURI)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tretryCount := 30\n\tfor {\n\t\terr := db.DB().Ping()\n\t\tif err != nil {\n\t\t\tif retryCount == 0 {\n\t\t\t\tlog.Fatalf(\"Not able to establish connection to database\")\n\t\t\t}\n\n\t\t\tlog.Printf(fmt.Sprintf(\"Could not connect to database. Wait 2 seconds. %d retries left...\", retryCount))\n\t\t\tretryCount--\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn db\n}", "func GetConn() (conn *sql.DB) {\n\n\tcfg, _ := config.ParseConfig()\n\n\tconnstr := cfg.Db.Username + \":\" + cfg.Db.Password + \"@tcp(\" + cfg.Db.Host + \")/\" + cfg.Db.Database + \"?parseTime=true\"\n\n\tconn, err := sql.Open(\"mysql\", connstr)\n\tif err != nil {\n\t\tutils.LogError(err.Error(), \"utils.go\", 18)\n\t\treturn\n\t}\n\treturn\n}", "func (c *Client) Connect() (*DBConnection, error) {\n\tdbRegistryLock.Lock()\n\tdefer dbRegistryLock.Unlock()\n\n\tdsn := c.config.connStr(c.databaseName)\n\tconn, found := dbRegistry[dsn]\n\tif !found {\n\t\tdb, err := sql.Open(proxyDriverName, dsn)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error connecting to PostgreSQL server %s: %w\", c.config.Host, err)\n\t\t}\n\n\t\t// We don't want to retain connection\n\t\t// So when we connect on a specific database which might be managed by terraform,\n\t\t// we don't keep opened connection in case of the db has to be dopped in the plan.\n\t\tdb.SetMaxIdleConns(0)\n\t\tdb.SetMaxOpenConns(c.config.MaxConns)\n\n\t\tconn = &DBConnection{\n\t\t\tdb,\n\t\t\tc,\n\t\t}\n\t\tdbRegistry[dsn] = conn\n\t}\n\n\treturn conn, nil\n}", "func GetDB(c *gin.Context) *gorm.DB {\n\tvalue, ok := c.Get(ContextKeyDB)\n\tif !ok {\n\t\tpanic(\"database not found in context\")\n\t}\n\tdb, ok := value.(*gorm.DB)\n\tif !ok {\n\t\tpanic(\"database was not the correct type\")\n\t}\n\treturn db\n}", "func GetDB() (couch.Database, os.Error) {\n\treturn couch.NewDatabase(Settings.DatabaseAddress(), \"5984\", Settings.Database())\n}", "func GetConn(name string, batchNum int64) (con *Connection) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tps, ok := poolMaps[name]\n\tif !ok {\n\t\treturn\n\t}\n\tcon = ps[batchNum%int64(len(ps))]\n\treturn\n}", "func GetDatabase() *gorm.DB {\n\treturn db\n}", "func (p *Persister) GetConnection(ctx context.Context) *pop.Connection {\n\tvar c = ctx.Value(transactionKey)\n\tif c != nil {\n\t\tif conn, ok := c.(*pop.Connection); ok {\n\t\t\treturn conn\n\t\t}\n\t}\n\n\treturn p.c\n}" ]
[ "0.75398844", "0.75309074", "0.7511773", "0.7433817", "0.73971796", "0.7390501", "0.7380873", "0.73717964", "0.73367685", "0.7331397", "0.7318038", "0.73079306", "0.72989", "0.72963756", "0.7286296", "0.7281452", "0.72402257", "0.7229041", "0.71688473", "0.71567273", "0.71350294", "0.713232", "0.71034074", "0.7036641", "0.7012784", "0.7012317", "0.70088196", "0.7008555", "0.6997099", "0.6988726", "0.69651204", "0.69567734", "0.6938734", "0.69104844", "0.6892025", "0.6888364", "0.6868259", "0.6806235", "0.6784965", "0.6768567", "0.67558396", "0.6735489", "0.67275125", "0.6697231", "0.6686023", "0.6686023", "0.66693074", "0.66684973", "0.666621", "0.66595054", "0.6654058", "0.66461086", "0.663449", "0.66312164", "0.6622675", "0.660523", "0.66035193", "0.6584991", "0.658231", "0.65781194", "0.65481937", "0.6538056", "0.65108067", "0.6505945", "0.65059155", "0.64954066", "0.6486082", "0.6477779", "0.64704216", "0.64518976", "0.6422892", "0.6420259", "0.64144295", "0.63918227", "0.63805735", "0.6380564", "0.6376088", "0.6371117", "0.6364907", "0.63585716", "0.6352259", "0.63447917", "0.63378376", "0.6315242", "0.6304822", "0.62936157", "0.627963", "0.62685007", "0.62663233", "0.6262756", "0.6260842", "0.6251721", "0.6232417", "0.62271965", "0.62263167", "0.6220415", "0.6215279", "0.62107706", "0.62043583", "0.62012404" ]
0.7414843
4
Transform Beeping Response to a map of collectd.Metrics and send it to Greedee
func sendCollectdMetricsToGreedee(bpResp *httpcheck.Response) { cMetrics := []*collectd.CollectDMetric{} timeNow := time.Now().Unix() cMetrics = append(cMetrics, createCMetric(timeNow, "http_status_code", float64(bpResp.HTTPStatusCode))) cMetrics = append(cMetrics, createCMetric(timeNow, "http_body_pattern", convertBoolToCMetricVal(bpResp.HTTPBodyPattern))) cMetrics = append(cMetrics, createCMetric(timeNow, "http_request_time", float64(bpResp.HTTPRequestTime))) cMetrics = append(cMetrics, createCMetric(timeNow, "dns_lookup", float64(bpResp.DNSLookup))) cMetrics = append(cMetrics, createCMetric(timeNow, "tcp_connection", float64(bpResp.TCPConnection))) cMetrics = append(cMetrics, createCMetric(timeNow, "tls_handshake", float64(bpResp.TLSHandshake))) cMetrics = append(cMetrics, createCMetric(timeNow, "content_transfer", float64(bpResp.ContentTransfer))) cMetrics = append(cMetrics, createCMetric(timeNow, "server_processing", float64(bpResp.ServerProcessing))) if bpResp.SSL != nil { cMetrics = append(cMetrics, createCMetric(timeNow, "cert_expiry_days_left", float64(bpResp.SSL.CertExpiryDaysLeft))) } cMetricsJson, _ := json.Marshal(cMetrics) httpClient := &http.Client{} gdReq, _ := http.NewRequest("POST", *greedeeURL+"/metrics", bytes.NewBuffer(cMetricsJson)) gdReq.Header.Set("Content-Type", "application/json") if greedeeUser != nil && greedeePass != nil { gdReq.SetBasicAuth(*greedeeUser, *greedeePass) } _, err := httpClient.Do(gdReq) if err != nil { log.Fatal(fmt.Printf("[FATAL] Greedee Error: %s\n\n", err)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func scrapeMetrics(ctx context.Context, req httpGetter) (pbMetricMap, error) {\n\tbody, err := httpGetBodyRetry(ctx, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparser := expfmt.TextParser{}\n\treader := strings.NewReader(string(body))\n\tresult, err := parser.TextToMetricFamilies(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbMetricMap(result), nil\n}", "func (g gatherer) GatherMetrics(ctx context.Context, out *apm.Metrics) error {\n\tmetricFamilies, err := g.p.Gather()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tfor _, mf := range metricFamilies {\n\t\tname := mf.GetName()\n\t\tswitch mf.GetType() {\n\t\tcase dto.MetricType_COUNTER:\n\t\t\tfor _, m := range mf.GetMetric() {\n\t\t\t\tv := m.GetCounter().GetValue()\n\t\t\t\tout.Add(name, makeLabels(m.GetLabel()), v)\n\t\t\t}\n\t\tcase dto.MetricType_GAUGE:\n\t\t\tmetrics := mf.GetMetric()\n\t\t\tif name == \"go_info\" && len(metrics) == 1 && metrics[0].GetGauge().GetValue() == 1 {\n\t\t\t\t// Ignore the \"go_info\" metric from the\n\t\t\t\t// built-in GoCollector, as we provide\n\t\t\t\t// the same information in the payload.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, m := range metrics {\n\t\t\t\tv := m.GetGauge().GetValue()\n\t\t\t\tout.Add(name, makeLabels(m.GetLabel()), v)\n\t\t\t}\n\t\tcase dto.MetricType_UNTYPED:\n\t\t\tfor _, m := range mf.GetMetric() {\n\t\t\t\tv := m.GetUntyped().GetValue()\n\t\t\t\tout.Add(name, makeLabels(m.GetLabel()), v)\n\t\t\t}\n\t\tcase dto.MetricType_SUMMARY:\n\t\t\tfor _, m := range mf.GetMetric() {\n\t\t\t\ts := m.GetSummary()\n\t\t\t\tlabels := makeLabels(m.GetLabel())\n\t\t\t\tout.Add(name+\".count\", labels, float64(s.GetSampleCount()))\n\t\t\t\tout.Add(name+\".total\", labels, float64(s.GetSampleSum()))\n\t\t\t\tfor _, q := range s.GetQuantile() {\n\t\t\t\t\tp := int(q.GetQuantile() * 100)\n\t\t\t\t\tout.Add(name+\".percentile.\"+strconv.Itoa(p), labels, q.GetValue())\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// TODO(axw) MetricType_HISTOGRAM\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Collector) Transform(allStats *NodeStatsResponse) (metrics []*exportertools.Metric) {\n for _, stats := range allStats.Nodes {\n // GC Stats\n for _, gcstats := range stats.JVM.GC.Collectors {\n metrics = append(metrics, c.ConvertToMetric(\"jvm_gc_collection_seconds_count\",\n float64(gcstats.CollectionCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_gc_collection_seconds_sum\",\n float64(gcstats.CollectionTime / 1000),\n \"COUNTER\",\n nil))\n }\n\n // Breaker stats\n for _, bstats := range stats.Breakers {\n metrics = append(metrics, c.ConvertToMetric(\"breakers_estimated_size_bytes\",\n float64(bstats.EstimatedSize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"breakers_limit_size_bytes\",\n float64(bstats.LimitSize),\n \"GAUGE\",\n nil))\n }\n\n // Thread Pool stats\n for pool, pstats := range stats.ThreadPool {\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_completed_count\",\n float64(pstats.Completed),\n \"COUNTER\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_rejected_count\",\n float64(pstats.Rejected),\n \"COUNTER\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_active_count\",\n float64(pstats.Active),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_threads_count\",\n float64(pstats.Threads),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_largest_count\",\n float64(pstats.Largest),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_queue_count\",\n float64(pstats.Queue),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n }\n\n // JVM Memory Stats\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_committed_bytes\",\n float64(stats.JVM.Mem.HeapCommitted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_used_bytes\",\n float64(stats.JVM.Mem.HeapUsed),\n \"GAUGE\",\n nil))\n\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_max_bytes\",\n float64(stats.JVM.Mem.HeapMax),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_committed_bytes\",\n float64(stats.JVM.Mem.NonHeapCommitted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_used_bytes\",\n float64(stats.JVM.Mem.NonHeapUsed),\n \"GAUGE\",\n nil))\n\n // Indices Stats)\n metrics = append(metrics, c.ConvertToMetric(\"indices_fielddata_memory_size_bytes\",\n float64(stats.Indices.FieldData.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_fielddata_evictions\",\n float64(stats.Indices.FieldData.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_filter_cache_memory_size_bytes\",\n float64(stats.Indices.FilterCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_filter_cache_evictions\",\n float64(stats.Indices.FilterCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_query_cache_memory_size_bytes\",\n float64(stats.Indices.QueryCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_query_cache_evictions\",\n float64(stats.Indices.QueryCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_request_cache_memory_size_bytes\",\n float64(stats.Indices.QueryCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_request_cache_evictions\",\n float64(stats.Indices.QueryCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_docs\",\n float64(stats.Indices.Docs.Count),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_docs_deleted\",\n float64(stats.Indices.Docs.Deleted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_segments_memory_bytes\",\n float64(stats.Indices.Segments.Memory),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_segments_count\",\n float64(stats.Indices.Segments.Count),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_store_size_bytes\",\n float64(stats.Indices.Store.Size),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_store_throttle_time_ms_total\",\n float64(stats.Indices.Store.ThrottleTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_flush_total\",\n float64(stats.Indices.Flush.Total),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_flush_time_ms_total\",\n float64(stats.Indices.Flush.Time),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_indexing_index_time_ms_total\",\n float64(stats.Indices.Indexing.IndexTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_indexing_index_total\",\n float64(stats.Indices.Indexing.IndexTotal),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total_time_ms_total\",\n float64(stats.Indices.Merges.TotalTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total_size_bytes_total\",\n float64(stats.Indices.Merges.TotalSize),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total\",\n float64(stats.Indices.Merges.Total),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_refresh_total_time_ms_total\",\n float64(stats.Indices.Refresh.TotalTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_refresh_total\",\n float64(stats.Indices.Refresh.Total),\n \"COUNTER\",\n nil))\n\n // Transport Stats)\n metrics = append(metrics, c.ConvertToMetric(\"transport_rx_packets_total\",\n float64(stats.Transport.RxCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_rx_size_bytes_total\",\n float64(stats.Transport.RxSize),\n \"COUNTER\",\n nil))\n\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_tx_packets_total\",\n float64(stats.Transport.TxCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_tx_size_bytes_total\",\n float64(stats.Transport.TxSize),\n \"COUNTER\",\n nil))\n\n // Process Stats)\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_percent\",\n float64(stats.Process.CPU.Percent),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_resident_size_bytes\",\n float64(stats.Process.Memory.Resident),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_share_size_bytes\",\n float64(stats.Process.Memory.Share),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_virtual_size_bytes\",\n float64(stats.Process.Memory.TotalVirtual),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_open_files_count\",\n float64(stats.Process.OpenFD),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.Total / 1000),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.Sys / 1000),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.User / 1000),\n \"COUNTER\",\n nil))\n\n }\n\n return metrics\n}", "func (ic *IpmiCollector) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) {\n\tif !ic.Initialized {\n\t\tic.construct(mts[0].Config().Table()) //reinitialize plugin\n\t}\n\trequestList := make(map[string][]ipmi.IpmiRequest, 0)\n\trequestDescList := make(map[string][]ipmi.RequestDescription, 0)\n\tresponseCache := map[string]map[string]uint16{}\n\tfor _, host := range ic.Hosts {\n\t\trequestList[host] = make([]ipmi.IpmiRequest, 0)\n\t\trequestDescList[host] = make([]ipmi.RequestDescription, 0)\n\t\tfor _, request := range ic.Vendor[host] {\n\t\t\trequestList[host] = append(requestList[host], request.Request)\n\t\t\trequestDescList[host] = append(requestDescList[host], request)\n\t\t}\n\t}\n\tresponse := make(map[string][]ipmi.IpmiResponse, 0)\n\n\tfor _, host := range ic.Hosts {\n\t\tresponse[host], _ = ic.IpmiLayer.BatchExecRaw(requestList[host], host)\n\t}\n\n\tfor nmResponseIdx, hostResponses := range response {\n\t\tcached := map[string]uint16{}\n\t\tfor i, resp := range hostResponses {\n\t\t\tformat := requestDescList[nmResponseIdx][i].Format\n\t\t\tif err := format.Validate(resp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsubmetrics := format.Parse(resp)\n\t\t\tfor k, v := range submetrics {\n\t\t\t\tpath := extendPath(requestDescList[nmResponseIdx][i].MetricsRoot, k)\n\t\t\t\tcached[path] = v\n\t\t\t}\n\t\t\tresponseCache[nmResponseIdx] = cached\n\t\t}\n\t}\n\n\tresults := make([]plugin.MetricType, len(mts))\n\tvar responseMetrics []plugin.MetricType\n\tresponseMetrics = make([]plugin.MetricType, 0)\n\tt := time.Now()\n\n\tfor _, host := range ic.Hosts {\n\t\tfor i, mt := range mts {\n\t\t\tns := mt.Namespace()\n\t\t\tkey := parseName(ns)\n\t\t\tdata := responseCache[host][key]\n\t\t\tmetric := plugin.MetricType{Namespace_: ns, Tags_: map[string]string{\"source\": host},\n\t\t\t\tTimestamp_: t, Data_: data}\n\t\t\tresults[i] = metric\n\t\t\tresponseMetrics = append(responseMetrics, metric)\n\t\t}\n\t}\n\n\treturn responseMetrics, nil\n}", "func (jbobject *MetricsRequestMetricCollector) CollectMetrics(a RequestInterface, b ResponseInterface) {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tconv_b := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := conv_b.Convert(b); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := jbobject.CallMethod(javabind.GetEnv(), \"collectMetrics\", javabind.Void, conv_a.Value().Cast(\"com/amazonaws/Request\"), conv_b.Value().Cast(\"com/amazonaws/Response\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tconv_b.CleanUp()\n\n}", "func (ld *loader) CollectMetrics() (writes metrics.RequestsSummary, reads metrics.RequestsSummary, err error) {\n\t// https://pkg.go.dev/github.com/prometheus/client_golang/prometheus?tab=doc#Gatherer\n\tmfs, err := prometheus.DefaultGatherer.Gather()\n\tif err != nil {\n\t\tld.cfg.Logger.Warn(\"failed to gather prometheus metrics\", zap.Error(err))\n\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t}\n\tfor _, mf := range mfs {\n\t\tif mf == nil {\n\t\t\tcontinue\n\t\t}\n\t\tswitch *mf.Name {\n\t\tcase \"secrets_client_write_requests_success_total\":\n\t\t\tgg := mf.Metric[0].GetGauge()\n\t\t\twrites.SuccessTotal = gg.GetValue()\n\t\tcase \"secrets_client_write_requests_failure_total\":\n\t\t\tgg := mf.Metric[0].GetGauge()\n\t\t\twrites.FailureTotal = gg.GetValue()\n\t\tcase \"secrets_client_write_request_latency_milliseconds\":\n\t\t\twrites.LatencyHistogram, err = metrics.ParseHistogram(\"milliseconds\", mf.Metric[0].GetHistogram())\n\t\t\tif err != nil {\n\t\t\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t\t\t}\n\n\t\tcase \"secrets_client_read_requests_success_total\":\n\t\t\tgg := mf.Metric[0].GetGauge()\n\t\t\treads.SuccessTotal = gg.GetValue()\n\t\tcase \"secrets_client_read_requests_failure_total\":\n\t\t\tgg := mf.Metric[0].GetGauge()\n\t\t\treads.FailureTotal = gg.GetValue()\n\t\tcase \"secrets_client_read_request_latency_milliseconds\":\n\t\t\treads.LatencyHistogram, err = metrics.ParseHistogram(\"milliseconds\", mf.Metric[0].GetHistogram())\n\t\t\tif err != nil {\n\t\t\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\tld.cfg.Logger.Info(\"sorting write latency results\", zap.Int(\"total-data-points\", ld.writeLatencies.Len()))\n\tnow := time.Now()\n\tsort.Sort(ld.writeLatencies)\n\tld.cfg.Logger.Info(\"sorted write latency results\", zap.Int(\"total-data-points\", ld.writeLatencies.Len()), zap.String(\"took\", time.Since(now).String()))\n\twrites.LantencyP50 = ld.writeLatencies.PickLantencyP50()\n\twrites.LantencyP90 = ld.writeLatencies.PickLantencyP90()\n\twrites.LantencyP99 = ld.writeLatencies.PickLantencyP99()\n\twrites.LantencyP999 = ld.writeLatencies.PickLantencyP999()\n\twrites.LantencyP9999 = ld.writeLatencies.PickLantencyP9999()\n\n\tld.cfg.Logger.Info(\"writing latency results in JSON to disk\", zap.String(\"path\", ld.cfg.WritesJSONPath))\n\twb, err := json.Marshal(ld.writeLatencies)\n\tif err != nil {\n\t\tld.cfg.Logger.Warn(\"failed to encode latency results in JSON\", zap.Error(err))\n\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t}\n\tif err = ioutil.WriteFile(ld.cfg.WritesJSONPath, wb, 0600); err != nil {\n\t\tld.cfg.Logger.Warn(\"failed to write latency results in JSON to disk\", zap.String(\"path\", ld.cfg.WritesJSONPath), zap.Error(err))\n\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t}\n\tld.cfg.Logger.Info(\"wrote latency results in JSON to disk\", zap.String(\"path\", ld.cfg.WritesJSONPath))\n\n\tld.cfg.Logger.Info(\"sorting read latency results\", zap.Int(\"total-data-points\", ld.readLatencies.Len()))\n\tnow = time.Now()\n\tsort.Sort(ld.readLatencies)\n\tld.cfg.Logger.Info(\"sorted read latency results\", zap.Int(\"total-data-points\", ld.readLatencies.Len()), zap.String(\"took\", time.Since(now).String()))\n\treads.LantencyP50 = ld.readLatencies.PickLantencyP50()\n\treads.LantencyP90 = ld.readLatencies.PickLantencyP90()\n\treads.LantencyP99 = ld.readLatencies.PickLantencyP99()\n\treads.LantencyP999 = ld.readLatencies.PickLantencyP999()\n\treads.LantencyP9999 = ld.readLatencies.PickLantencyP9999()\n\n\tld.cfg.Logger.Info(\"writing latency results in JSON to disk\", zap.String(\"path\", ld.cfg.ReadsJSONPath))\n\twb, err = json.Marshal(ld.readLatencies)\n\tif err != nil {\n\t\tld.cfg.Logger.Warn(\"failed to encode latency results in JSON\", zap.Error(err))\n\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t}\n\tif err = ioutil.WriteFile(ld.cfg.ReadsJSONPath, wb, 0600); err != nil {\n\t\tld.cfg.Logger.Warn(\"failed to write latency results in JSON to disk\", zap.String(\"path\", ld.cfg.ReadsJSONPath), zap.Error(err))\n\t\treturn metrics.RequestsSummary{}, metrics.RequestsSummary{}, err\n\t}\n\tld.cfg.Logger.Info(\"wrote latency results in JSON to disk\", zap.String(\"path\", ld.cfg.ReadsJSONPath))\n\n\treturn writes, reads, nil\n}", "func SendProcessMetrics() {\n\n c := h.NewClient(ip, port)\n\n processMetrics := s.ProcessMeasurement{\n TimeSlice: timeSlice,\n CpuUsed: cpu,\n MemUsed: mem,\n }\n\n\n path := fmt.Sprintf(\"/v1/metrics/nodes/%s/process/%s/\", nodeName, processName)\n req, _ := c.NewRequest(\"POST\", path, processMetrics)\n\n\n var processMeasurement s.ProcessMeasurement\n\n c.Do(req, &processMeasurement)\n\n\n //fmt.Printf(\"PROCESS MEASUREMENT SENT: %s\\n\", u.PrettyPrint(processMeasurement))\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tresp, err := e.Pihole.GetMetrics()\n\tif err != nil {\n\t\tlog.Errorf(\"Pihole error: %s\", err.Error())\n\t\treturn\n\t}\n\tlog.Debugf(\"PiHole metrics: %#v\", resp)\n\tch <- prometheus.MustNewConstMetric(\n\t\tdomainsBeingBlocked, prometheus.CounterValue, float64(resp.DomainsBeingBlocked))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tdnsQueries, prometheus.CounterValue, float64(resp.DNSQueriesToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsBlocked, prometheus.CounterValue, float64(resp.AdsBlockedToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsPercentage, prometheus.CounterValue, float64(resp.AdsPercentageToday))\n\n\tfor k, v := range resp.Querytypes {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tqueryTypes, prometheus.CounterValue, v, k)\n\t}\n\tfor k, v := range resp.TopQueries {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopQueries, prometheus.CounterValue, float64(v), k)\n\t}\n\tfor k, v := range resp.TopAds {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopAds, prometheus.CounterValue, float64(v), k)\n\n\t}\n\tfor k, v := range resp.TopSources {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopSources, prometheus.CounterValue, float64(v), k)\n\t}\n}", "func ShipMetrics(db *db.DB, cfg *app.Config) {\n\n\tlogger := log.With(logger, \"stage\", \"shipMetrics\")\n\n\toutput := make(chan *fetchedData)\n\n\tpipeline := make(chan []byte, cfg.ConcurrentRequests+1)\n\tgo processTimeSeriesSet(output, pipeline, cfg.MaxSizePerRequest, cfg.ExtLabels)\n\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < int(cfg.ConcurrentRequests); i++ {\n\t\twg.Add(1)\n\t\tgo sendPreparedTimeSeries(&wg, pipeline, cfg.URLStorage, cfg.HTTPTimeout)\n\t}\n\n\tif cfg.Partition <= 0 {\n\t\tcfg.Partition = 1\n\t}\n\n\tdelta := cfg.Partition * 1000 // Seconds -> Milliseconds\n\tmint, maxt := checkTimeRange(db, cfg.Mint, cfg.Maxt)\n\n\tlogger.Log(\"from\", mint, \"to\", maxt)\n\n\tfor current := mint; current <= maxt; current += delta {\n\t\toutput <- getSeriesSetFor(db, current, current+delta)\n\t}\n\n\tclose(output)\n\tlogger.Log(\"status\", \"waiting for finish senders\")\n\n\twg.Wait()\n\tlogger.Log(\"status\", \"finished\")\n}", "func (h *httpJSONRPCClient) CollectMetrics(mts []core.Metric) ([]core.Metric, error) {\n\tvar results []core.Metric\n\tif len(mts) == 0 {\n\t\treturn nil, errors.New(\"no metrics to collect\")\n\t}\n\n\tmetricsToCollect := make([]plugin.PluginMetricType, len(mts))\n\tfor idx, mt := range mts {\n\t\tmetricsToCollect[idx] = plugin.PluginMetricType{\n\t\t\tNamespace_: mt.Namespace(),\n\t\t\tLastAdvertisedTime_: mt.LastAdvertisedTime(),\n\t\t\tVersion_: mt.Version(),\n\t\t\tTags_: mt.Tags(),\n\t\t\tLabels_: mt.Labels(),\n\t\t\tConfig_: mt.Config(),\n\t\t}\n\t}\n\n\targs := &plugin.CollectMetricsArgs{PluginMetricTypes: metricsToCollect}\n\n\tout, err := h.encoder.Encode(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := h.call(\"Collector.CollectMetrics\", []interface{}{out})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(res.Result) == 0 {\n\t\terr := errors.New(\"Invalid response: result is 0\")\n\t\tlogger.WithFields(log.Fields{\n\t\t\t\"_block\": \"CollectMetrics\",\n\t\t\t\"jsonrpc response\": fmt.Sprintf(\"%+v\", res),\n\t\t}).Error(err)\n\t\treturn nil, err\n\t}\n\tr := &plugin.CollectMetricsReply{}\n\terr = h.encoder.Decode(res.Result, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults = make([]core.Metric, len(r.PluginMetrics))\n\tidx := 0\n\tfor _, m := range r.PluginMetrics {\n\t\tresults[idx] = m\n\t\tidx++\n\t}\n\n\treturn results, nil\n}", "func produceMetrics(completeStatMap map[string]string, metricChannel chan<- prometheus.Metric) {\n\n\t// kamailio_core_request_total\n\tconvertStatToMetric(completeStatMap, \"core.drop_requests\", \"drop\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.err_requests\", \"err\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.fwd_requests\", \"fwd\", core_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests\", \"rcv\", core_request_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_rcv_request_total\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_ack\", \"ack\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_bye\", \"bye\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_cancel\", \"cancel\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_info\", \"info\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_invite\", \"invite\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_message\", \"message\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_notify\", \"notify\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_options\", \"options\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_prack\", \"prack\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_publish\", \"publish\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_refer\", \"refer\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_register\", \"register\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_subscribe\", \"subscribe\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_requests_update\", \"update\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.unsupported_methods\", \"unsupported\", core_rcv_request_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_reply_total\n\tconvertStatToMetric(completeStatMap, \"core.drop_replies\", \"drop\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.err_replies\", \"err\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.fwd_replies\", \"fwd\", core_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies\", \"rcv\", core_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_core_rcv_reply_total\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_18x\", \"18x\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_1xx\", \"1xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_2xx\", \"2xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_3xx\", \"3xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_401\", \"401\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_404\", \"404\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_407\", \"407\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_408\", \"408\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_480\", \"480\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_486\", \"486\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_4xx\", \"4xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_5xx\", \"5xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.rcv_replies_6xx\", \"6xx\", core_rcv_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_shm_bytes\n\tconvertStatToMetric(completeStatMap, \"shmem.free_size\", \"free\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.max_used_size\", \"max_used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.real_used_size\", \"real_used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.total_size\", \"total\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"shmem.used_size\", \"used\", shmem_bytes, metricChannel, prometheus.GaugeValue)\n\n\tconvertStatToMetric(completeStatMap, \"shmem.fragments\", \"\", shmem_fragments, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"dns.failed_dns_request\", \"\", dns_failed, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.bad_URIs_rcvd\", \"\", bad_uri, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"core.bad_msg_hdr\", \"\", bad_msg_hdr, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_sl_reply_total\n\tconvertStatToMetric(completeStatMap, \"sl.1xx_replies\", \"1xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.200_replies\", \"200\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.202_replies\", \"202\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.2xx_replies\", \"2xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.300_replies\", \"300\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.301_replies\", \"301\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.302_replies\", \"302\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.3xx_replies\", \"3xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.400_replies\", \"400\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.401_replies\", \"401\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.403_replies\", \"403\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.404_replies\", \"404\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.407_replies\", \"407\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.408_replies\", \"408\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.483_replies\", \"483\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.4xx_replies\", \"4xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.500_replies\", \"500\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.5xx_replies\", \"5xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.6xx_replies\", \"6xx\", sl_reply_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_sl_type_total\n\tconvertStatToMetric(completeStatMap, \"sl.failures\", \"failure\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.received_ACKs\", \"received_ack\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.sent_err_replies\", \"sent_err_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.sent_replies\", \"sent_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"sl.xxx_replies\", \"xxx_reply\", sl_type_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_tcp_total\n\tconvertStatToMetric(completeStatMap, \"tcp.con_reset\", \"con_reset\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.con_timeout\", \"con_timeout\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.connect_failed\", \"connect_failed\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.connect_success\", \"connect_success\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.established\", \"established\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.local_reject\", \"local_reject\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.passive_open\", \"passive_open\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.send_timeout\", \"send_timeout\", tcp_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tcp.sendq_full\", \"sendq_full\", tcp_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tcp_connections\n\tconvertStatToMetric(completeStatMap, \"tcp.current_opened_connections\", \"\", tcp_connections, metricChannel, prometheus.GaugeValue)\n\t// kamailio_tcp_writequeue\n\tconvertStatToMetric(completeStatMap, \"tcp.current_write_queue_size\", \"\", tcp_writequeue, metricChannel, prometheus.GaugeValue)\n\n\t// kamailio_tmx_code_total\n\tconvertStatToMetric(completeStatMap, \"tmx.2xx_transactions\", \"2xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.3xx_transactions\", \"3xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.4xx_transactions\", \"4xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.5xx_transactions\", \"5xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.6xx_transactions\", \"6xx\", tmx_code_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tmx_type_total\n\tconvertStatToMetric(completeStatMap, \"tmx.UAC_transactions\", \"uac\", tmx_type_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.UAS_transactions\", \"uas\", tmx_type_total, metricChannel, prometheus.CounterValue)\n\t// kamailio_tmx\n\tconvertStatToMetric(completeStatMap, \"tmx.active_transactions\", \"active\", tmx, metricChannel, prometheus.GaugeValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.inuse_transactions\", \"inuse\", tmx, metricChannel, prometheus.GaugeValue)\n\n\t// kamailio_tmx_rpl_total\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_absorbed\", \"absorbed\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_generated\", \"generated\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_received\", \"received\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_relayed\", \"relayed\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"tmx.rpl_sent\", \"sent\", tmx_rpl_total, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_dialog\n\tconvertStatToMetric(completeStatMap, \"dialog.active_dialogs\", \"active_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.early_dialogs\", \"early_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.expired_dialogs\", \"expired_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.failed_dialogs\", \"failed_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"dialog.processed_dialogs\", \"processed_dialogs\", dialog, metricChannel, prometheus.CounterValue)\n\n\t// kamailio_usrloc\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-contacts\", \"location-contacts\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-expires\", \"location-expires\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.location-users\", \"location-users\", usrloc, metricChannel, prometheus.CounterValue)\n\tconvertStatToMetric(completeStatMap, \"usrloc.registered_users\", \"registered_users\", usrloc, metricChannel, prometheus.CounterValue)\n}", "func (p RekognitionPlugin) FetchMetrics() (map[string]float64, error) {\n\tstat := make(map[string]float64)\n\n\tfor _, met := range [...]string{\n\t\t\"SuccessfulRequestCount\",\n\t\t\"ThrottledCount\",\n\t\t\"ResponseTime\",\n\t\t\"DetectedFaceCount\",\n\t\t\"DetectedLabelCount\",\n\t\t\"ServerErrorCount\",\n\t\t\"UserErrorCount\",\n\t} {\n\t\tv, err := p.getLastPoint(met)\n\t\tif err == nil {\n\t\t\tstat[met] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\n\treturn stat, nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\t// Reset metrics.\n\tfor _, vec := range e.gauges {\n\t\tvec.Reset()\n\t}\n\n\tfor _, vec := range e.counters {\n\t\tvec.Reset()\n\t}\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\te.up.Set(0)\n\t\tlog.Printf(\"Error while querying Elasticsearch: %v\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read ES response body: %v\", err)\n\t\te.up.Set(0)\n\t\treturn\n\t}\n\n\te.up.Set(1)\n\n\tvar all_stats NodeStatsResponse\n\terr = json.Unmarshal(body, &all_stats)\n\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshal JSON into struct: %v\", err)\n\t\treturn\n\t}\n\n\t// Regardless of whether we're querying the local host or the whole\n\t// cluster, here we can just iterate through all nodes found.\n\n\tfor node, stats := range all_stats.Nodes {\n\t\tlog.Printf(\"Processing node %v\", node)\n\t\t// GC Stats\n\t\tfor collector, gcstats := range stats.JVM.GC.Collectors {\n\t\t\te.counters[\"jvm_gc_collection_count\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionCount))\n\t\t\te.counters[\"jvm_gc_collection_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name, collector).Set(float64(gcstats.CollectionTime))\n\t\t}\n\n\t\t// Breaker stats\n\t\tfor breaker, bstats := range stats.Breakers {\n\t\t\te.gauges[\"breakers_estimated_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.EstimatedSize))\n\t\t\te.gauges[\"breakers_limit_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name, breaker).Set(float64(bstats.LimitSize))\n\t\t}\n\n\t\t// JVM Memory Stats\n\t\te.gauges[\"jvm_mem_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapCommitted))\n\t\te.gauges[\"jvm_mem_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapUsed))\n\t\te.gauges[\"jvm_mem_heap_max_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.HeapMax))\n\t\te.gauges[\"jvm_mem_non_heap_committed_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapCommitted))\n\t\te.gauges[\"jvm_mem_non_heap_used_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.JVM.Mem.NonHeapUsed))\n\n\t\t// Indices Stats\n\t\te.gauges[\"indices_fielddata_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.Evictions))\n\t\te.gauges[\"indices_fielddata_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FieldData.MemorySize))\n\t\te.gauges[\"indices_filter_cache_evictions\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.Evictions))\n\t\te.gauges[\"indices_filter_cache_memory_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.FilterCache.MemorySize))\n\n\t\te.gauges[\"indices_docs_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Count))\n\t\te.gauges[\"indices_docs_deleted\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Docs.Deleted))\n\n\t\te.gauges[\"indices_segments_memory_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Segments.Memory))\n\n\t\te.gauges[\"indices_store_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.Size))\n\t\te.counters[\"indices_store_throttle_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Store.ThrottleTime))\n\n\t\te.counters[\"indices_flush_total\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Total))\n\t\te.counters[\"indices_flush_time_in_millis\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Indices.Flush.Time))\n\n\t\t// Transport Stats\n\t\te.counters[\"transport_rx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxCount))\n\t\te.counters[\"transport_rx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.RxSize))\n\t\te.counters[\"transport_tx_count\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxCount))\n\t\te.counters[\"transport_tx_size_in_bytes\"].WithLabelValues(all_stats.ClusterName, stats.Name).Set(float64(stats.Transport.TxSize))\n\t}\n\n\t// Report metrics.\n\tch <- e.up\n\n\tfor _, vec := range e.counters {\n\t\tvec.Collect(ch)\n\t}\n\n\tfor _, vec := range e.gauges {\n\t\tvec.Collect(ch)\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tif err := e.scrape(); err != nil {\n\t\tlog.Error(err)\n\t\tnomad_up.Set(0)\n\t\tch <- nomad_up\n\t\treturn\n\t}\n\n\tch <- nomad_up\n\tch <- metric_uptime\n\tch <- metric_request_response_time_total\n\tch <- metric_request_response_time_avg\n\n\tfor _, metric := range metric_request_status_count_current {\n\t\tch <- metric\n\t}\n\tfor _, metric := range metric_request_status_count_total {\n\t\tch <- metric\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n if err := e.scrape(ch); err != nil {\n\t\tlog.Infof(\"Error scraping tinystats: %s\", err)\n\t}\n e.ipv4QueryA.Collect(ch)\n e.ipv4QueryNS.Collect(ch)\n e.ipv4QueryCNAME.Collect(ch)\n e.ipv4QuerySOA.Collect(ch)\n e.ipv4QueryPTR.Collect(ch)\n e.ipv4QueryHINFO.Collect(ch)\n e.ipv4QueryMX.Collect(ch)\n e.ipv4QueryTXT.Collect(ch)\n e.ipv4QueryRP.Collect(ch)\n e.ipv4QuerySIG.Collect(ch)\n e.ipv4QueryKEY.Collect(ch)\n e.ipv4QueryAAAA.Collect(ch)\n e.ipv4QueryAXFR.Collect(ch)\n e.ipv4QueryANY.Collect(ch)\n e.ipv4QueryTOTAL.Collect(ch)\n e.ipv4QueryOTHER.Collect(ch)\n e.ipv4QueryNOTAUTH.Collect(ch)\n e.ipv4QueryNOTIMPL.Collect(ch)\n e.ipv4QueryBADCLASS.Collect(ch)\n e.ipv4QueryNOQUERY.Collect(ch)\n\n e.ipv6QueryA.Collect(ch)\n e.ipv6QueryNS.Collect(ch)\n e.ipv6QueryCNAME.Collect(ch)\n e.ipv6QuerySOA.Collect(ch)\n e.ipv6QueryPTR.Collect(ch)\n e.ipv6QueryHINFO.Collect(ch)\n e.ipv6QueryMX.Collect(ch)\n e.ipv6QueryTXT.Collect(ch)\n e.ipv6QueryRP.Collect(ch)\n e.ipv6QuerySIG.Collect(ch)\n e.ipv6QueryKEY.Collect(ch)\n e.ipv6QueryAAAA.Collect(ch)\n e.ipv6QueryAXFR.Collect(ch)\n e.ipv6QueryANY.Collect(ch)\n e.ipv6QueryTOTAL.Collect(ch)\n e.ipv6QueryOTHER.Collect(ch)\n e.ipv6QueryNOTAUTH.Collect(ch)\n e.ipv6QueryNOTIMPL.Collect(ch)\n e.ipv6QueryBADCLASS.Collect(ch)\n e.ipv6QueryNOQUERY.Collect(ch)\n\n\treturn\n}", "func (o *requestMetrics) Collect(ch chan<- prometheus.Metric) {\n\tmetricFamilies, err := o.stStore.GetPromDirectMetrics()\n\tif err != nil {\n\t\tklog.Errorf(\"fetch prometheus metrics failed: %v\", err)\n\t\treturn\n\t}\n\to.handleMetrics(metricFamilies, ch)\n}", "func (m Plugin) FetchMetrics() (map[string]float64, error) {\n\tresp, err := http.Get(fmt.Sprintf(\"http://%s/stats\", m.Target))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tstats := struct {\n\t\tConnections float64 `json:\"connections\"`\n\t\tTotalConnections float64 `json:\"total_connections\"`\n\t\tTotalMessages float64 `json:\"total_messages\"`\n\t\tConnectErrors float64 `json:\"connect_errors\"`\n\t\tMessageErrors float64 `json:\"message_errors\"`\n\t\tClosingConnections float64 `json:\"closing_connections\"`\n\t}{}\n\tif err := json.NewDecoder(resp.Body).Decode(&stats); err != nil {\n\t\treturn nil, err\n\t}\n\tret := make(map[string]float64, 6)\n\tret[\"conn_current\"] = stats.Connections\n\tret[\"conn_total\"] = stats.TotalConnections\n\tret[\"conn_errors\"] = stats.ConnectErrors\n\tret[\"conn_closing\"] = stats.ClosingConnections\n\tret[\"messages_total\"] = stats.TotalMessages\n\tret[\"messages_errors\"] = stats.MessageErrors\n\n\treturn ret, nil\n}", "func (c *SVCResponse) Collect(ch chan<- prometheus.Metric) {\n\tvar err error\n\tc.totalScrapes.Inc()\n\tdefer func() {\n\t\tch <- c.up\n\t\tch <- c.totalScrapes\n\t\tch <- c.jsonParseFailures\n\t}()\n\n\tSVCResp, err := c.fetchDataAndDecode()\n\tif err != nil {\n\t\tc.up.Set(0)\n\t\t_ = level.Warn(*c.logger).Log(\n\t\t\t\"msg\", \"failed to fetch and decode data\",\n\t\t\t\"err\", err,\n\t\t)\n\t\treturn\n\t}\n\tc.up.Set(1)\n\n\tfor _, metric := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tmetric.Desc,\n\t\t\tmetric.Type,\n\t\t\tmetric.Value(&SVCResp),\n\t\t)\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tc.data.Desc,\n\t\tc.data.Type,\n\t\tc.data.Value(&SVCResp),\n\t\tSVCResp.UniqueID, SVCResp.Version, SVCResp.LongVersion, SVCResp.Platform,\n\t)\n}", "func (h *Metrics) Collect(in chan<- prometheus.Metric) {\n\th.duration.Collect(in)\n\th.totalRequests.Collect(in)\n\th.requestSize.Collect(in)\n\th.responseSize.Collect(in)\n\th.handlerStatuses.Collect(in)\n\th.responseTime.Collect(in)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar (\n\t\tdata *Data\n\t\terr error\n\t)\n\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\te.resetGaugeVecs() // Clean starting point\n\n\tvar endpointOfAPI []string\n\tif strings.HasSuffix(rancherURL, \"v3\") || strings.HasSuffix(rancherURL, \"v3/\") {\n\t\tendpointOfAPI = endpointsV3\n\t} else {\n\t\tendpointOfAPI = endpoints\n\t}\n\n\tcacheExpired := e.IsCacheExpired()\n\n\t// Range over the pre-configured endpoints array\n\tfor _, p := range endpointOfAPI {\n\t\tif cacheExpired {\n\t\t\tdata, err = e.gatherData(e.rancherURL, e.resourceLimit, e.accessKey, e.secretKey, p, ch)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error getting JSON from URL %s\", p)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.cache[p] = data\n\t\t} else {\n\t\t\td, ok := e.cache[p]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdata = d\n\t\t}\n\n\t\tif err := e.processMetrics(data, p, e.hideSys, ch); err != nil {\n\t\t\tlog.Errorf(\"Error scraping rancher url: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Metrics successfully processed for %s\", p)\n\t}\n\n\tif cacheExpired {\n\t\te.RenewCache()\n\t}\n\n\tfor _, m := range e.gaugeVecs {\n\t\tm.Collect(ch)\n\t}\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (b *EBPFTelemetry) Collect(ch chan<- prometheus.Metric) {\n\tb.getHelpersTelemetry(ch)\n\tb.getMapsTelemetry(ch)\n}", "func (h *GrayLog) gatherServer(\n\tacc telegraf.Accumulator,\n\tserverURL string,\n) error {\n\tresp, _, err := h.sendRequest(serverURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\trequestURL, err := url.Parse(serverURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to parse address %q: %w\", serverURL, err)\n\t}\n\n\thost, port, _ := net.SplitHostPort(requestURL.Host)\n\tvar dat ResponseMetrics\n\tif err := json.Unmarshal([]byte(resp), &dat); err != nil {\n\t\treturn err\n\t}\n\tfor _, mItem := range dat.Metrics {\n\t\tfields := make(map[string]interface{})\n\t\ttags := map[string]string{\n\t\t\t\"server\": host,\n\t\t\t\"port\": port,\n\t\t\t\"name\": mItem.Name,\n\t\t\t\"type\": mItem.Type,\n\t\t}\n\t\th.flatten(mItem.Fields, fields, \"\")\n\t\tacc.AddFields(mItem.FullName, fields, tags)\n\t}\n\treturn nil\n}", "func (p CognitoIdpPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tstat := make(map[string]interface{})\n\n\tfor _, met := range [...]metrics{\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignUpThrottles\", MackerelName: \"SignUpThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignInThrottles\", MackerelName: \"SignInThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"TokenRefreshThrottles\", MackerelName: \"TokenRefreshThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"FederationThrottles\", MackerelName: \"FederationThrottles\", Type: metricsTypeSum},\n\t} {\n\t\tv, err := p.getLastPoint(met)\n\t\tif err == nil {\n\t\t\tstat[met.MackerelName] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\treturn stat, nil\n}", "func (k *KACollector) Collect(ch chan<- prometheus.Metric) {\n\tk.mutex.Lock()\n\tdefer k.mutex.Unlock()\n\n\tvar err error\n\tvar kaStats []KAStats\n\n\tif k.useJSON {\n\t\tkaStats, err = k.json()\n\t\tif err != nil {\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\t\tlog.Printf(\"keepalived_exporter: %v\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tkaStats, err = k.text()\n\t\tif err != nil {\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\t\tlog.Printf(\"keepalived_exporter: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 1)\n\n\tfor _, st := range kaStats {\n\t\tstate := \"\"\n\t\tif _, ok := state2string[st.Data.State]; ok {\n\t\t\tstate = state2string[st.Data.State]\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_sent\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertSent), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_become_master\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.BecomeMaster), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_release_master\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.ReleaseMaster), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_packet_len_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PacketLenErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_advert_interval_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertIntervalErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_ip_ttl_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AdvertIntervalErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_invalid_type_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.InvalidTypeRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_addr_list_err\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AddrListErr), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_invalid_authtype\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.InvalidAuthtype), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_authtype_mismatch\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AuthtypeMismatch), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_auth_failure\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.AuthFailure), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_pri_zero_rcvd\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PriZeroRcvd), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_vrrp_pri_zero_sent\"], prometheus.CounterValue,\n\t\t\tfloat64(st.Stats.PriZeroSent), st.Data.Iname, st.Data.IfpIfname, strconv.Itoa(st.Data.Vrid), state)\n\t}\n\n\tif k.handle == nil {\n\t\treturn\n\t}\n\n\tsvcs, err := k.handle.GetServices()\n\tif err != nil {\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_up\"], prometheus.GaugeValue, 0)\n\t\tlog.Printf(\"keepalived_exporter: services: %v\", err)\n\t\treturn\n\t}\n\n\tfor _, s := range svcs {\n\t\tdsts, err := k.handle.GetDestinations(s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"keepalived_exporter: destinations: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\taddr := s.Address.String() + \":\" + strconv.Itoa(int(s.Port))\n\t\tproto := strconv.Itoa(int(s.Protocol))\n\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_in_packets\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.PacketsIn), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_out_packets\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.PacketsOut), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_in_bytes\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.BytesIn), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_out_bytes\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.BytesOut), addr, proto)\n\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_vip_conn\"], prometheus.CounterValue,\n\t\t\tfloat64(s.Stats.Connections), addr, proto)\n\n\t\tfor _, d := range dsts {\n\t\t\taddr := d.Address.String() + \":\" + strconv.Itoa(int(d.Port))\n\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_in_packets\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.PacketsIn), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_out_packets\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.PacketsOut), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_in_bytes\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.BytesIn), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_out_bytes\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.BytesOut), addr, proto)\n\t\t\tch <- prometheus.MustNewConstMetric(k.metrics[\"keepalived_lvs_rs_conn\"], prometheus.CounterValue,\n\t\t\t\tfloat64(d.Stats.Connections), addr, proto)\n\t\t}\n\t}\n}", "func (m *Metrics) Data() (*Data, error) {\n\tvar (\n\t\ttotalResponseTime float64\n\t\tmaxTime float64\n\t\tminTime = math.MaxFloat64\n\t\tbufsize = len(m.requests)\n\t\tpercentiledTime = make(percentiledTimeMap)\n\t)\n\tm.m.RLock()\n\tdefer m.m.RUnlock()\n\tfor _, v := range m.requests {\n\t\ttotalResponseTime += v\n\n\t\tif minTime > v {\n\t\t\tminTime = v\n\t\t}\n\t\tif maxTime < v {\n\t\t\tmaxTime = v\n\t\t}\n\t}\n\n\tfor _, p := range percents {\n\t\tvar err error\n\t\tpercentiledTime[p], err = m.requests.Percentile(float64(p))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstatusCount := make(statusCountMap)\n\tfor _, status := range httpStatuses {\n\t\tstatusCount[status] = atomic.LoadInt64(&m.statusCount[status])\n\t}\n\n\treturn &Data{\n\t\tRequest: RequestData{\n\t\t\tCount: atomic.LoadInt64(&m.count),\n\t\t\tStatusCount: statusCount,\n\t\t},\n\t\tResponse: ResponseData{\n\t\t\tMaxTime: maxTime,\n\t\t\tMinTime: minTime,\n\t\t\tAverageTime: totalResponseTime / float64(bufsize),\n\t\t\tPercentiledTime: percentiledTime,\n\t\t},\n\t}, nil\n}", "func (c *poolCollector) Collect(dClient utils.DS8kClient, ch chan<- prometheus.Metric) {\n\tlog.Debugln(\"Entering pools collector ...\")\n\treqPoolURL := \"https://\" + dClient.IpAddress + \":\" + ds8KAPIPort + \"/api/v1/pools\"\n\tpoolsResp, err := dClient.CallDS8kAPI(reqPoolURL)\n\tif err != nil {\n\t\tlog.Errorln(\"Executing '/api/v1/pools' failed: \", err)\n\t}\n\tlog.Debugln(\"Response of '/api/v1/pools': \", poolsResp)\n\t// This is a sample output of /api/v1/polls call\n\t// {\n\t// \t\"counts\": {\n\t// \t\t\"data_counts\": 6,\n\t// \t\t\"total_counts\": 6\n\t// \t},\n\t// \t\"data\": {\n\t// \t\t\"pools\": [\n\t// \t\t\t{\n\t// \t\t\t\t\"cap\": \"5541581553664\",\n\t// \t\t\t\t\"capalloc\": \"1248761741312\",\n\t// \t\t\t\t\"capavail\": \"4273492459520\",\n\t// \t\t\t\t\"easytier\": \"none\",\n\t// \t\t\t\t\"eserep\": {},\n\t// \t\t\t\t\"extent_size\": \"1GiB\",\n\t// \t\t\t\t\"id\": \"P0\",\n\t// \t\t\t\t\"link\": {\n\t// \t\t\t\t\t\"href\": \"https:/10.23.1.10:8452/api/v1/pools/P0\",\n\t// \t\t\t\t\t\"rel\": \"self\"\n\t// \t\t\t\t},\n\t// \t\t\t\t\"name\": \"Prod_code\",\n\t// \t\t\t\t\"node\": \"0\",\n\t// \t\t\t\t\"overprovisioned\": \"0.2\",\n\t// \t\t\t\t\"real_capacity_allocated_on_ese\": \"0\",\n\t// \t\t\t\t\"stgtype\": \"fb\",\n\t// \t\t\t\t\"threshold\": \"15\",\n\t// \t\t\t\t\"tieralloc\": [\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\t\"allocated\": \"1248761741312\",\n\t// \t\t\t\t\t\t\"assigned\": \"0\",\n\t// \t\t\t\t\t\t\"cap\": \"5541581553664\",\n\t// \t\t\t\t\t\t\"tier\": \"ENT\"\n\t// \t\t\t\t\t}\n\t// \t\t\t\t],\n\t// \t\t\t\t\"tserep\": {},\n\t// \t\t\t\t\"virtual_capacity_allocated_on_ese\": \"0\",\n\t// \t\t\t\t\"volumes\": {\n\t// \t\t\t\t\t\"link\": {\n\t// \t\t\t\t\t\t\"href\": \"https:/10.23.1.10:8452/api/v1/pools/P0/volumes\",\n\t// \t\t\t\t\t\t\"rel\": \"self\"\n\t// \t\t\t\t\t}\n\t// \t\t\t\t}\n\t// \t\t\t}\n\t// \t\t]\n\t// \t},\n\t// \t\"server\": {\n\t// \t\t\"code\": \"\",\n\t// \t\t\"message\": \"Operation done successfully.\",\n\t// \t\t\"status\": \"ok\"\n\t// \t}\n\t// }\n\n\tpoolsData := gjson.Get(poolsResp, \"data\").String()\n\tpools := gjson.Get(poolsData, \"pools\").Array()\n\tfor _, pool := range pools {\n\t\tlabelvalues := []string{dClient.IpAddress, pool.Get(\"name\").String() + \"_\" + pool.Get(\"id\").String(), pool.Get(\"node\").String()}\n\t\tch <- prometheus.MustNewConstMetric(totalPoolCapacity, prometheus.GaugeValue, pool.Get(\"cap\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(availablePoolCapacity, prometheus.GaugeValue, pool.Get(\"capavail\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(allocatedPoolCapacity, prometheus.GaugeValue, pool.Get(\"capalloc\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(poolCapacityUsedPercent, prometheus.GaugeValue, pool.Get(\"capalloc\").Float()/pool.Get(\"cap\").Float(), labelvalues...)\n\t}\n\tlog.Debugln(\"Leaving pools collector.\")\n}", "func (km *KataMonitor) ProcessMetricsRequest(w http.ResponseWriter, r *http.Request) {\n\tstart := time.Now()\n\n\tscrapeCount.Inc()\n\tdefer func() {\n\t\tscrapeDurationsHistogram.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Millisecond)))\n\t}()\n\n\t// this is likely the same as `kata-runtime metrics <SANDBOX>`.\n\tsandboxID, err := getSandboxIDFromReq(r)\n\tif err == nil && sandboxID != \"\" {\n\t\tmetrics, err := GetSandboxMetrics(sandboxID)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tw.Write([]byte(metrics))\n\t\treturn\n\t}\n\n\t// if no sandbox provided, will get all sandbox's metrics.\n\n\t// prepare writer for writing response.\n\tcontentType := expfmt.Negotiate(r.Header)\n\n\t// set response header\n\theader := w.Header()\n\theader.Set(contentTypeHeader, string(contentType))\n\n\t// create writer\n\twriter := io.Writer(w)\n\tif mutils.GzipAccepted(r.Header) {\n\t\theader.Set(contentEncodingHeader, \"gzip\")\n\t\tgz := gzipPool.Get().(*gzip.Writer)\n\t\tdefer gzipPool.Put(gz)\n\n\t\tgz.Reset(w)\n\t\tdefer gz.Close()\n\n\t\twriter = gz\n\t}\n\n\t// create encoder to encode metrics.\n\tencoder := expfmt.NewEncoder(writer, contentType)\n\n\t// gather metrics collected for management agent.\n\tmfs, err := prometheus.DefaultGatherer.Gather()\n\tif err != nil {\n\t\tmonitorLog.WithError(err).Error(\"failed to Gather metrics from prometheus.DefaultGatherer\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t// encode metric gathered in current process\n\tif err := encodeMetricFamily(mfs, encoder); err != nil {\n\t\tmonitorLog.WithError(err).Warnf(\"failed to encode metrics\")\n\t}\n\n\t// aggregate sandboxes metrics and write to response by encoder\n\tif err := km.aggregateSandboxMetrics(encoder); err != nil {\n\t\tmonitorLog.WithError(err).Errorf(\"failed aggregateSandboxMetrics\")\n\t\tscrapeFailedCount.Inc()\n\t}\n}", "func (s SolrPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tstat := make(map[string]interface{})\n\tfor core, stats := range s.Stats {\n\t\tfor k, v := range stats {\n\t\t\tstat[core+\"_\"+k] = v\n\t\t}\n\t}\n\treturn stat, nil\n}", "func (c *systemCollector) Collect(dClient utils.DS8kClient, ch chan<- prometheus.Metric) {\n\tlog.Debugln(\"Entering systems collector ...\")\n\treqSystemURL := \"https://\" + dClient.IpAddress + \":\" + ds8KAPIPort + \"/api/v1/systems\"\n\tsystemsResp, err := dClient.CallDS8kAPI(reqSystemURL)\n\tif err != nil {\n\t\tlog.Errorln(\"Executing '/api/v1/systems' failed: \", err)\n\t}\n\tlog.Debugln(\"Response of '/api/v1/systems': \", systemsResp)\n\t// This is the sample output of /api/v1/systems\n\t// {\n\t// \t\"counts\": {\n\t// \t\t\"data_counts\": 1,\n\t// \t\t\"total_counts\": 1\n\t// \t},\n\t// \t\"data\": {\n\t// \t\t\"systems\": [\n\t// \t\t\t{\n\t// \t\t\t\t\"MTM\": \"2831-984\",\n\t// \t\t\t\t\"bundle\": \"88.33.41.0\",\n\t// \t\t\t\t\"cap\": \"43512313675776\",\n\t// \t\t\t\t\"capalloc\": \"31521838727168\",\n\t// \t\t\t\t\"capavail\": \"11906723086336\",\n\t// \t\t\t\t\"capraw\": \"87241523200000\",\n\t// \t\t\t\t\"id\": \"2107-75DXA41\",\n\t// \t\t\t\t\"name\": \"IBM.2107-75DXA40\",\n\t// \t\t\t\t\"release\": \"8.3.3\",\n\t// \t\t\t\t\"sn\": \"75DXA41\",\n\t// \t\t\t\t\"state\": \"online\",\n\t// \t\t\t\t\"wwnn\": \"5005076306FFD65A\"\n\t// \t\t\t}\n\t// \t\t]\n\t// \t},\n\t// \t\"server\": {\n\t// \t\t\"code\": \"\",\n\t// \t\t\"message\": \"Operation done successfully.\",\n\t// \t\t\"status\": \"ok\"\n\t// \t}\n\t// }\n\n\tsystemsData := gjson.Get(systemsResp, \"data\").String()\n\tsystems := gjson.Get(systemsData, \"systems\").Array()\n\tfor _, system := range systems {\n\t\tlabelvalues := []string{system.Get(\"name\").String(), dClient.IpAddress}\n\t\tch <- prometheus.MustNewConstMetric(totalSystemCapacity, prometheus.GaugeValue, system.Get(\"cap\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(availableSystemCapacity, prometheus.GaugeValue, system.Get(\"capavail\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(allocatedSystemCapacity, prometheus.GaugeValue, system.Get(\"capalloc\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(systemCapacityUsedPercent, prometheus.GaugeValue, system.Get(\"capalloc\").Float()/system.Get(\"cap\").Float(), labelvalues...)\n\t\tch <- prometheus.MustNewConstMetric(rawSystemCapacity, prometheus.GaugeValue, system.Get(\"capraw\").Float(), labelvalues...)\n\t}\n\tlog.Debugln(\"Leaving systems collector.\")\n}", "func Metrics(w http.ResponseWriter, r *http.Request) {\n\tpromhttp.Handler().ServeHTTP(w, r)\n}", "func (h *Handler) Heatmap(w http.ResponseWriter, r *http.Request) {\n\n\tdata, err := h.Source.GetAll(0, 0)\n\n\tif err != nil {\n\t\te := Error{\n\t\t\tMessage: \"An error occured when trying to retrieve the deliveries\",\n\t\t}\n\t\tJSONWithHTTPCode(w, e, 500)\n\t\treturn\n\t}\n\n\tlayout := \"2006-01-02T15:04:05Z\"\n\n\trtr := map[string]int{}\n\n\tfor _, d := range data {\n\t\tt, _ := time.Parse(layout, d.Date)\n\t\tts := fmt.Sprintf(\"%d\", t.Unix())\n\t\trtr[ts] = 1\n\t}\n\n\tJSON(w, rtr)\n\n}", "func (h *Handlers) MetricsCollector(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\t\tww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\tdefer func() {\n\t\t\trctx := chi.RouteContext(r.Context())\n\t\t\th.metrics.duration.WithLabelValues(\n\t\t\t\thttp.StatusText(ww.Status()),\n\t\t\t\tr.Method,\n\t\t\t\trctx.RoutePattern(),\n\t\t\t).Observe(time.Since(start).Seconds())\n\t\t}()\n\t\tnext.ServeHTTP(ww, r)\n\t})\n}", "func ExtractMetrics(j []byte) (Metrics, error) {\n\tvar m Metrics\n\terr := json.Unmarshal(j, &m)\n\treturn m, err\n}", "func Collect(ctx context.Context) error {\n\tif !singleton.enabled {\n\t\treturn nil\n\t}\n\n\tif singleton.darkstatAddr == \"\" {\n\t\treturn fmt.Errorf(\"Darkstat address is empty\")\n\t}\n\n\tstartTime := time.Now()\n\n\tinventoryHosts := inventory.Get()\n\n\tlocalAddr, err := network.DefaultLocalAddr()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// To label source traffic that we need to build dependency graph\n\tlocalHostgroup := localAddr.String()\n\tlocalDomain := localAddr.String()\n\tlocalInventory, ok := inventoryHosts[localAddr.String()]\n\tif ok {\n\t\tlocalHostgroup = localInventory.Hostgroup\n\t\tlocalDomain = localInventory.Domain\n\t}\n\tlog.Debugf(\"Local address don't exist in inventory: %v\", localAddr.String())\n\n\t// Scrape darkstat prometheus endpoint for host_bytes_total\n\tvar darkstatHostBytesTotal *prom2json.Family\n\tdarkstatScrape, err := prometheus.Scrape(singleton.darkstatAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, v := range darkstatScrape {\n\t\tif v.Name == \"host_bytes_total\" {\n\t\t\tdarkstatHostBytesTotal = v\n\t\t\tbreak\n\t\t}\n\t}\n\tif darkstatHostBytesTotal == nil {\n\t\treturn fmt.Errorf(\"Metric host_bytes_total doesn't exist\")\n\t}\n\n\t// Extract relevant data out of host_bytes_total\n\tvar hosts []Metric\n\tfor _, m := range darkstatHostBytesTotal.Metrics {\n\t\tmetric := m.(prom2json.Metric)\n\n\t\tip := net.ParseIP(metric.Labels[\"ip\"])\n\n\t\t// Skip its own IP as we don't need it\n\t\tif ip.Equal(localAddr) {\n\t\t\tcontinue\n\t\t}\n\n\t\tinventoryHostInfo := inventoryHosts[metric.Labels[\"ip\"]]\n\n\t\tbandwidth, err := strconv.ParseFloat(metric.Value, 64)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to parse 'host_bytes_total' value: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tdirection := \"\"\n\t\t// Reversed from netfilter perspective\n\t\tswitch metric.Labels[\"dir\"] {\n\t\tcase \"out\":\n\t\t\tdirection = \"ingress\"\n\t\tcase \"in\":\n\t\t\tdirection = \"egress\"\n\t\t}\n\n\t\thosts = append(hosts, Metric{\n\t\t\tLocalHostgroup: localHostgroup,\n\t\t\tRemoteHostgroup: inventoryHostInfo.Hostgroup,\n\t\t\tRemoteIPAddr: metric.Labels[\"ip\"],\n\t\t\tLocalDomain: localDomain,\n\t\t\tRemoteDomain: inventoryHostInfo.Domain,\n\t\t\tDirection: direction,\n\t\t\tBandwidth: bandwidth,\n\t\t})\n\t}\n\n\tsingleton.mu.Lock()\n\tsingleton.hosts = hosts\n\tsingleton.mu.Unlock()\n\n\tlog.Debugf(\"taskdarkstat.Collect retrieved %v downstreams metrics\", len(hosts))\n\tlog.Debugf(\"taskdarkstat.Collect process took %v\", time.Since(startTime))\n\treturn nil\n}", "func MeterResponseStatus(i *Info, m *Metrics) {\n\ts := i.Status / 100\n\tif s >= 2 && s < 4 {\n\t\tm.Counter(\"res.status.ok\").Add()\n\t} else if s == 5 {\n\t\tm.Counter(\"res.status.error\").Add()\n\t} else if s == 4 {\n\t\tm.Counter(\"res.status.bad\").Add()\n\t}\n}", "func (g gatherer) GatherMetrics(ctx context.Context, m *elasticapm.Metrics) error {\n\tg.r.Each(func(name string, v interface{}) {\n\t\tswitch v := v.(type) {\n\t\tcase metrics.Counter:\n\t\t\tm.Add(name, nil, float64(v.Count()))\n\t\tcase metrics.Gauge:\n\t\t\tm.Add(name, nil, float64(v.Value()))\n\t\tcase metrics.GaugeFloat64:\n\t\t\tm.Add(name, nil, v.Value())\n\t\tcase metrics.Histogram:\n\t\t\tm.Add(name+\".count\", nil, float64(v.Count()))\n\t\t\tm.Add(name+\".total\", nil, float64(v.Sum()))\n\t\t\tm.Add(name+\".min\", nil, float64(v.Min()))\n\t\t\tm.Add(name+\".max\", nil, float64(v.Max()))\n\t\t\tm.Add(name+\".stddev\", nil, v.StdDev())\n\t\t\tm.Add(name+\".percentile.50\", nil, v.Percentile(0.5))\n\t\t\tm.Add(name+\".percentile.95\", nil, v.Percentile(0.95))\n\t\t\tm.Add(name+\".percentile.99\", nil, v.Percentile(0.99))\n\t\tdefault:\n\t\t\t// TODO(axw) Meter, Timer, EWMA\n\t\t}\n\t})\n\treturn nil\n}", "func decodeCAdvisorResponse(r io.Reader) (CAdvisorMetrics, error) {\n\tbufScanner := bufio.NewScanner(r)\n\tbufScanner.Split(scanTokens)\n\tcomment := false\n\tcounter := 0\n\tvar (\n\t\tmetric string\n\t\ttags map[string]string\n\t\tvalue float64\n\t\tret = make(CAdvisorMetrics)\n\t)\n\tfor bufScanner.Scan() {\n\t\tscanned := bufScanner.Text()\n\t\ttoken := strings.TrimSpace(scanned[:len(scanned)-1])\n\t\tswitch counter % 3 {\n\t\tcase 0:\n\t\t\tif strings.HasPrefix(token, \"#\") {\n\t\t\t\tcomment = true\n\t\t\t} else {\n\t\t\t\tmetric = token\n\t\t\t}\n\t\tcase 1:\n\t\t\tif !comment {\n\t\t\t\ttags = make(map[string]string)\n\t\t\t\t// TODO: if there is a comma in the value, this will break\n\t\t\t\ttagList := strings.Split(token, \",\")\n\t\t\t\tfor _, tag := range tagList {\n\t\t\t\t\ttagSplit := strings.SplitN(tag, \"=\", 2)\n\t\t\t\t\ttmp, err := strconv.Unquote(tagSplit[1])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, karma.Format(err, \"unable to unquote: %s\", token)\n\t\t\t\t\t}\n\t\t\t\t\ttags[tagSplit[0]] = tmp\n\t\t\t\t}\n\t\t\t}\n\t\tcase 2:\n\t\t\tif !comment {\n\t\t\t\ttmp, err := strconv.ParseFloat(token, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, karma.Format(err, \"unable to parse float %s\", token)\n\t\t\t\t}\n\t\t\t\tvalue = tmp\n\t\t\t\tv, ok := ret[metric]\n\t\t\t\tif !ok {\n\t\t\t\t\tv = make([]TagsValue, 0)\n\t\t\t\t}\n\t\t\t\tv = append(v, TagsValue{\n\t\t\t\t\tTags: tags,\n\t\t\t\t\tValue: value,\n\t\t\t\t})\n\t\t\t\tret[metric] = v\n\t\t\t}\n\t\t}\n\t\tcounter++\n\t\tif scanned[len(scanned)-1] == '\\n' {\n\t\t\tcomment = false\n\t\t\tcounter = 0\n\t\t}\n\t}\n\n\tif err := bufScanner.Err(); err != nil {\n\t\treturn nil, karma.Format(err, \"bufScanner returned an error\")\n\t}\n\treturn ret, nil\n}", "func (m *ClientMetrics) Collect(ch chan<- prom.Metric) {\n\tm.clientStartedCounter.Collect(ch)\n\tm.clientHandledCounter.Collect(ch)\n\tm.clientStreamMsgReceived.Collect(ch)\n\tm.clientStreamMsgSent.Collect(ch)\n\tif m.clientHandledHistogramEnabled {\n\t\tm.clientHandledHistogram.Collect(ch)\n\t}\n}", "func handleResponse(domain *domainDefinition, request *beanRequest, response []*gojmx.AttributeResponse, i *integration.Integration, host, port string) (handlingErrs []error) {\n\t// If there are multiple domains, we have to create an entity for each\n\t// Create a map with domain as the key that returns query/value\n\tdomainsMap := make(map[string][]*beanAttrValue)\n\tfor _, attribute := range response {\n\t\tattrRequest := matchRequest(attribute, request)\n\t\t// Attribute was not requested by config or was filtered.\n\t\tif attrRequest == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif attribute.ResponseType == gojmx.ResponseTypeErr {\n\t\t\tlog.Warn(\"Failed to process attribute for query: %s status: %s\", request.beanQuery, attribute.StatusMsg)\n\t\t\tcontinue\n\t\t}\n\n\t\tdomainName, beanAttr, err := splitBeanName(attribute.Name)\n\t\tif err != nil {\n\t\t\thandlingErrs = append(handlingErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tdomainsMap[domainName] = append(domainsMap[domainName], &beanAttrValue{\n\t\t\tbeanAttr: beanAttr,\n\t\t\tattrRequest: attrRequest,\n\t\t\tvalue: attribute.GetValue(),\n\t\t})\n\t}\n\n\t// For each domain, create an entity and a metric set\n\tfor domainName, beanAttrVals := range domainsMap {\n\t\terr := insertDomainMetrics(domain.eventType, domainName, beanAttrVals, request, i, host, port)\n\t\tif err != nil {\n\t\t\thandlingErrs = append(handlingErrs, err)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn\n}", "func OpMetrics(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tres, err := metrics.GetUsageCpuMem(refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func (m httpReferenceDiscoveryMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.firstPacket.Collect(metrics)\n\tm.totalTime.Collect(metrics)\n\tm.advertisedRefs.Collect(metrics)\n}", "func createGroupMetricsView(results []GroupMetrics, msg string, code int) ([]byte, error) {\n\n\tdocRoot := &respond.ResponseMessage{\n\t\tStatus: respond.StatusResponse{\n\t\t\tMessage: msg,\n\t\t\tCode: strconv.Itoa(code),\n\t\t},\n\t}\n\tdocRoot.Data = results\n\n\toutput, err := json.MarshalIndent(docRoot, \"\", \" \")\n\treturn output, err\n\n}", "func Collect(mon StatSource) map[string]float64 {\n\trv := make(map[string]float64)\n\tmon.Stats(func(key SeriesKey, field string, val float64) {\n\t\trv[key.WithField(field)] = val\n\t})\n\treturn rv\n}", "func (d *decorator) Collect(in chan<- prometheus.Metric) {\n\td.duration.Collect(in)\n\td.requests.Collect(in)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\n\tup, result := e.scrape(ch)\n\n\tch <- e.totalScrapes\n\tch <- e.jsonParseFailures\n\tch <- prometheus.MustNewConstMetric(iqAirUp, prometheus.GaugeValue, up)\n\tch <- prometheus.MustNewConstMetric(iqAirCO2, prometheus.GaugeValue, float64(result.CO2))\n\tch <- prometheus.MustNewConstMetric(iqAirP25, prometheus.GaugeValue, float64(result.P25))\n\tch <- prometheus.MustNewConstMetric(iqAirP10, prometheus.GaugeValue, float64(result.P10))\n\tch <- prometheus.MustNewConstMetric(iqAirTemp, prometheus.GaugeValue, float64(result.Temperature))\n\tch <- prometheus.MustNewConstMetric(iqAirHumidity, prometheus.GaugeValue, float64(result.Humidity))\n}", "func DecodeGrpcReqMetricsQueryResponse(ctx context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*MetricsQueryResponse)\n\treturn req, nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\t// Protect metrics from concurrent collects.\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\t// Scrape metrics from Tankerkoenig API.\n\tif err := e.scrape(ch); err != nil {\n\t\te.logger.Printf(\"error: cannot scrape tankerkoenig api: %v\", err)\n\t}\n\n\t// Collect metrics.\n\te.up.Collect(ch)\n\te.scrapeDuration.Collect(ch)\n\te.failedScrapes.Collect(ch)\n\te.totalScrapes.Collect(ch)\n}", "func (exp *Expvar) Collect() (map[string]interface{}, error) {\n\treq, err := http.NewRequest(http.MethodGet, exp.host, nil)\n\tlog.Println(exp.host)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\n\tresp, err := exp.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := make(map[string]interface{})\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmemStats, ok := (data[\"memstats\"]).(map[string]interface{})\n\tif ok {\n\t\tdata[\"heap\"] = memStats[\"Alloc\"]\n\t}\n\n\tu, err := url.Parse(exp.host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata[\"host\"] = u.Hostname()\n\n\tdelete(data, \"memStats\")\n\tdelete(data, \"cmdline\")\n\n\treturn data, nil\n}", "func serveMetrics(d device) http.Handler {\n\treg := prometheus.NewRegistry()\n\treg.MustRegister(newCollector(d))\n\n\treturn promhttp.HandlerFor(reg, promhttp.HandlerOpts{})\n}", "func (target *Target) Collect() http.HandlerFunc {\n\tif target.opts.ExpositionFormat == \"json\" {\n\t\tdata, err := collectJSONFormat(target.metrics)\n\t\tif err != nil {\n\t\t\tfmt.Errorf(\"error collecting data in json: %s\", err)\n\t\t\treturn sendResponse([]byte(\"Error collecting targets and exposing in json format. Please check logs\"), http.StatusInternalServerError)\n\t\t}\n\t\treturn sendResponse(data, http.StatusOK)\n\t}\n\tcollectPrometheusFormat(target.metrics, target.opts.Namespace)\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tmetrics.WritePrometheus(w, target.opts.ExposeDefaultMetrics)\n\t})\n}", "func (me *Prometheus) ServeInfo(w http.ResponseWriter, r *http.Request) {\n\t// TODO: also add plugins and plugin metrics\n\tstart := time.Now()\n\n\tif !me.checkAddr(r.RemoteAddr) {\n\t\tme.denyAccess(w, r)\n\t\treturn\n\t}\n\n\tme.Logger.Debug().Msgf(\"(httpd) serving info request [%s] (%s)\", r.RequestURI, r.RemoteAddr)\n\n\tbody := make([]string, 0)\n\n\tnumCollectors := 0\n\tnumObjects := 0\n\tnumMetrics := 0\n\n\tuniqueData := map[string]map[string][]string{}\n\n\t// copy cache so we don't lock it\n\tme.cache.Lock()\n\tcache := make(map[string][][]byte)\n\tfor key, data := range me.cache.Get() {\n\t\tcache[key] = make([][]byte, len(data))\n\t\tcopy(cache[key], data)\n\t}\n\tme.cache.Unlock()\n\n\tme.Logger.Debug().Msgf(\"(httpd) fetching %d cached elements\", len(cache))\n\n\tfor key, data := range cache {\n\t\tme.Logger.Debug().Msgf(\"(httpd) key => [%s] (%d)\", key, len(data))\n\t\tvar collector, object string\n\n\t\tif keys := strings.Split(key, \".\"); len(keys) == 2 {\n\t\t\tcollector = keys[0]\n\t\t\tobject = keys[1]\n\t\t\tme.Logger.Debug().Msgf(\"(httpd) collector [%s] - object [%s]\", collector, object)\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\t// skip metadata\n\t\tif strings.HasPrefix(object, \"metadata_\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tmetricNames := set.New()\n\t\tfor _, m := range data {\n\t\t\tif x := strings.Split(string(m), \"{\"); len(x) >= 2 && x[0] != \"\" {\n\t\t\t\tmetricNames.Add(x[0])\n\t\t\t}\n\t\t}\n\t\tnumMetrics += metricNames.Size()\n\n\t\tif _, exists := uniqueData[collector]; !exists {\n\t\t\tuniqueData[collector] = make(map[string][]string)\n\t\t}\n\t\tuniqueData[collector][object] = metricNames.Values()\n\n\t}\n\n\tfor col, perObject := range uniqueData {\n\t\tobjects := make([]string, 0)\n\t\tfor obj, metricNames := range perObject {\n\t\t\tmetrics := make([]string, 0)\n\t\t\tfor _, m := range metricNames {\n\t\t\t\tif m != \"\" {\n\t\t\t\t\tmetrics = append(metrics, fmt.Sprintf(metric_template, m))\n\t\t\t\t}\n\t\t\t}\n\t\t\tobjects = append(objects, fmt.Sprintf(object_template, obj, strings.Join(metrics, \"\\n\")))\n\t\t\tnumObjects += 1\n\t\t}\n\n\t\tbody = append(body, fmt.Sprintf(collector_template, col, strings.Join(objects, \"\\n\")))\n\t\tnumCollectors += 1\n\t}\n\n\tpoller := me.Options.Poller\n\tbodyFlat := fmt.Sprintf(html_template, poller, poller, poller, numCollectors, numObjects, numMetrics, strings.Join(body, \"\\n\\n\"))\n\n\tw.WriteHeader(200)\n\tw.Header().Set(\"content-type\", \"text/html\")\n\t_, err := w.Write([]byte(bodyFlat))\n\tif err != nil {\n\t\tme.Logger.Error().Stack().Err(err).Msg(\"error\")\n\t}\n\n\terr = me.Metadata.LazyAddValueInt64(\"time\", \"info\", time.Since(start).Microseconds())\n\tif err != nil {\n\t\tme.Logger.Error().Stack().Err(err).Msg(\"error\")\n\t}\n}", "func (m httpPostMetrics) Collect(metrics chan<- prometheus.Metric) {\n\tm.totalTime.Collect(metrics)\n\tm.firstProgressPacket.Collect(metrics)\n\tm.firstPackPacket.Collect(metrics)\n\tm.packBytes.Collect(metrics)\n}", "func (c *OrchestratorCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mutex.Lock() // To protect metrics from concurrent collects\n\tdefer c.mutex.Unlock()\n\n\tstats, err := c.orchestratorClient.GetMetrics()\n\tif err != nil {\n\t\tc.upMetric.Set(serviceDown)\n\t\tch <- c.upMetric\n\t\tlog.Printf(\"Error getting Orchestrator stats: %v\", err)\n\t\treturn\n\t}\n\n\tc.upMetric.Set(serviceUp)\n\tch <- c.upMetric\n\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"cluter_size\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Status.Details.AvailableNodes)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_active_node\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.IsActiveNode))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"problems\"],\n\t\tprometheus.GaugeValue, float64(len(stats.Problems)))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"last_failover_id\"],\n\t\tprometheus.CounterValue, float64(stats.LastFailoverID))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"is_healthy\"],\n\t\tprometheus.GaugeValue, boolToFloat64(stats.Status.Details.Healthy))\n\tch <- prometheus.MustNewConstMetric(c.metrics[\"failed_seeds\"],\n\t\tprometheus.CounterValue, float64(stats.FailedSeeds))\n}", "func (c SslCertPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tdays, err := getSslCertMetrics(c.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make(map[string]interface{})\n\tresult[\"days\"] = days\n\treturn result, nil\n}", "func hostMetrics(host *Host, time int32) string {\n \n cpu := random(BigDogMinCPU,BigDogMaxCPU)\n disk := random(BigDogMinDisk,BigDogMaxDisk)\n mem := random(BigDogMinMem,BigDogMaxMem)\n json := fmt.Sprintf(`{\"series\" : \n [\n {\n \"metric\":\"system.cpu.stolen\",\n \"points\":[[%d,0]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.cpu.user\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.disk.used\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.mem.used\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n }\n ]\n }`,time,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,cpu,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,disk,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,mem,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value)\n fmt.Println(json)\n\n return json\n}", "func (c *LoadBalancerCollector) Metrics() []*prometheus.Desc {\n\treturn []*prometheus.Desc{\n\t\tc.Created,\n\t\tc.Services,\n\t\tc.MaxServices,\n\t\tc.Targets,\n\t\tc.MaxTargets,\n\t\tc.TargetsHealthy,\n\t\tc.TargetsUnhealthy,\n\t\tc.TargetsUnknown,\n\t\tc.AssignedCertificates,\n\t\tc.MaxAssignedCertificates,\n\t\tc.IngoingTraffic,\n\t\tc.OutgoingTraffic,\n\t\tc.IncludedTraffic,\n\t\tc.Connections,\n\t\tc.MaxConnections,\n\t\tc.ConnectionsPerSecond,\n\t\tc.RequestsPerSecond,\n\t\tc.IncomingBandwidth,\n\t\tc.OutgoingBandwidth,\n\t}\n}", "func (m *MeterImpl) collect(ctx context.Context, labels []attribute.KeyValue, measurements []Measurement) {\n\tm.provider.addMeasurement(Batch{\n\t\tCtx: ctx,\n\t\tLabels: labels,\n\t\tMeasurements: measurements,\n\t\tLibrary: m.library,\n\t})\n}", "func (mtbulk *MTbulk) ResponseCollector(ctx context.Context) {\n\thostsErrors := make(map[entities.Host][]error)\n\ncollectorLooop:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tbreak collectorLooop\n\t\tcase result, ok := <-mtbulk.Results:\n\t\t\tif !ok {\n\t\t\t\tbreak collectorLooop\n\t\t\t}\n\t\t\tif result.Errors != nil {\n\t\t\t\thostsErrors[result.Job.Host] = append(hostsErrors[result.Job.Host], result.Errors...)\n\t\t\t}\n\n\t\t\tif (mtbulk.Verbose && result.Job.Host != entities.Host{}) {\n\t\t\t\tfmt.Printf(\"%s > /// job: \\\"%s\\\"\\n\", result.Job.Host, result.Job.Kind)\n\t\t\t\tfor _, commandResult := range result.Results {\n\t\t\t\t\tfor _, response := range commandResult.Responses {\n\t\t\t\t\t\tfor _, line := range strings.Split(response, \"\\n\") {\n\t\t\t\t\t\t\tif line != \"\" {\n\t\t\t\t\t\t\t\tfmt.Printf(\"%s > %s\\n\", result.Job.Host, line)\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\tif len(hostsErrors) == 0 {\n\t\treturn\n\t}\n\n\tmtbulk.Status.SetCode(1)\n\n\tif mtbulk.SkipSummary {\n\t\treturn\n\t}\n\n\tvulnerabilitiesDetected := false\n\n\tfmt.Println()\n\tfmt.Println(\"Errors list:\")\n\tfor host, errors := range hostsErrors {\n\t\tif host.IP != \"\" {\n\t\t\tfmt.Printf(\"Device: %s:%s\\n\", host.IP, host.Port)\n\t\t} else {\n\t\t\tfmt.Println(\"Generic:\")\n\t\t}\n\n\t\tfor _, err := range errors {\n\t\t\tif err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"\\t%s\\n\", err)\n\t\t\tif vul, ok := err.(vulnerabilities.VulnerabilityError); ok && vul.Vulnerabilities != nil {\n\t\t\t\tvulnerabilitiesDetected = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif vulnerabilitiesDetected {\n\t\tcves := ExtractCVEs(hostsErrors)\n\n\t\tfmt.Println()\n\t\tfmt.Println(\"Deetected CVE:\")\n\t\tfor _, cve := range cves {\n\t\t\tfmt.Printf(\"%s\\n\", cve)\n\t\t}\n\t}\n}", "func (c *SpeakerDeckCollector) Collect(channel chan<- prometheus.Metric) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tbegin := time.Now()\n\tstats, err := c.client.GetResponses(c.users)\n\tduration := time.Since(begin)\n\n\tif err != nil {\n\t\tchannel <- prometheus.MustNewConstMetric(c.state, prometheus.GaugeValue, 0)\n\t\tchannel <- prometheus.MustNewConstMetric(c.duration, prometheus.GaugeValue, duration.Seconds())\n\t\treturn\n\t}\n\n\tchannel <- prometheus.MustNewConstMetric(c.state, prometheus.GaugeValue, 1)\n\tchannel <- prometheus.MustNewConstMetric(c.duration, prometheus.GaugeValue, duration.Seconds())\n\n\tfor _, stat := range stats {\n\t\tchannel <- prometheus.MustNewConstMetric(c.stars, prometheus.CounterValue, stat.Stars, stat.Deck, stat.Author)\n\t\tchannel <- prometheus.MustNewConstMetric(c.views, prometheus.CounterValue, stat.Views, stat.Deck, stat.Author)\n\t}\n}", "func (p *promProducer) Collect(ch chan<- prometheus.Metric) {\n\tfor _, obj := range p.store.Objects() {\n\t\tmessage, ok := obj.(producers.MetricsMessage)\n\t\tif !ok {\n\t\t\tpromLog.Warnf(\"Unsupported message type %T\", obj)\n\t\t\tcontinue\n\t\t}\n\t\tdims := dimsToMap(message.Dimensions)\n\n\t\tfor _, d := range message.Datapoints {\n\t\t\tpromLog.Debugf(\"Processing datapoint %s\", d.Name)\n\t\t\tvar tagKeys []string\n\t\t\tvar tagVals []string\n\t\t\tfor k, v := range dims {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\t\t\tfor k, v := range d.Tags {\n\t\t\t\ttagKeys = append(tagKeys, sanitizeName(k))\n\t\t\t\ttagVals = append(tagVals, v)\n\t\t\t}\n\n\t\t\tname := sanitizeName(d.Name)\n\t\t\tval, err := coerceToFloat(d.Value)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Bad datapoint value %q: %s\", d.Value, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdesc := prometheus.NewDesc(name, \"DC/OS Metrics Datapoint\", tagKeys, nil)\n\t\t\tmetric, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, val, tagVals...)\n\t\t\tif err != nil {\n\t\t\t\tpromLog.Warnf(\"Could not create Prometheus metric %s: %s\", name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpromLog.Debugf(\"Emitting datapoint %s\", name)\n\t\t\tch <- metric\n\t\t}\n\n\t}\n}", "func (mw *Stats) Data() *Data {\n\tmw.mu.RLock()\n\n\tresponseCounts := make(map[string]int, len(mw.ResponseCounts))\n\ttotalResponseCounts := make(map[string]int, len(mw.TotalResponseCounts))\n\ttotalMetricsCounts := make(map[string]int, len(mw.MetricsCounts))\n\tmetricsCounts := make(map[string]float64, len(mw.MetricsCounts))\n\n\tnow := time.Now()\n\n\tuptime := now.Sub(mw.Uptime)\n\n\tcount := 0\n\tfor code, current := range mw.ResponseCounts {\n\t\tresponseCounts[code] = current\n\t\tcount += current\n\t}\n\n\ttotalCount := 0\n\tfor code, count := range mw.TotalResponseCounts {\n\t\ttotalResponseCounts[code] = count\n\t\ttotalCount += count\n\t}\n\n\ttotalResponseTime := mw.TotalResponseTime.Sub(time.Time{})\n\ttotalResponseSize := mw.TotalResponseSize\n\n\taverageResponseTime := time.Duration(0)\n\taverageResponseSize := int64(0)\n\tif totalCount > 0 {\n\t\tavgNs := int64(totalResponseTime) / int64(totalCount)\n\t\taverageResponseTime = time.Duration(avgNs)\n\t\taverageResponseSize = int64(totalResponseSize) / int64(totalCount)\n\t}\n\n\tfor key, count := range mw.MetricsCounts {\n\t\ttotalMetric := mw.MetricsTimers[key].Sub(time.Time{})\n\t\tavgNs := int64(totalMetric) / int64(count)\n\t\tmetricsCounts[key] = time.Duration(avgNs).Seconds()\n\t\ttotalMetricsCounts[key] = count\n\t}\n\n\tmw.mu.RUnlock()\n\n\tr := &Data{\n\t\tPid: mw.Pid,\n\t\tUpTime: uptime.String(),\n\t\tUpTimeSec: uptime.Seconds(),\n\t\tTime: now.String(),\n\t\tTimeUnix: now.Unix(),\n\t\tStatusCodeCount: responseCounts,\n\t\tTotalStatusCodeCount: totalResponseCounts,\n\t\tCount: count,\n\t\tTotalCount: totalCount,\n\t\tTotalResponseTime: totalResponseTime.String(),\n\t\tTotalResponseSize: totalResponseSize,\n\t\tTotalResponseTimeSec: totalResponseTime.Seconds(),\n\t\tTotalMetricsCounts: totalMetricsCounts,\n\t\tAverageResponseSize: averageResponseSize,\n\t\tAverageResponseTime: averageResponseTime.String(),\n\t\tAverageResponseTimeSec: averageResponseTime.Seconds(),\n\t\tAverageMetricsTimers: metricsCounts,\n\t}\n\n\treturn r\n}", "func (u RackStatsPlugin) FetchMetrics() (stats map[string]interface{}, err error) {\n\tstats, err = u.parseStats()\n\treturn stats, err\n}", "func (c config) Metrics(w http.ResponseWriter, r *http.Request) {\n\tvar generated string\n\n\t// Open nft -nn dump file\n\tnftDump, err := os.Open(c.nftOutPath)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not nft export file %s\", c.nftOutPath)\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"\"))\n\t\treturn\n\t}\n\tdefer nftDump.Close()\n\n\te, err := nftables.ExtractCounters(nftDump)\n\t// Sth went wrong, could not parse\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"\"))\n\t\treturn\n\t}\n\n\t// Iterate over the metrics and generate prometheus readable ones out of it\n\tfor _, metric := range e {\n\t\tgenerated += fmt.Sprintf(\"nft_counter_bytes{comment=\\\"%s\\\"} %d\\n\", metric.Name, metric.Bytes)\n\t\tgenerated += fmt.Sprintf(\"nft_counter_packets{comment=\\\"%s\\\"} %d\\n\", metric.Name, metric.Packets)\n\t}\n\n\tklog.Infof(\"Exported %d counters\", len(e))\n\n\t// Simple af but should be sufficient\n\tw.Write([]byte(generated))\n}", "func (l *Latency) ToMap() map[string]string {\n\tm := make(map[string]string)\n\tj := time.Since(l.Start) - l.Processing - l.Parsing\n\tm[\"parsing\"] = l.Parsing.String()\n\tm[\"processing\"] = l.Processing.String()\n\tm[\"json\"] = j.String()\n\tm[\"total\"] = time.Since(l.Start).String()\n\treturn m\n}", "func Test_CollectMetrics12(t *testing.T) {\n\tassert := assert.New(t)\n\tconfig := getTestConfig(1, 2)\n\tconfig.DataFunc = config.GetTestData1\n\n\tres := config.CollectMetrics()\n\tfmt.Println(\"12: \", res)\n\tfmt.Println(\"12: \", []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}})\n\tassert.Equal(true, cmp.Equal(res, []cmd.MetricData{{Name: \"m1\", Help: \"h1\", MetricType: \"gauge\", Stats: []cmd.MetricRecord{{Value: 999, Labels: []string{\"l01\"}, LabelValues: []string{\"lv01\"}}, {Value: 999, Labels: []string{\"l00\"}, LabelValues: []string{\"lv00\"}}}}}))\n}", "func eventMapping(info []*haproxy.Stat, r mb.ReporterV2) {\n\tfor _, evt := range info {\n\t\tst := reflect.ValueOf(evt).Elem()\n\t\ttypeOfT := st.Type()\n\t\tsource := map[string]interface{}{}\n\n\t\tfor i := 0; i < st.NumField(); i++ {\n\t\t\tf := st.Field(i)\n\t\t\tsource[typeOfT.Field(i).Name] = f.Interface()\n\t\t}\n\n\t\tfields, _ := schema.Apply(source)\n\t\tevent := mb.Event{\n\t\t\tRootFields: common.MapStr{},\n\t\t}\n\n\t\tif processID, err := fields.GetValue(\"process_id\"); err == nil {\n\t\t\tevent.RootFields.Put(\"process.pid\", processID)\n\t\t\tfields.Delete(\"process_id\")\n\t\t}\n\n\t\tevent.MetricSetFields = fields\n\t\tr.Event(event)\n\t}\n}", "func ParseGetMetricsResponse(rsp *http.Response) (*GetMetricsResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &GetMetricsResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest MetricsResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 400:\n\t\tvar dest ResponseError\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON400 = &dest\n\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 500:\n\t\tvar dest ResponseError\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON500 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func toFloat64(t *testing.T, c prometheus.Collector) map[string]float64 {\n\tvar (\n\t\tmChan = make(chan prometheus.Metric)\n\t\texp = map[string]float64{}\n\t)\n\n\tgo func() {\n\t\tc.Collect(mChan)\n\t\tclose(mChan)\n\t}()\n\n\tfor m := range mChan {\n\t\tpb := &dto.Metric{}\n\t\ttestutil.Ok(t, m.Write(pb))\n\t\tif pb.Gauge != nil {\n\t\t\texp[lbToString(pb.GetLabel())] = pb.Gauge.GetValue()\n\t\t\tcontinue\n\t\t}\n\t\tif pb.Counter != nil {\n\t\t\texp[lbToString(pb.GetLabel())] = pb.Counter.GetValue()\n\t\t\tcontinue\n\t\t}\n\t\tif pb.Untyped != nil {\n\t\t\texp[lbToString(pb.GetLabel())] = pb.Untyped.GetValue()\n\t\t}\n\t\tpanic(errors.Errorf(\"collected a non-gauge/counter/untyped metric: %s\", pb))\n\t}\n\n\treturn exp\n}", "func (m *ClientMetrics) Collect(ch chan<- prometheus.Metric) {\n\tm.clientHandledSummary.Collect(ch)\n}", "func (c *metricbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (p *Payload) Map() map[string]interface{} {\n\tpayload := make(map[string]interface{}, 4)\n\n\tif !p.Alert.isValid() {\n\t\tif p.Alert.isSimpleForm() {\n\t\t\tpayload[\"alert\"] = p.Alert.Body\n\t\t} else {\n\t\t\tpayload[\"alert\"] = p.Alert\n\t\t}\n\t}\n\n\tif p.Badge != 0 {\n\t\tpayload[\"badge\"] = p.Badge\n\t}\n\n\tif p.Sound != \"\" {\n\t\tpayload[\"sound\"] = p.Sound\n\t}\n\n\tif p.ContentAvailable {\n\t\tpayload[\"content-available\"] = 1\n\t}\n\n\tif p.Category != \"\" {\n\t\tpayload[\"category\"] = p.Category\n\t}\n\n\treturn map[string]interface{}{\"aps\": payload}\n}", "func (c *libbeatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n\t// output.type with dynamic label\n\tch <- prometheus.MustNewConstMetric(libbeatOutputType, prometheus.CounterValue, float64(1), c.stats.LibBeat.Output.Type)\n\n}", "func (cl *Collector) Send() []error {\n\tif Mail == \"\" || Token == \"\" {\n\t\treturn errAccessCredentials\n\t}\n\n\tmeasurements := cl.collectFunc()\n\n\tif len(measurements) == 0 {\n\t\treturn nil\n\t}\n\n\tvar errs []error\n\n\tfor _, m := range measurements {\n\t\terr := m.Validate()\n\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\tcl.execErrorHandler(errs)\n\t\treturn errs\n\t}\n\n\tcl.lastSendingDate = time.Now().Unix()\n\n\tdata := convertMeasurementSlice(measurements)\n\terrs = execRequest(cl.Engine, req.POST, APIEndpoint+\"/v1/metrics/\", data)\n\n\tcl.execErrorHandler(errs)\n\n\treturn errs\n}", "func (collector *atlassianUPMCollector) Collect(ch chan<- prometheus.Metric) {\n\tstartTime := time.Now()\n\tlog.Debug(\"Collect start\")\n\n\tlog.Debug(\"create request object\")\n\treq, err := http.NewRequest(\"GET\", baseURL, nil)\n\tif err != nil {\n\t\tlog.Error(\"http.NewRequest returned an error:\", err)\n\t}\n\n\tlog.Debug(\"create Basic auth string from argument passed\")\n\tbearer = \"Basic \" + *token\n\n\tlog.Debug(\"add authorization header to the request\")\n\treq.Header.Add(\"Authorization\", bearer)\n\n\tlog.Debug(\"add content type to the request\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tlog.Debug(\"make request... get back a response\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\t\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 0, *fqdn)\n\t\tlog.Warn(\"http.DefaultClient.Do returned an error:\", err, \" return from Collect\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Debug(\"response status code: \", resp.StatusCode)\n\t}\n\n\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 1, *fqdn)\n\n\tvar allPlugins restPlugins\n\tif resp.StatusCode == 200 {\n\t\tlog.Debug(\"get all plugins\")\n\t\tallPlugins = plugins(resp)\n\n\t\t// return user-installed plugins if argument passed\n\t\tif *userInstalled {\n\t\t\tlog.Debug(\"-user-installed found\")\n\t\t\tallPlugins = userInstalledPlugins(allPlugins)\n\t\t}\n\n\t\t// plugins have the ability to be installed, but disabled, this will remove them if disabled\n\t\tif *dropDisabled {\n\t\t\tlog.Debug(\"-drop-disabled found\")\n\t\t\tallPlugins = dropDisabledPlugins(allPlugins)\n\t\t}\n\n\t\t// Jira specific\n\t\t// some plugins maintained by Jira have an additional element, this gives the option to drop those plugins\n\t\tif *dropJiraSoftware {\n\t\t\tlog.Debug(\"-drop-jira-software found\")\n\t\t\tallPlugins = dropJiraSoftwarePlugins(allPlugins)\n\t\t}\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range allPlugins.Plugins {\n\n\t\t\tlog.Debug(\"creating plugin metric for: \" + plugin.Name)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMPlugins,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t0,\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tif resp.StatusCode == 200 && *checkUpdates {\n\t\tlog.Debug(\"get remaining plugins available info\")\n\t\tavailablePluginsMap := getAvailablePluginInfo(allPlugins)\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range availablePluginsMap {\n\t\t\tavailableUpdate := false\n\n\t\t\tverInstalled, err := version.NewVersion(plugin.InstalledVersion)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning plugin installed into version object\")\n\t\t\t}\n\n\t\t\tverAvailable, err := version.NewVersion(plugin.Version)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning available plugin into version object\")\n\t\t\t}\n\n\t\t\tif verInstalled.LessThan(verAvailable) {\n\t\t\t\tlog.Debug(\"plugin: \", plugin.Name, \", is currently running: \", plugin.InstalledVersion, \", and can be upgraded to: \", plugin.Version)\n\t\t\t\tavailableUpdate = true\n\t\t\t}\n\n\t\t\tlog.Debug(\"creating plugin version metric for: \", plugin.Name, \", with Key: \", plugin.Key)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMVersionsMetric,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tboolToFloat(availableUpdate),\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstring(plugin.InstalledVersion),\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tfinishTime := time.Now()\n\telapsedTime := finishTime.Sub(startTime)\n\tlog.Debug(\"set the duration metric\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMTimeMetric, prometheus.GaugeValue, elapsedTime.Seconds(), *fqdn)\n\n\tlog.Debug(\"Collect finished\")\n}", "func (s monitoringMetricsClientDroplet) SendMetrics() (int, error) {\n\tpostURL := s.url + fmt.Sprintf(\"/v1/metrics/droplet_id/%d\", s.dropletID)\n\tappKey := s.appKey\n\tnextPush := randomizedPushInterval()\n\n\tif s.r == nil {\n\t\treturn nextPush, errors.New(\"no registry\")\n\t}\n\terr := httpsCheck(postURL)\n\tif err != nil {\n\t\treturn nextPush, err\n\t}\n\n\t// Collect all metrics.\n\treport := s.CreateReport()\n\n\tlog.Debugf(\"Posting metrics to: %s\", postURL)\n\treq, err := http.NewRequest(\"POST\", postURL, bytes.NewBuffer(report))\n\tif err != nil {\n\t\treturn nextPush, err\n\t}\n\taddUserAgentToHTTPRequest(req)\n\treq.Header.Set(contentTypeHeader, DelimitedTelemetryContentType)\n\treq.Header.Add(authKeyHeader, appKey)\n\n\thc := http.Client{\n\t\tTimeout: httpTimeout,\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: httpTimeout,\n\t\t\t}).Dial,\n\t\t\tTLSHandshakeTimeout: httpTimeout,\n\t\t\tResponseHeaderTimeout: httpTimeout,\n\t\t\tDisableKeepAlives: true,\n\t\t},\n\t}\n\n\tresp, err := hc.Do(req)\n\tif err != nil {\n\t\treturn nextPush, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 202 {\n\t\treturn nextPush,\n\t\t\tfmt.Errorf(\"unexpected status code %d while pushing to %s\", resp.StatusCode, postURL)\n\t}\n\n\treceivedHeaders := resp.Header\n\tsendInterval, err := strconv.Atoi(receivedHeaders.Get(pushIntervalHeaderKey))\n\tif err != nil {\n\t\tsendInterval = nextPush\n\t}\n\treturn sendInterval, nil\n}", "func CaptureMetrics(hnd http.Handler, w http.ResponseWriter, r *http.Request) Metrics {\n\treturn CaptureMetricsFn(w, func(ww http.ResponseWriter) {\n\t\thnd.ServeHTTP(ww, r)\n\t})\n}", "func (r IpvsPlugin) FetchMetrics() (map[string]float64, error) {\n file, err := os.Open(r.Target)\n if err != nil {\n return nil, err\n }\n defer file.Close()\n\n return Parse(file)\n}", "func Collect(metrics []Metric, c CloudWatchService, namespace string) {\n\tid, err := GetInstanceID()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, metric := range metrics {\n\t\tmetric.Collect(id, c, namespace)\n\t}\n}", "func (p S3RequestsPlugin) FetchMetrics() (map[string]float64, error) {\n\tstats := make(map[string]float64)\n\n\tfor _, met := range s3RequestMetricsGroup {\n\t\tv, err := getLastPointFromCloudWatch(p.CloudWatch, p.BucketName, p.FilterID, met)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t} else if v != nil {\n\t\t\tstats = mergeStatsFromDatapoint(stats, v, met)\n\t\t}\n\t}\n\treturn stats, nil\n}", "func (c *beatCollector) Collect(ch chan<- prometheus.Metric) {\n\n\tfor _, i := range c.metrics {\n\t\tch <- prometheus.MustNewConstMetric(i.desc, i.valType, i.eval(c.stats))\n\t}\n\n}", "func (a *SatellitesApiService) ListMetrics(ctx _context.Context, cloud string, satellite string, pool string) ([]Metric, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Metric\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/satellites/{cloud}/{satellite}/{pool}/metrics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"cloud\"+\"}\", _neturl.QueryEscape(parameterToString(cloud, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"satellite\"+\"}\", _neturl.QueryEscape(parameterToString(satellite, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"pool\"+\"}\", _neturl.QueryEscape(parameterToString(pool, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v []Metric\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func MeterResponseTime(i *Info, m *Metrics) {\n\tresTime := i.TimeEnd.Sub(i.TimeStart).Nanoseconds() / int64(time.Millisecond)\n\tm.Histogram(\"res.time\").RecordValue(resTime)\n}", "func Collect(mon Monitor) map[string]float64 {\n\trv := make(map[string]float64)\n\tmon.Stats(func(name string, val float64) {\n\t\trv[name] = val\n\t})\n\treturn rv\n}", "func ServerMetrics() (*Metrics, error) {\n\t// Fetch total artists\n\tartists, err := data.DB.CountArtists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total albums\n\talbums, err := data.DB.CountAlbums()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total songs\n\tsongs, err := data.DB.CountSongs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Fetch total folders\n\tfolders, err := data.DB.CountFolders()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Combine all metrics\n\treturn &Metrics{\n\t\tArtists: artists,\n\t\tAlbums: albums,\n\t\tSongs: songs,\n\t\tFolders: folders,\n\t}, nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.scrape(ch); err != nil {\n\t\tlog.Printf(\"Error scraping nightscout url: %s\", err)\n\t}\n\n\te.statusNightscout.Collect(ch)\n\n\treturn\n}", "func (this *ReceiverHolder) stats(c *gin.Context) {\n\n\tflightData := this.receiver.GetInFlightRavens()\n\n\tdeadBoxData := this.receiver.GetDeadBoxCount()\n\tboxes := make([]string, 0)\n\tfor _, box := range this.receiver.msgReceivers {\n\t\tboxes = append(boxes, box.id)\n\t}\n\n\tdata := gin.H{\n\t\t\"Queue\": this.receiver.source.GetName(),\n\t\t\"IsReliable\": this.receiver.options.isReliable,\n\t\t\"Boxes\": boxes,\n\t\t\"Inflight\": flightData,\n\t\t\"DeadBox\": deadBoxData,\n\t}\n\tc.JSON(200, data)\n}", "func (tr *trackerRequest) decodeResponse() (err error) {\n\ttrackerResponse := strings.NewReader(*tr.response)\n\tdecodedResponse, dErr := bencode.Decode(trackerResponse)\n\tif dErr != nil {\n\t\treturn dErr\n\t}\n\n\t// TODO: Add error handling for failure (requires discussion)\n\t// for each type of key, value pair in response\n\tfor key, val := range decodedResponse {\n\t\tswitch val.(type) {\n\n\t\tcase int64:\n\t\t\t/*\n\t\t\t\tFor each of the key with int64 type\n\t\t\t\tFind the respective struct variable (using FieldByName)\n\t\t\t\tThen by using SetInt(), set value for the same in tr.decodedResp\n\t\t\t*/\n\t\t\trresp := reflect.ValueOf(&tr.DecodedResp)\n\t\t\tresStruct := rresp.Elem()\n\t\t\tformattedKey := utils.FormatKey(key)\n\t\t\ttargetField := resStruct.FieldByName(strings.Title(formattedKey))\n\t\t\ttargetField.SetInt(val.(int64))\n\n\t\tcase []interface{}:\n\t\t\tfetchedValues := val.([]interface{})\n\t\t\tvar p PeerObject\n\t\t\tfor _, values := range fetchedValues {\n\t\t\t\tassertedFetchedVal := values.(map[string]interface{})\n\t\t\t\tfor key, fetchedVal := range assertedFetchedVal {\n\n\t\t\t\t\t/*\n\t\t\t\t\t\tFor each of the key in the peers response from tracker\n\t\t\t\t\t\ti.e. Ip, Port and PeerID\n\t\t\t\t\t\tDynamically, find FieldByName\n\t\t\t\t\t\tAnd update the same in tr.decodedResp.peers by appending\n\t\t\t\t\t\teach peerObject\n\t\t\t\t\t*/\n\t\t\t\t\trresp := reflect.ValueOf(&p)\n\t\t\t\t\tresStruct := rresp.Elem()\n\t\t\t\t\tformattedKey := utils.FormatKey(key)\n\t\t\t\t\ttargetField :=\n\t\t\t\t\t\tresStruct.FieldByName(strings.Title(formattedKey))\n\t\t\t\t\ttargetField.SetString(fetchedVal.(string))\n\n\t\t\t\t\ttr.DecodedResp.Peers =\n\t\t\t\t\t\tappend(tr.DecodedResp.Peers, p)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.New(utils.UnknownDecodeKeysEncountered)\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ebpfConntracker) Collect(ch chan<- prometheus.Metric) {\n\tebpfTelemetry := &netebpf.ConntrackTelemetry{}\n\tif err := e.telemetryMap.Lookup(unsafe.Pointer(&zero), unsafe.Pointer(ebpfTelemetry)); err != nil {\n\t\tlog.Tracef(\"error retrieving the telemetry struct: %s\", err)\n\t} else {\n\t\tdelta := ebpfTelemetry.Registers - conntrackerTelemetry.lastRegisters\n\t\tconntrackerTelemetry.lastRegisters = ebpfTelemetry.Registers\n\t\tch <- prometheus.MustNewConstMetric(conntrackerTelemetry.registersTotal, prometheus.CounterValue, float64(delta))\n\t}\n}", "func (serv MetricsService) Metrics(w http.ResponseWriter, r *http.Request) {\n\tsetAccessControlHeaders(w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tmetricNames := serv.Storage.GetLabelValuesForLabelName(clientmodel.MetricNameLabel)\n\tsort.Sort(metricNames)\n\tresultBytes, err := json.Marshal(metricNames)\n\tif err != nil {\n\t\tglog.Error(\"Error marshalling metric names: \", err)\n\t\thttpJSONError(w, fmt.Errorf(\"Error marshalling metric names: %s\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Write(resultBytes)\n}", "func extractResponseTimes(t *testing.T, context string, bid *openrtb2.BidResponse) map[string]int {\n\tif data, dataType, _, err := jsonparser.Get(bid.Ext, \"responsetimemillis\"); err != nil || dataType != jsonparser.Object {\n\t\tt.Errorf(\"%s: Exchange did not return ext.responsetimemillis object: %v\", context, err)\n\t\treturn nil\n\t} else {\n\t\tresponseTimes := make(map[string]int)\n\t\tif err := json.Unmarshal(data, &responseTimes); err != nil {\n\t\t\tt.Errorf(\"%s: Failed to unmarshal ext.responsetimemillis into map[string]int: %v\", context, err)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Delete the response times so that they don't appear in the JSON, because they can't be tested reliably anyway.\n\t\t// If there's no other ext, just delete it altogether.\n\t\tbid.Ext = jsonparser.Delete(bid.Ext, \"responsetimemillis\")\n\t\tif jsonpatch.Equal(bid.Ext, []byte(\"{}\")) {\n\t\t\tbid.Ext = nil\n\t\t}\n\t\treturn responseTimes\n\t}\n}", "func (dj DelayedJob) CollectMetrics() common.MapStr {\n\tvar failedQuery strings.Builder\n\tfailedQuery.WriteString(\"select count(id) from delayed_jobs where run_at <= '\")\n\tfailedQuery.WriteString(time.Now().Format(\"2006-01-02 15:04:05\"))\n\tfailedQuery.WriteString(\"' AND locked_at IS NULL AND attempts = 0\")\n\tfmt.Println(failedQuery.String())\n\treturn common.MapStr{\n\t\t\"running_jobs\": dj.MetricForQuery(\"select count(id) from delayed_jobs where locked_at IS NOT NULL AND failed_at IS NULL\"),\n\t\t\"failed_jobs\": dj.MetricForQuery(\"select count(id) from delayed_jobs where attempts > 0 AND failed_at IS NULL AND locked_at IS NULL\"),\n\t\t\"pending_jobs\": dj.MetricForQuery(failedQuery.String()),\n\t}\n}", "func (b Blackbox) Collect(metrics chan<- prometheus.Metric) {\n\tb.fetchReferenceDiscoveryMetrics.Collect(metrics)\n\tb.httpPostMetrics.Collect(metrics)\n\tb.wantedRefs.Collect(metrics)\n}", "func (c *Collector) Collect(sampleContainers []stats.SampleContainer) {\n\tselect {\n\tcase <-c.stopSendingMetricsCh:\n\t\treturn\n\tdefault:\n\t}\n\n\tif c.referenceID == \"\" {\n\t\treturn\n\t}\n\n\tnewSamples := []*Sample{}\n\tnewHTTPTrails := []*httpext.Trail{}\n\n\tfor _, sampleContainer := range sampleContainers {\n\t\tswitch sc := sampleContainer.(type) {\n\t\tcase *httpext.Trail:\n\t\t\tsc = useCloudTags(sc)\n\t\t\t// Check if aggregation is enabled,\n\t\t\tif c.config.AggregationPeriod.Duration > 0 {\n\t\t\t\tnewHTTPTrails = append(newHTTPTrails, sc)\n\t\t\t} else {\n\t\t\t\tnewSamples = append(newSamples, NewSampleFromTrail(sc))\n\t\t\t}\n\t\tcase *netext.NetTrail:\n\t\t\t// TODO: aggregate?\n\t\t\tvalues := map[string]float64{\n\t\t\t\tmetrics.DataSent.Name: float64(sc.BytesWritten),\n\t\t\t\tmetrics.DataReceived.Name: float64(sc.BytesRead),\n\t\t\t}\n\n\t\t\tif sc.FullIteration {\n\t\t\t\tvalues[metrics.IterationDuration.Name] = stats.D(sc.EndTime.Sub(sc.StartTime))\n\t\t\t\tvalues[metrics.Iterations.Name] = 1\n\t\t\t}\n\n\t\t\tnewSamples = append(newSamples, &Sample{\n\t\t\t\tType: DataTypeMap,\n\t\t\t\tMetric: \"iter_li_all\",\n\t\t\t\tData: &SampleDataMap{\n\t\t\t\t\tTime: toMicroSecond(sc.GetTime()),\n\t\t\t\t\tTags: sc.GetTags(),\n\t\t\t\t\tValues: values,\n\t\t\t\t},\n\t\t\t})\n\t\tdefault:\n\t\t\tfor _, sample := range sampleContainer.GetSamples() {\n\t\t\t\tnewSamples = append(newSamples, &Sample{\n\t\t\t\t\tType: DataTypeSingle,\n\t\t\t\t\tMetric: sample.Metric.Name,\n\t\t\t\t\tData: &SampleDataSingle{\n\t\t\t\t\t\tType: sample.Metric.Type,\n\t\t\t\t\t\tTime: toMicroSecond(sample.Time),\n\t\t\t\t\t\tTags: sample.Tags,\n\t\t\t\t\t\tValue: sample.Value,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(newSamples) > 0 || len(newHTTPTrails) > 0 {\n\t\tc.bufferMutex.Lock()\n\t\tc.bufferSamples = append(c.bufferSamples, newSamples...)\n\t\tc.bufferHTTPTrails = append(c.bufferHTTPTrails, newHTTPTrails...)\n\t\tc.bufferMutex.Unlock()\n\t}\n}", "func Process(response string, lc logger.LoggingClient) map[string]interface{} {\n\trsp := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(response), &rsp)\n\tif err != nil {\n\t\tlc.Error(\"error unmarshalling response from JSON: %v\", err.Error())\n\t}\n\treturn rsp\n}", "func (s *sender) sendMetrics(ctx context.Context, flds fields) ([]metricPair, error) {\n\tvar (\n\t\tbody strings.Builder\n\t\terrs error\n\t\tdroppedRecords []metricPair\n\t\tcurrentRecords []metricPair\n\t)\n\n\tfor _, record := range s.metricBuffer {\n\t\tvar formattedLine string\n\t\tvar err error\n\n\t\tswitch s.config.MetricFormat {\n\t\tcase PrometheusFormat:\n\t\t\tformattedLine = s.prometheusFormatter.metric2String(record)\n\t\tcase Carbon2Format:\n\t\t\tformattedLine = carbon2Metric2String(record)\n\t\tcase GraphiteFormat:\n\t\t\tformattedLine = s.graphiteFormatter.metric2String(record)\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unexpected metric format: %s\", s.config.MetricFormat)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tar, err := s.appendAndSend(ctx, formattedLine, MetricsPipeline, &body, flds)\n\t\tif err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tif ar.sent {\n\t\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t\t}\n\n\t\t\tif !ar.appended {\n\t\t\t\tdroppedRecords = append(droppedRecords, record)\n\t\t\t}\n\t\t}\n\n\t\t// If data was sent, cleanup the currentTimeSeries counter\n\t\tif ar.sent {\n\t\t\tcurrentRecords = currentRecords[:0]\n\t\t}\n\n\t\t// If log has been appended to body, increment the currentTimeSeries\n\t\tif ar.appended {\n\t\t\tcurrentRecords = append(currentRecords, record)\n\t\t}\n\t}\n\n\tif body.Len() > 0 {\n\t\tif err := s.send(ctx, MetricsPipeline, strings.NewReader(body.String()), flds); err != nil {\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tdroppedRecords = append(droppedRecords, currentRecords...)\n\t\t}\n\t}\n\n\treturn droppedRecords, errs\n}", "func TestCollectorOK(t *testing.T) {\n\tc := collector.New()\n\tctx := context.Background()\n\tmpa := NewStubMeterPoints(\"a\", 0, 100*time.Millisecond)\n\tmpb := NewStubMeterPoints(\"b\", 5, 200*time.Millisecond)\n\tmpc := NewStubMeterPoints(\"c\", 10, 50*time.Millisecond)\n\terr := c.Register(mpa, mpb, mpc)\n\tif err != nil {\n\t\tt.Errorf(\"collector register error: %v\", err)\n\t}\n\tmetrics := c.Retrieve(ctx, time.Second)\n\tif a, ok := metrics.Get(\"a.count\"); !ok || a != \"1\" {\n\t\tt.Errorf(\"illegal value a: %q\", a)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif b, ok := metrics.Get(\"b.count\"); !ok || b != \"7\" {\n\t\tt.Errorf(\"illegal value b: %q\", b)\n\t}\n\tmetrics = c.Retrieve(ctx, time.Second)\n\tif c, ok := metrics.Get(\"c.count\"); !ok || c != \"13\" {\n\t\tt.Errorf(\"illegal value c: %q\", c)\n\t}\n}", "func MetricsHttp(w http.ResponseWriter, r *http.Request) {\n\tvar allOut []string\n\ttotal := big.NewFloat(0)\n\tfor _, v := range allWatching {\n\t\tif v.Balance == \"\" {\n\t\t\tv.Balance = \"0\"\n\t\t}\n\t\tbal := big.NewFloat(0)\n\t\tbal.SetString(v.Balance)\n\t\ttotal.Add(total, bal)\n\t\tallOut = append(allOut, fmt.Sprintf(\"%veth_balance{name=\\\"%v\\\",address=\\\"%v\\\"} %v\", prefix, v.Name, v.Address, v.Balance))\n\t}\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_balance_total %0.18f\", prefix, total))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_load_seconds %0.2f\", prefix, loadSeconds))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_loaded_addresses %v\", prefix, totalLoaded))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_total_addresses %v\", prefix, len(allWatching)))\n\tfmt.Fprintln(w, strings.Join(allOut, \"\\n\"))\n}", "func (r response) Stats() *Stats {\n\tnow := time.Now()\n\n\tvar traces []*Stats\n\n\tfor _, t := range r.Traces() {\n\t\ttraces = append(traces, t.Stats())\n\t}\n\n\treturn &Stats{\n\t\tStatus: r.Status(),\n\t\tRedirects: r.Redirects(),\n\t\tTLS: r.TLS(),\n\t\tHeader: r.Header(),\n\t\tHeaderSize: r.HeaderSize(),\n\t\tBodySize: r.BodySize(),\n\t\tTimeDNS: r.TimeDNS(),\n\t\tTimeConnect: r.TimeConnect(),\n\t\tTimeTLS: r.TimeTLS(),\n\t\tTimeWait: r.TimeWait(),\n\t\tTimeResponse: r.TimeResponse(now),\n\t\tTimeDownload: r.TimeDownload(now),\n\t\tTimeTotal: r.TimeTotal(now),\n\t\tTimeTotalWithRedirects: r.TimeTotalWithRedirects(now),\n\t\tTimeRedirects: r.TimeRedirects(),\n\t\tTraces: traces,\n\t}\n}", "func getMetrics() []Metric {\n\tms := make([]Metric, 0)\n\treturn append(ms, &SimpleEapMetric{})\n}" ]
[ "0.583221", "0.5549367", "0.55337614", "0.55043054", "0.54930604", "0.54480356", "0.5446217", "0.54323757", "0.54194236", "0.5400703", "0.5376873", "0.5363512", "0.5346815", "0.53466266", "0.5343253", "0.5342643", "0.5337625", "0.53317267", "0.5327768", "0.5316042", "0.5310291", "0.52850616", "0.52743673", "0.5262671", "0.5241058", "0.52246237", "0.5224204", "0.5223818", "0.5206003", "0.51874447", "0.516131", "0.5148001", "0.5137544", "0.51231563", "0.5069258", "0.50639653", "0.50630254", "0.5058483", "0.50479937", "0.50334096", "0.5024526", "0.5023822", "0.50178605", "0.50176376", "0.5009904", "0.5003626", "0.49996376", "0.498512", "0.49828053", "0.49798557", "0.49695742", "0.49662077", "0.49655452", "0.4959301", "0.49567825", "0.49525052", "0.49506846", "0.49502218", "0.49483263", "0.49407893", "0.4939763", "0.49354094", "0.4927527", "0.49158293", "0.4915113", "0.49091753", "0.489367", "0.48886362", "0.4887099", "0.48747197", "0.4861853", "0.4859355", "0.48547313", "0.48537102", "0.48491052", "0.48476243", "0.48441428", "0.4838704", "0.48255685", "0.48219138", "0.4819818", "0.48193988", "0.4818927", "0.48178875", "0.48101154", "0.4809174", "0.4803196", "0.4796161", "0.4793352", "0.47927088", "0.47925058", "0.4784214", "0.47838488", "0.47827825", "0.47821394", "0.478181", "0.47782", "0.47763854", "0.47738296", "0.47717184" ]
0.66424936
0
Go is a basic promise implementation: it wraps calls a function in a goroutine, and returns a channel which will later return the function's return value.
func Go(f func() error) chan error { ch := make(chan error, 1) go func() { ch <- f() }() return ch }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func Go(f func() error) chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\tch <- f()\n\t}()\n\treturn ch\n}", "func (pool *Pool) Go(f func()) {\n\tg := pool.get()\n\tg.ch <- f\n}", "func Go(goroutine func()) {\n\tGoWithRecover(goroutine, defaultRecoverGoroutine)\n}", "func Go(goroutine func()) {\n\tGoWithRecover(goroutine, defaultRecoverGoroutine)\n}", "func ExamplePromise() {\n\tstuff := Promise(func() int {\n\t\treturn 3\n\t}).\n\t\tThen(func(x int) int {\n\t\t\tfmt.Println(x)\n\t\t\treturn x * x\n\t\t}).\n\t\tThen(func(x int) {\n\t\t\tfmt.Println(x)\n\t\t})\n\tfmt.Println(stuff.Result)\n\t// Output:\n\t// 3\n\t// 9\n\t// []\n}", "func (c *Circuit) Go(ctx context.Context, runFunc func(context.Context) error, fallbackFunc func(context.Context, error) error) error {\n\tif c == nil {\n\t\tvar wrapper goroutineWrapper\n\t\treturn c.Execute(ctx, wrapper.run(runFunc), wrapper.fallback(fallbackFunc))\n\t}\n\treturn c.Execute(ctx, c.goroutineWrapper.run(runFunc), c.goroutineWrapper.fallback(fallbackFunc))\n}", "func (dummyPool) Go(ctx context.Context, fn func()) error {\n\tgo fn()\n\treturn nil\n}", "func (p *Pool) Go(ctx context.Context, exec Executor) chan error {\n\t//open pool if not\n\tp.Open(nil)\n\t//req\n\tch := make(chan error, 2)\n\tif exec == nil {\n\t\tch <- errors.New(\"Executor required\")\n\t\treturn ch\n\t}\n\tselect {\n\tcase <-p.ctx.Done():\n\t\tch <- p.ctx.Err()\n\tdefault:\n\t\treq := &request{\n\t\t\tctx: context.TODO(),\n\t\t\texec: exec,\n\t\t\tch: ch,\n\t\t}\n\t\tif req.ctx != nil {\n\t\t\treq.ctx = ctx\n\t\t}\n\t\tp.reqs <- req\n\t\tWaitAdd(req.ctx, 1)\n\t}\n\treturn ch\n}", "func (e *Endpoint) Go(function string, args interface{}, reply interface{}, done chan *rpc.Call) *rpc.Call {\n\tcall := &rpc.Call{}\n\tcall.ServiceMethod = function\n\tcall.Args = args\n\tcall.Reply = reply\n\tif done == nil {\n\t\tdone = make(chan *rpc.Call, 10)\n\t} else {\n\t\tif cap(done) == 0 {\n\t\t\tlog.Panic(\"ws_rpc: done channel is unbuffered\")\n\t\t}\n\t}\n\tcall.Done = done\n\n\tmsg := &Message{\n\t\tFunc: function,\n\t\tArgs: args,\n\t}\n\n\te.client.mutex.Lock()\n\te.client.seq++\n\tmsg.ID = e.client.seq\n\te.client.pending[msg.ID] = call\n\te.client.mutex.Unlock()\n\n\t// put sending in a goroutine so a malicious client that\n\t// refuses to read cannot ever make a .Go call block\n\tgo e.send(msg)\n\treturn call\n}", "func Go(name string, run runFunc, fallback fallbackFunc) chan error {\n\tcmd := &command{\n\t\trun: run,\n\t\tfallback: fallback,\n\t\tstart: time.Now(),\n\t\terrChan: make(chan error, 1),\n\t\tfinished: make(chan bool, 1),\n\t\tfallbackOnce: &sync.Once{},\n\t\ttimeoutChan: make(chan struct{}, 1),\n\t\tticketChecked: make(chan struct{}),\n\t}\n\n\t// dont have methods with explicit params and returns\n\t// let data come in and out naturally, like with any closure\n\t// explicit error return to give place for us to kill switch the operation (fallback)\n\n\tcircuit, _, err := GetCircuit(name)\n\tif err != nil {\n\t\tcmd.errChan <- err\n\t\treturn cmd.errChan\n\t}\n\tcmd.circuit = circuit\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tcmd.finished <- true\n\t\t}()\n\n\t\t// Circuits get opened when recent executions have shown to have a high error rate.\n\t\t// Rejecting new executions allows backends to recover, and the circuit will allow\n\t\t// new traffic when it feels a healthly state has returned.\n\t\tif !cmd.circuit.AllowRequest() {\n\t\t\tcmd.errorWithFallback(ErrCircuitOpen)\n\t\t\tclose(cmd.ticketChecked)\n\t\t\treturn\n\t\t}\n\n\t\t// As backends falter, requests take longer but don't always fail.\n\t\t//\n\t\t// When requests slow down but the incoming rate of requests stays the same, you have to\n\t\t// run more at a time to keep up. By controlling concurrency during these situations, you can\n\t\t// shed load which accumulates due to the increasing ratio of active commands to incoming requests.\n\n\t\tselect {\n\t\tcase t := <-circuit.executorPool.Tickets:\n\t\t\tcmd.setTicket(t)\n\n\t\tdefault:\n\t\t\tselect {\n\t\t\tcase t := <-circuit.executorPool.WaitingTicket:\n\t\t\t\tcmd.reportEvent(\"queued\")\n\t\t\t\tcmd.setOverflowTicket(t)\n\t\t\tdefault: // Unable to get execution or waiting ticket, error with MaxConcurrency\n\t\t\t\tcmd.errorWithFallback(ErrMaxConcurrency)\n\t\t\t\tclose(cmd.ticketChecked)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Unable to execute the cmd but was able to get the waiting slot\n\t\t\tselect {\n\t\t\tcase executionTicket := <-circuit.executorPool.Tickets:\n\t\t\t\t// return the ticket right away as it is not required\n\t\t\t\tcmd.circuit.executorPool.ReturnWaitingTicket(cmd.overflowTicket)\n\t\t\t\tcmd.setTicket(executionTicket)\n\t\t\t\tif circuit.IsOpen() {\n\t\t\t\t\tcmd.errorWithFallback(ErrCircuitOpen)\n\t\t\t\t\tclose(cmd.ticketChecked)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-cmd.timeoutChan:\n\t\t\t\t// return the ticket right away as it is not required\n\t\t\t\tcmd.circuit.executorPool.ReturnWaitingTicket(cmd.overflowTicket)\n\t\t\t\tclose(cmd.ticketChecked)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tclose(cmd.ticketChecked)\n\t\trunStart := time.Now()\n\t\trunErr := run()\n\n\t\tif cmd.isTimedOut() {\n\t\t\treturn\n\t\t}\n\n\t\tcmd.setRunDuration(time.Since(runStart))\n\n\t\tif runErr != nil {\n\t\t\tcmd.errorWithFallback(runErr)\n\t\t\treturn\n\t\t}\n\n\t\tcmd.reportEvent(\"success\")\n\t}()\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\t<-cmd.ticketChecked\n\n\t\t\tcmd.mu.Lock()\n\t\t\tcmd.circuit.executorPool.Return(cmd.ticket)\n\t\t\tcopyEvents := append([]string(nil), cmd.events...)\n\t\t\tcmd.mu.Unlock()\n\n\t\t\terr := cmd.circuit.ReportEvent(copyEvents, cmd.start, cmd.getRunDuration())\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t}\n\t\t}()\n\n\t\ttimer := time.NewTimer(getSettings(name).Timeout)\n\t\tdefer timer.Stop()\n\n\t\tselect {\n\t\tcase <-cmd.finished:\n\t\tcase <-timer.C:\n\t\t\tclose(cmd.timeoutChan)\n\t\t\t// mark as timeout only if the reason is timeout,\n\t\t\t// if the job was in overflowQueue mark it as MaxConcurrency\n\t\t\tif cmd.hasOverflowTicket() {\n\t\t\t\t// even if the execution was waiting in queue and then timed-out while executing,\n\t\t\t\t// mark it as ErrMaxConcurrency\n\t\t\t\tcmd.errorWithFallback(ErrMaxConcurrency)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcmd.mu.Lock()\n\t\t\tcmd.timedOut = true\n\t\t\tcmd.mu.Unlock()\n\t\t\tcmd.errorWithFallback(ErrTimeout)\n\t\t}\n\t}()\n\n\treturn cmd.errChan\n}", "func (client *RPCClient) Go(ctx context.Context, serviceMethod string, args *protocol.Message, done chan *Call) *Call {\n\tcall := new(Call)\n\tcall.ServicePath = client.servicePath\n\tcall.ServiceMethod = serviceMethod\n\tcall.ctx = ctx\n\tcall.Req = args\n\n\tif done == nil {\n\t\tdone = make(chan *Call, 10) // buffered.\n\t} else {\n\t\t// If caller passes done != nil, it must arrange that\n\t\t// done has enough buffer for the number of simultaneous\n\t\t// RPCs that will be using that channel. If the channel\n\t\t// is totally unbuffered, it's best not to run at all.\n\t\tif cap(done) == 0 {\n\t\t\tlog.Panic(\"rpc: done channel is unbuffered\")\n\t\t}\n\t}\n\tcall.Done = done\n\tclient.send(call)\n\treturn call\n}", "func (r *rpcClientService) Go(serviceMethod string, args interface{},\n reply interface{}, rspCh chan error) error {\n\n go func() {\n err := r.Call(serviceMethod, args, reply)\n rspCh <- err\n }()\n return nil\n}", "func (g *Group) Go(f func() (interface{}, error)) {\n\tg.initOnce.Do(func() {\n\t\tg.init(context.Background())\n\t})\n\n\tatomic.AddInt64(&g.count, 1)\n\tgo func() {\n\t\tv, err := f()\n\t\tselect {\n\t\tcase g.ch <- result{value: v, err: err}:\n\t\tcase <-g.ctx.Done():\n\t\t}\n\t\tatomic.AddInt64(&g.count, -1)\n\t}()\n}", "func (c *Client) Go(ctx context.Context, method string, result interface{}, done chan Call, args ...interface{}) Call {\n\tswitch {\n\tcase done == nil:\n\t\tdone = make(chan Call, 1)\n\tcase cap(done) == 0:\n\t\tpanic(\"wsrpc: done channel is unbuffered\")\n\t}\n\n\tcall := &call{\n\t\tdone: done,\n\t\tresult: result,\n\t}\n\tif ctx.Err() != nil {\n\t\tcall.err = ctx.Err()\n\t\tcall.finalize()\n\t\treturn call\n\t}\n\tid := atomic.AddUint32(&c.atomicSeq, 1)\n\tif id == 0 {\n\t\tid = atomic.AddUint32(&c.atomicSeq, 1)\n\t}\n\tc.callMu.Lock()\n\tif c.calls != nil {\n\t\tc.calls[id] = call\n\t} else {\n\t\tc.callMu.Unlock()\n\t\tcall.err = c.err\n\t\tcall.finalize()\n\t\treturn call\n\t}\n\tc.callMu.Unlock()\n\n\treq := &request{\n\t\tJSONRPC: \"2.0\",\n\t\tMethod: method,\n\t\tParams: args,\n\t\tID: id,\n\t\tctx: ctx,\n\t}\n\tvar err error\n\tselect {\n\tcase c.send <- req:\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\tcase <-c.errc:\n\t\terr = c.err\n\t}\n\tif err != nil {\n\t\tc.callMu.Lock()\n\t\tdelete(c.calls, id)\n\t\tc.callMu.Unlock()\n\t\t// call was not sent, safe to set and finalize error\n\t\tcall.err = err\n\t\tcall.finalize()\n\t}\n\treturn call\n}", "func (p *GoroutinePool) Go(ctx context.Context, fn func()) error {\n\tselect {\n\tcase <-p.quitChan:\n\t\treturn ErrClosed\n\tdefault:\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase p.fnChan <- fn:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif err := p.startGoroutine(ctx, fn); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase p.fnChan <- fn:\n\t\t\t\treturn nil\n\t\t\tcase <-time.After(time.Millisecond):\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) Go(serviceMethod string, args, reply interface{}, done chan *Call) *Call {\n\tif done == nil {\n\t\tdone = make(chan *Call)\n\t} else if cap(done) == 0 {\n\t\tlog.Panic(\"client: done channel is unbuffered\")\n\t}\n\n\tcall := &Call{\n\t\tServiceMethod: serviceMethod,\n\t\tArgs: args,\n\t\tReply: reply,\n\t\tDone: done,\n\t}\n\n\tc.send(call)\n\treturn call\n}", "func Go(ctx Context, f func(ctx Context)) {\n\tstate := getState(ctx)\n\tstate.dispatcher.newCoroutine(ctx, f)\n}", "func (p *Pool) Go(goroutine func(stop chan bool)) {\n\tp.lock.Lock()\n\tnewRoutine := routine{\n\t\tgoroutine: goroutine,\n\t\tstop: make(chan bool, 1),\n\t}\n\tp.routines = append(p.routines, newRoutine)\n\tp.waitGroup.Add(1)\n\tGo(func() {\n\t\tgoroutine(newRoutine.stop)\n\t\tp.waitGroup.Done()\n\t})\n\tp.lock.Unlock()\n}", "func Go(fn func()) {\n\tgo func() {\n\t\tdefer func() { Ignore(Recover()) }()\n\t\tfn()\n\t}()\n}", "func (client *Client) Go(req proto.AppRequest, reply *proto.AppResponse, done chan *Call) *Call {\n\tcall := new(Call)\n\tcall.Request = req\n\tcall.Reply = reply\n\tif done == nil {\n\t\tdone = make(chan *Call, 10) // buffered.\n\t} else {\n\t\t// If caller passes done != nil, it must arrange that\n\t\t// done has enough buffer for the number of simultaneous\n\t\t// RPCs that will be using that channel. If the channel\n\t\t// is totally unbuffered, it's best not to run at all.\n\t\tif cap(done) == 0 {\n\t\t\tlog.Panic(\"rpc: done channel is unbuffered\")\n\t\t}\n\t}\n\tcall.Done = done\n\tclient.send(call)\n\treturn call\n}", "func (p *Pipeline) Go(f func()) {\n\tp.wait.Add(1)\n\tgo func() {\n\t\tdefer p.wait.Done()\n\t\texc.Try(f).Catch(&exc.Exception{}, func(e exc.Throwable) {\n\t\t\tp.mut.Lock()\n\t\t\tdefer p.mut.Unlock()\n\t\t\tif p.err == nil {\n\t\t\t\tp.err = e\n\t\t\t\tclose(p.done)\n\t\t\t}\n\t\t}).Error()\n\t}()\n}", "func (c *Client) Go(serviceMethod string, args, reply interface{}, done chan *Call) *Call {\n\tif done == nil {\n\t\tdone = make(chan *Call, 10)\n\t} else if cap(done) == 0 {\n\t\tlog.Panic(\"rpc client: done channel is unbuffered\")\n\t}\n\tcall := &Call{\n\t\tServiceMethod: serviceMethod,\n\t\tArgs: args,\n\t\tReply: reply,\n\t\tDone: done,\n\t}\n\tc.send(call)\n\treturn call\n}", "func (client *RPCClient) Go(ctx context.Context, serviceMethod string, args interface{}, reply interface{}, done chan *Call, options ...BeforeOrAfterCallOption) *Call {\n\tcall := new(Call)\n\tcall.ServicePath = client.servicePath\n\tcall.ServiceMethod = serviceMethod\n\tcall.ctx = ctx\n\tcall.Args = args\n\tcall.Reply = reply\n\tcall.serializeType = protocol.MsgPack\n\tfor _, opt := range options {\n\t\tif opt.after {\n\t\t\tcall.AfterCalls = append(call.AfterCalls, opt.option)\n\t\t} else {\n\t\t\topt.option(call)\n\t\t}\n\t}\n\n\tif done == nil {\n\t\tdone = make(chan *Call, 10) // buffered.\n\t} else {\n\t\t// If caller passes done != nil, it must arrange that\n\t\t// done has enough buffer for the number of simultaneous\n\t\t// RPCs that will be using that channel. If the channel\n\t\t// is totally unbuffered, it's best not to run at all.\n\t\tif cap(done) == 0 {\n\t\t\tlog.Panic(\"rpc: done channel is unbuffered\")\n\t\t}\n\t}\n\tcall.Done = done\n\tclient.send(call)\n\treturn call\n}", "func (c *OneClient) Go(ctx context.Context, servicePath string, serviceMethod string, args interface{}, reply interface{}, done chan *Call) (*Call, error) {\n\tc.mu.RLock()\n\txclient := c.xclients[servicePath]\n\tc.mu.RUnlock()\n\n\tif xclient == nil {\n\t\tvar err error\n\t\tc.mu.Lock()\n\t\txclient = c.xclients[servicePath]\n\t\tif xclient == nil {\n\t\t\txclient, err = c.newXClient(servicePath)\n\t\t\tc.xclients[servicePath] = xclient\n\t\t}\n\t\tc.mu.Unlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn xclient.Go(ctx, serviceMethod, args, reply, done)\n}", "func (p *pool) Go(goroutine func(context.Context)) {\n\tp.waitGroup.Add(1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif p.recoverFunc != nil {\n\t\t\t\t\tp.recoverFunc(r)\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.waitGroup.Done()\n\t\t}()\n\t\tgoroutine(p.ctx)\n\t}()\n}", "func (client *BaseClient) Go(\n\tname string,\n\targs []reflect.Value,\n\tsettings *InvokeSettings,\n\tcallback Callback) {\n\tgo func() {\n\t\tdefer client.fireErrorEvent(name, nil)\n\t\tcallback(client.Invoke(name, args, settings))\n\t}()\n}", "func (g *Group) Go(f func(quit <-chan struct{}) error) {\n\tg.mu.Lock()\n\tif g.quit == nil {\n\t\tg.quit = make(chan struct{})\n\t}\n\tg.mu.Unlock()\n\n\tg.wg.Add(1)\n\tgo func() {\n\t\terr := f(g.quit)\n\t\tif err != nil {\n\t\t\tg.mu.Lock()\n\t\t\tif g.err == nil {\n\t\t\t\tg.err = err\n\t\t\t}\n\t\t\tg.mu.Unlock()\n\t\t\tg.Quit()\n\t\t}\n\t\tg.wg.Done()\n\t}()\n}", "func (p *GoroutinePool) Go(ctx context.Context, f func()) {\n\tif err := p.sem.Acquire(context.TODO(), 1); err != nil {\n\t\tlog.Errorf(ctx, \"[GoroutinePool] Go acquire failed %v\", err)\n\t\treturn\n\t}\n\tSentryGo(func() {\n\t\tdefer p.sem.Release(1)\n\t\tf()\n\t})\n}", "func (x Go) Go(f func()) error {\n\tvar started, funcDone chan struct{}\n\tif x.ensureStarted {\n\t\tstarted = make(chan struct{})\n\t}\n\tif x.timeout != 0 {\n\t\tfuncDone = make(chan struct{})\n\t}\n\tif x.wg != nil {\n\t\tx.wg.Add(1)\n\t}\n\n\tgo func() {\n\t\tif started != nil {\n\t\t\tclose(started)\n\t\t}\n\t\tif x.wg != nil {\n\t\t\tdefer x.wg.Done()\n\t\t}\n\t\tif funcDone != nil {\n\t\t\tdefer close(funcDone)\n\t\t}\n\t\tif x.recoverFunc != nil {\n\t\t\tdefer func() {\n\t\t\t\tif e := recover(); e != nil {\n\t\t\t\t\tx.recoverFunc(e)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tif x.before != nil {\n\t\t\tx.before()\n\t\t}\n\t\tif x.after != nil && x.deferAfter {\n\t\t\tdefer x.after()\n\t\t}\n\n\t\tf()\n\n\t\tif x.after != nil && !x.deferAfter {\n\t\t\tx.after()\n\t\t}\n\t}()\n\n\tif started != nil {\n\t\t<-started\n\t}\n\tif funcDone != nil {\n\t\tif x.timeout > 0 {\n\t\t\ttm := time.NewTimer(x.timeout)\n\t\t\tdefer func() {\n\t\t\t\tif !tm.Stop() {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-tm.C:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\tselect {\n\t\t\tcase <-funcDone:\n\t\t\tcase <-tm.C:\n\t\t\t\treturn ErrTimeout\n\t\t\t}\n\t\t} else if x.timeout < 0 {\n\t\t\t<-funcDone\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *promise) Wait(waitChan chan Controller) Promise {\n\tp.Always(func(p2 Controller) {\n\t\twaitChan <- p2\n\t})\n\n\treturn <-waitChan\n}", "func (wg *WaitGroup) Go(fn func(...interface{}), arg ...interface{}) {\n\twg.Wg.Add(1)\n\tgo func() {\n\t\tfn(arg...)\n\t\twg.Wg.Done()\n\t}()\n}", "func ExamplePromiseStruct() {\n\tstuff := Promise(func() int {\n\t\treturn 3\n\t}).\n\t\tThen(func(x int) (int, error) {\n\t\t\tfmt.Println(x)\n\t\t\treturn x * x, nil\n\t\t}).\n\t\tThen(func(x float64) (float64, error) {\n\t\t\tfmt.Println(x)\n\t\t\treturn x * x, nil\n\t\t}).\n\t\tCatch(func(e error) error {\n\t\t\tfmt.Println(e)\n\t\t\treturn e\n\t\t})\n\tfmt.Println(stuff.Result[0])\n\t// Output:\n\t// 3\n\t// Args should be float64 but got int\n\t// Args should be float64 but got int\n}", "func (g *Group) Go(\n\tfn func(context.Context) error,\n) error {\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn g.ctx.Err()\n\tdefault:\n\t}\n\n\tg.wgM.RLock()\n\tdefer g.wgM.RUnlock()\n\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn g.ctx.Err()\n\tdefault:\n\t\tg.wg.Add(1)\n\t\tgo g.execute(fn)\n\t\treturn nil\n\t}\n}", "func getNumberWithReturnChan() <-chan int {\n\t// create the channel\n\tc := make(chan int)\n\t// 3.0\n\tgo func() {\n\t\t// push the result into the channel\n\t\tc <- 5\n\t}()\n\n\t// 3.1\n\t// go func() {\n\t// \tfor i := 0; i < 3; i++ {\n\t// \t\tc <- i\n\t// \t}\n\t// \tclose(c)\n\t// }()\n\t// immediately return the channel\n\treturn c\n}", "func (g *FuncGroup) Go(f func()) {\n\t(*sync.WaitGroup)(unsafe.Pointer(g)).Add(1)\n\tdefer (*sync.WaitGroup)(unsafe.Pointer(g)).Done()\n\tf()\n}", "func NewPromise() Promise {\n\treturn &promise{sync.Mutex{}, make(chan error), nil, nil, false}\n}", "func (w *WaitGroup) Go(f func()) {\n\tw.wg.Add(1)\n\tgo w.do(f)\n}", "func (p *promise) Signal(waitChan chan Controller) Promise {\n\tp.Always(func(p2 Controller) {\n\t\twaitChan <- p2\n\t})\n\n\treturn p\n}", "func main() {\n\tc := make(chan int)\n\n\tgo func() {c <- 42}()\n\n\tfmt.Println(<-c)\n}", "func testfunctions(){\n\t// Test Go Channels\n\tchannel_var := make(chan string)\n\t\n\t// Test GoRoutine\n\tgo mygoroutine(channel_var)\n\tfmt.Println(\"This is after calling goroutine.\")\n\ttime.Sleep(2*time.Second)\n\n\t//testdata := [...] string {\"rak\",\"raj\",\"ram\"}\n\t//channel_var <- \"Rakesh\" //testdata\n\t\n\t// Receive data from string channel\n\tchan_data:=<-channel_var\n\n\tfmt.Println(\"Got from Channel: \",chan_data)\n\n\t// Multiple return values from function\n\ta,b,c := multi_return()\n\tfmt.Println(\"Multi-Return-Values:\",a,b,c)\n}", "func (e *binaryExprEvaluator) C() <-chan map[string]interface{} { return e.c }", "func New(f interface{}, args ...interface{}) *Promise {\n\t// Extract the type\n\tp := &Promise{\n\t\tcond: sync.Cond{L: new(sync.Mutex)},\n\t\tt: simpleCall,\n\t}\n\n\tfunctionRv := reflect.ValueOf(f)\n\n\tif functionRv.Kind() != reflect.Func {\n\t\tpanic(errors.Errorf(\"expected Function, got %s\", functionRv.Kind()))\n\t}\n\n\treflectType := functionRv.Type()\n\n\tinputs := []reflect.Type{}\n\tfor i := 0; i < reflectType.NumIn(); i++ {\n\t\tinputs = append(inputs, reflectType.In(i))\n\t}\n\n\tif len(args) != len(inputs) {\n\t\tpanic(errors.Errorf(\"expected %d args, got %d args\", len(inputs), len(args)))\n\t}\n\n\tp.resultType, p.returnsError = getResultType(reflectType)\n\n\targValues := []reflect.Value{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tprovidedArgRv := reflect.ValueOf(args[i])\n\t\tprovidedArgType := providedArgRv.Type()\n\t\tif providedArgType != inputs[i] {\n\t\t\tpanic(errors.Errorf(\"for argument %d: expected type %s got type %s\", i, inputs[i], providedArgType))\n\t\t}\n\t\targValues = append(argValues, providedArgRv)\n\t}\n\tgo p.run(functionRv, nil, nil, 0, argValues)\n\treturn p\n}", "func (g *Group) Go(runnable func() error) *Task {\n\ttask := &Task{\n\t\tgroup: g,\n\t\tdone: make(chan struct{}),\n\t}\n\ttask.start(runnable)\n\treturn task\n}", "func (m *MockCallResult) Channel() <-chan *Result {\n\targs := m.MethodCalled(\"Channel\")\n\n\tif resultChan := args.Get(0); resultChan != nil {\n\t\treturn resultChan.(<-chan *Result)\n\t}\n\n\treturn nil\n}", "func isPrimeAsync(number int64, channel chan PrimeResult) {\n\n\tresult:= new (PrimeResult)\n\tresult.number= number\n\tresult.prime= isPrime(number)\n\tchannel <- *result\n}", "func main() {\n\t// make a channel\n\tch := make(chan int)\n\t// create a go routine and wrap do something in an anonymous function\n\t// put the value on the channel and then pull it off\n\tgo func() {\n\t\tch <- doSomething(5)\n\t}()\n\tfmt.Println(<-ch)\n}", "func (c *OSContext) Go(t *testing.T, fn func()) {\n\tt.Helper()\n\terrCh := make(chan error, 1)\n\tgo func() {\n\t\tteardown, err := c.Set()\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tdefer teardown(t)\n\t\tclose(errCh)\n\t\tfn()\n\t}()\n\n\tif err := <-errCh; err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n}", "func (wp *Pool) C() <-chan Processor {\n\treturn wp.resultChan\n}", "func (g *Group) Go(f func() error) {\n\t// ...\n}", "func ExamplePromiseStruct_Then() {\n\tstuff := Promise(func() int {\n\t\treturn 3\n\t}).\n\t\tThen(func(x int) (int, error) {\n\t\t\tfmt.Println(x)\n\t\t\treturn x * x, nil\n\t\t}).\n\t\tThen(func(x int) (int, error) {\n\t\t\tfmt.Println(x)\n\t\t\treturn x * x, nil\n\t\t})\n\tfmt.Println(stuff.Result[0])\n\t// Output:\n\t// 3\n\t// 9\n\t// 81\n}", "func (g *Group) Go(f func()) {\n\tg.group.Add(1)\n\tgo func() { f(); g.group.Done() }()\n}", "func CallVal(f func() interface{}) interface{} {\n\tcheckRun()\n\trespChan := make(chan interface{})\n\tcallQueue <- func() {\n\t\trespChan <- f()\n\t}\n\treturn <-respChan\n}", "func NewPromise() Controller {\n\treturn &promise{}\n}", "func (g *Group) Go(fn func() error) {\n\tselect {\n\tcase <-g.ctx.Done():\n\t\treturn\n\tcase g.limiter <- struct{}{}:\n\t}\n\n\tg.parent.Go(func() error {\n\t\terr := fn()\n\n\t\tselect {\n\t\tcase <-g.limiter:\n\t\tcase <-g.ctx.Done():\n\t\t}\n\t\treturn err\n\t})\n}", "func helloGo() {\n\tvar ret = 100\n\tfmt.Println(ret)\n}", "func Go(f func(), nsrefs ...Referrer) error {\n\tstarted := make(chan error)\n\tgo func() {\n\t\t// Lock, but never unlock the OS thread exclusively powering our Go\n\t\t// routine. This ensures that the Golang runtime will destroy the OS\n\t\t// thread and never attempts to reuse it.\n\t\truntime.LockOSThread()\n\t\t// Switch our highly exclusive OS thread into the specified\n\t\t// namespaces...\n\t\tfor _, nsref := range nsrefs {\n\t\t\t// Important: since nsref.Reference() returns a file descriptor\n\t\t\t// which potentially is derived from an open os.File, the latter\n\t\t\t// must not get garbage collected while we attempt to use the file\n\t\t\t// descriptor, as otherwise the os.File's finalizer will have closed\n\t\t\t// the fd prematurely. Luckily (hopefully not!) the (varargs) slice\n\t\t\t// won't be collectible until the iteration terminates, keeping its\n\t\t\t// slice elements and thus its os.Files (if any) alive. In\n\t\t\t// consequence, we don't need an explicit runtime.KeepAlive(...)\n\t\t\t// here.\n\t\t\tfd, close, err := nsref.Reference()\n\t\t\tif err != nil {\n\t\t\t\tstarted <- err\n\t\t\t\treturn // ex-terminate ;)\n\t\t\t}\n\t\t\terr = unix.Setns(fd, 0)\n\t\t\tif close {\n\t\t\t\t// Don't leak open file descriptors...\n\t\t\t\tunix.Close(int(fd))\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tstarted <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Our preparations are finally done, so let's call the desired function and\n\t\t// then call it a day.\n\t\tstarted <- nil\n\t\tf()\n\t}()\n\t// Wait for the goroutine to have finished switching namespaces and about to\n\t// invoke the specified function. We're lazy and are never closing the\n\t// channel, but it will get garbage collected anyway.\n\treturn <-started\n}", "func (r *role) GoHandle(rng *rand.Rand) (h *acceptNextPropHandler, wait func()) {\n\tdone := make(chan struct{})\n\tpropHandler := r.acceptNextPropHandler(rng)\n\tgo func() {\n\t\tdefer close(done)\n\t\tr.log.Info(\"Starting request handler.\")\n\t\tr.Handle(propHandler, r.UpdateHandler())\n\t\tr.log.Debug(\"Request handler returned.\")\n\t}()\n\n\treturn propHandler, func() {\n\t\tr.log.Debug(\"Waiting for request handler to return...\")\n\t\t<-done\n\t}\n}", "func (s *Supervisor) Go(task func(ctx context.Context) error) {\n\ts.wg.Add(1)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\n\t\tif err := task(s.ctx); err != nil {\n\t\t\tif s.onError != nil {\n\t\t\t\ts.onError(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (p *Promise) Force() interface{} {\n\tp.once.Do(func() { p.value = p.f() })\n\treturn p.value\n}", "func (f *future) wait() *future {\n\t<-f.waitCh\n\treturn f\n}", "func mainChannel() {\n\n\tretCanal := make(chan string)\n\n\tgo say(\"world\", retCanal) // retorna uma mensagem no channel retChannel\n\n\tfmt.Println(<-retCanal) // \taqui, a go routine principal esta esperando receber a mensagem do channel retornado pela go routine acima\n}", "func (promise *Promise) Then(fulfillment func(data interface{}) interface{}) *Promise {\n\tpromise.mutex.Lock()\n\tdefer promise.mutex.Unlock()\n\n\tif promise.state == pending {\n\t\tpromise.wg.Add(1)\n\t\tpromise.then = append(promise.then, fulfillment)\n\t} else if promise.state == fulfilled {\n\t\tpromise.result = fulfillment(promise.result)\n\t}\n\n\treturn promise\n}", "func Delay(f func() interface{}) *Promise {\n\treturn &Promise{f: f}\n}", "func (d *deferredErrGroupScheduler) Go(ctx context.Context,\n\tf func() error) string {\n\n\t// build new key\n\tkey := uuid.New().String()\n\t// derive new context from input context\n\tctx, cancelFunc := context.WithCancel(ctx)\n\n\t// map key to the cancel func\n\td.mu.Lock()\n\td.m[key] = cancelFunc\n\td.mu.Unlock()\n\n\tvar trig context.Context\n\tvar trigCancelFunc context.CancelFunc\n\n\tswitch v := d.trig.value.(type) {\n\tcase time.Duration:\n\t\t// create a context based on timeout\n\t\ttrig, trigCancelFunc = context.WithTimeout(context.Background(), v)\n\t\t// spawn a go-routine that will call cancel func once triggered\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-trig.Done():\n\t\t\t\ttrigCancelFunc()\n\t\t\t}\n\t\t}()\n\tcase context.Context:\n\t\ttrig = v\n\t}\n\n\t// spawn func within an error group.\n\td.eg.Go(func() error {\n\t\tselect {\n\t\tcase <-trig.Done():\n\t\t\terr := f()\n\t\t\td.Cancel(key)\n\t\t\treturn err\n\t\tcase <-ctx.Done():\n\t\t\treturn FuncExecCancelled\n\t\t}\n\t})\n\n\treturn key\n}", "func New(executor func(resolve func(interface{}), reject func(error))) *Promise {\n\tvar wg = &sync.WaitGroup{}\n\twg.Add(1)\n\n\tvar promise = &Promise{\n\t\tstate: pending,\n\t\texecutor: executor,\n\t\tthen: make([]func(interface{}) interface{}, 0),\n\t\tcatch: make([]func(error) error, 0),\n\t\tresult: nil,\n\t\terr: nil,\n\t\tmutex: &sync.Mutex{},\n\t\twg: wg,\n\t}\n\n\tgo func() {\n\t\tdefer promise.handlePanic()\n\t\tpromise.executor(promise.resolve, promise.reject)\n\t}()\n\n\treturn promise\n}", "func main() {\n\n\tc_amount_pages := make(chan int)\n\tgo fn_get__amount_pages(c_amount_pages)\n\tint_amount := <- c_amount_pages\n\n\tfn_get__job_infos(int_amount)\n}", "func generate(nums ...int) <-chan int {\n\t// create channel with results\n\tout := make(chan int)\n\n\t// run new gouroutine\n\tgo func() {\n\t\tfor _, n := range nums {\n\t\t\tfmt.Printf(\"Generating value %d \\n\", n)\n\t\t\tout <- n\n\t\t}\n\t\tclose(out)\n\t}()\n\n\t// return result channel immediately (it's empty at that time)\n\treturn out\n}", "func (g *Group) Go(f func() error, index int) {\n\tg.wg.Add(1)\n\tgo func() {\n\t\tdefer g.wg.Done()\n\t\tif g.bucket != nil {\n\t\t\t// Wait for token\n\t\t\tselect {\n\t\t\tcase <-g.bucket:\n\t\t\t\tdefer func() {\n\t\t\t\t\t// Put back token..\n\t\t\t\t\tg.bucket <- struct{}{}\n\t\t\t\t}()\n\t\t\tcase <-g.ctxCancel:\n\t\t\t\tif len(g.errs) > index {\n\t\t\t\t\tatomic.CompareAndSwapInt64(&g.firstErr, -1, int64(index))\n\t\t\t\t\tg.errs[index] = g.ctxErr()\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err := f(); err != nil {\n\t\t\tif len(g.errs) > index {\n\t\t\t\tatomic.CompareAndSwapInt64(&g.firstErr, -1, int64(index))\n\t\t\t\tg.errs[index] = err\n\t\t\t}\n\t\t\tif g.cancel != nil {\n\t\t\t\tg.cancel()\n\t\t\t}\n\t\t}\n\t}()\n}", "func main() {\n\n\t// Create a new channel\n\tmessages := make(chan string)\n\n\t// Send a value into a channel using the channel <- syntax\n\tgo func() { messages <- \"ping\" }()\n\n\tmsg := <-messages\n\tfmt.Println(msg)\n\n}", "func (e Executor) Submit(ctx context.Context, f Func) (interface{}, error) {\n\tresultChan := make(chan *result, 1)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, context.Canceled\n\tcase e <- &Request{\n\t\tFunc: f,\n\t\tContext: ctx,\n\t\tresult: resultChan,\n\t}:\n\t}\n\tres, ok := <-resultChan\n\tif !ok {\n\t\tpanic(\"cgc: result channel closed without any results\")\n\t}\n\treturn res.val, res.err\n}", "func Resolve() {\n\tfmt.Println(\"Exercise 6\")\n\n\tc := make(chan int)\n\n\tgo func(cs chan<- int) {\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tc <- i\n\t\t}\n\t\tclose(cs)\n\t}(c)\n\n\tfor v := range c {\n\t\tfmt.Println(\"Value from channel\", v)\n\t}\n\n\tfmt.Println()\n}", "func (f *Flow) Go() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\n\t\t\tcase request := <-f.addRequest:\n\t\t\t\tf.requests = append(f.requests, request)\n\t\t\t\tf.pollingInterval = minimumPollingInterval(f.requests)\n\t\t\t\trequest.Poll(f.requestQueue)\n\n\t\t\tcase request := <-f.requestQueue:\n\t\t\t\tfmt.Println(time.Now().Format(time.StampMilli), request.GetMessage())\n\t\t\t\t<-time.After(f.pollingInterval)\n\n\t\t\t}\n\t\t}\n\t}()\n}", "func producer() <-chan int {\n\tc := make(chan int)\n\t//...\n\treturn c\n}", "func (*rootMessageProducer) RequestFuture(pid *PID, message interface{}, timeout time.Duration) *Future {\n\treturn pid.RequestFuture(message, timeout)\n}", "func (*rootMessageProducer) RequestFuture(pid *PID, message interface{}, timeout time.Duration) *Future {\n\treturn pid.RequestFuture(message, timeout)\n}", "func (f *FirstErrPromise) Promise() func(*Record, error) {\n\tf.wg.Add(1)\n\treturn f.promise\n}", "func (f *Future) Get() interface{} {\n\treturn <-f.response\n}", "func (p *pipeline) Channel() Channel {\n\treturn p.channel\n}", "func getPromiseOrEmptyPromise(p *Promise) *Promise {\n\tif p != nil {\n\t\treturn p\n\t}\n\tp1 := &Promise{}\n\tp1.channel = make(chan int)\n\tp1.res = nil\n\tp1.err = nil\n\tp1.status = PENDING\n\treturn p1\n}", "func (f WaiterFunc) Wait(ctx context.Context) error {\n\treturn f(ctx)\n}", "func (self Memo) Get() interface{} {\n\tresponse := make(chan interface{})\n\tself.requestChan <- response\n\treturn <-response\n}", "func (promise *Promise) Await() (interface{}, error) {\n\tpromise.wg.Wait()\n\treturn promise.result, promise.err\n}", "func (s *Subscription) C() <-chan interface{} {\n\treturn s.channel\n}", "func example3() {\n\n\t// channel send and receive is blocking function\n\tc := make(chan string)\n\tgo count(\"sheep\", c)\n\tfor {\n\t\t//\n\t\tmsg, open := <-c // receive value from the channel, if channel is empty, blocking happen\n\t\t// if channel is closed, break the loop\n\t\tif !open {\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(msg)\n\t}\n}", "func RoutinesWaitChannel() {\n\tlog.Println(\"Started.\")\n\n\t// var donea chan bool doesn't work!\n\tdonea := make(chan bool)\n\tdoneb := make(chan bool)\n\n\tgo rwc(\"a\", donea)\n\tgo rwc(\"b\", doneb)\n\n\t<- donea\n\t<- doneb\n\n\tclose(donea)\n\tclose(doneb)\n\n\tlog.Println(\"Done.\")\n}", "func Go(task func()) {\n\tif gLimitedCounter == nil {\n\t\tonce.Do(func() {\n\t\t\tgLimitedCounter = NewLimitedCounter(defaultSize)\n\t\t})\n\n\t}\n\n\tgLimitedCounter.ApplyOne()\n\tgo func() {\n\t\tdefer gLimitedCounter.ReturnOne()\n\t\ttask()\n\t}()\n}", "func runNaiveGoRoutine(gr g.Graph, poolSize int, debug int, c chan g.Graph) {\n\tc <- RunNaive(gr, poolSize, debug)\n}", "func WrapInPromise(f func() (interface{}, error)) js.Value {\n\tvar executor js.Func\n\texecutor = js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tresolve := args[0]\n\t\treject := args[1]\n\t\tgo func() {\n\t\t\tdefer executor.Release()\n\t\t\tif result, err := f(); err != nil {\n\t\t\t\treject.Invoke(ErrorToJS(err))\n\t\t\t} else {\n\t\t\t\tresolve.Invoke(result)\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t})\n\treturn js.Global().Get(\"Promise\").New(executor)\n}", "func (p *promise) Then(promise Promise) Promise {\n\treturn p.Thenf(func() Promise { return promise })\n}", "func main() {\n\t// making a channel\n\tc := make(chan int)\n\n\t// putting values on a channel\n\tc <- 42\n\n\t// taking values off a channel\n\tfmt.Println(<-c)\n}", "func callGreet() {\n\tc := make(chan string)\n\tgo Greet(c) //start new goroutine,ready state\n\tc <- \"zhang sir\"\n}", "func (s *Service) Exec(job interface{}) {\n\n\ts.Lock.RLock()\n\t// In case this routine has to wait for the calculation routine:\n\tif s.InProgress[job] {\n\n\t\t// Make a new channel (reader)\n\t\ts.Lock.RUnlock()\n\t\tresponse := make(chan interface{})\n\t\tdefer close(response)\n\n\t\t// Append the reader to its respective queue (regarding to the job)\n\t\ts.Lock.Lock()\n\t\ts.PendingReaders[job] = append(s.PendingReaders[job], response)\n\t\ts.Lock.Unlock()\n\n\t\t// The reader now only has to wait for the result of the routine\n\t\t// that is calculating the result for the required job\n\t\tfmt.Printf(\"Waiting for Response job: %d\\n\", job)\n\t\tresp := <-response\n\t\tfmt.Printf(\"Response Done, received %d\\n\", resp)\n\t\treturn\n\t}\n\n\t// In case this routine is the one to perform the calculation:\n\n\ts.Lock.RUnlock()\n\ts.Lock.Lock()\n\n\t// Flag to tell other routines that the required job is being calculated\n\ts.InProgress[job] = true\n\ts.Lock.Unlock()\n\n\tfmt.Printf(\"Performing expensive function for job %d\\n\", job)\n\tresult := s.f(job)\n\n\t// Once finished the function call, recall the channels\n\t// to send the result to\n\ts.Lock.RLock()\n\tpendingWorkers, inProgress := s.PendingReaders[job]\n\ts.Lock.RUnlock()\n\n\t// Send the message to all routines via channels\n\tif inProgress {\n\t\tfor _, pendingWorker := range pendingWorkers {\n\t\t\tpendingWorker <- result\n\t\t}\n\t\tfmt.Printf(\"Result sent - all pending workers ready job:%d\\n\", job)\n\t}\n\n\t// Free in-progess flag and delete all readers\n\ts.Lock.Lock()\n\ts.InProgress[job] = false\n\ts.PendingReaders[job] = make([]chan interface{}, 0)\n\ts.Lock.Unlock()\n}", "func (np *NodePromise) Get(ctx context.Context) (Node, error) {\n\tselect {\n\tcase <-np.done:\n\t\treturn np.value, np.err\n\tcase <-np.ctx.Done():\n\t\treturn nil, np.ctx.Err()\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}", "func boring4(msg string, waitForIt chan bool) <-chan Message { // Returns receive-only channel of strings.\n\tc := make(chan Message)\n\tgo func() { // We launch the goroutine from inside the function.\n\t\tfor i := 0; ; i++ {\n\t\t\tc <- Message{fmt.Sprintf(\"%s: %d\", msg, i), waitForIt}\n\t\t\ttime.Sleep(time.Duration(rand.Intn(2e3)) * time.Millisecond)\n\t\t\t//这里会堵塞,等待消费者先消费先\n\t\t\t// Each speaker must wait for a go-ahead.\n\t\t\t<-waitForIt\n\t\t}\n\t}()\n\treturn c // Return the channel to the caller.\n}", "func Spawn(f func()) sync.Locker {\r\n\tdone := NewDone() // created in locked state\r\n\tgo func() {\r\n\t\tf()\r\n\t\tdone.Unlock()\r\n\t} ()\r\n\treturn done\r\n}", "func jumlah(a, b int, c chan bool) {\n\ttime.Sleep(2 * time.Second)\n\tfmt.Println(a, b, a+b)\n\tc <- true // artinya akan menerima nilai\n}", "func foo(c chan int, someValue int) {\n\t// Send value over channel, don't return anything\n\tc <- someValue * 5\n}", "func (*Go) Dispose() {}", "func Resolve(resolution interface{}) *Promise {\n\treturn New(func(resolve func(interface{}), reject func(error)) {\n\t\tresolve(resolution)\n\t})\n}" ]
[ "0.6992752", "0.6992752", "0.61629105", "0.60897183", "0.60897183", "0.6083577", "0.6016385", "0.59572494", "0.59428996", "0.59207195", "0.5909397", "0.5888332", "0.5833589", "0.5795857", "0.57485086", "0.57162493", "0.567959", "0.56691086", "0.56540793", "0.5620747", "0.56103504", "0.5595385", "0.55866796", "0.5577493", "0.55502117", "0.5529397", "0.55240667", "0.55117935", "0.54395866", "0.5429109", "0.540355", "0.5343054", "0.53067404", "0.5280576", "0.5266667", "0.52521104", "0.5242589", "0.52179456", "0.51965225", "0.5194995", "0.5173371", "0.51642126", "0.5150793", "0.51392156", "0.51197267", "0.5117301", "0.5107618", "0.5077008", "0.50764465", "0.5057344", "0.50465405", "0.5030744", "0.5021343", "0.50199133", "0.5005285", "0.49791166", "0.49641696", "0.49530572", "0.49434063", "0.49265006", "0.49205142", "0.4919603", "0.48932776", "0.48916948", "0.48860392", "0.48848063", "0.48737788", "0.48585722", "0.48487592", "0.48441824", "0.48321098", "0.4825294", "0.48252916", "0.48126027", "0.4801121", "0.4801121", "0.47704262", "0.4762218", "0.4757933", "0.4755175", "0.47548026", "0.47392505", "0.47379047", "0.47297418", "0.4728084", "0.47198784", "0.47147945", "0.47048718", "0.470371", "0.47026685", "0.46939707", "0.4685613", "0.46672237", "0.46615547", "0.46563372", "0.46450463", "0.464024", "0.46341085", "0.46307403", "0.46232182" ]
0.7003164
0
Request a given URL and return an io.Reader
func Download(url string) (resp *http.Response, err error) { if resp, err = http.Get(url); err != nil { return nil, err } if resp.StatusCode >= 400 { return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status) } return resp, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func readerFromURL(url string) io.ReadCloser {\n\tfmt.Println(fmt.Sprintf(\"Getting: %s\", url))\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Couldn't download file %s: %s\", url, err))\n\t}\n\n\tfileBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Unable to read file to bytes %s: %s\", url, err))\n\t}\n\tresp.Body.Close()\n\n\treturn ioutil.NopCloser(bytes.NewReader(fileBytes))\n}", "func readFromURL(url string, writer io.Writer) error {\n\thttpTransport := new(http.Transport)\n\thttpTransport.Proxy = http.ProxyFromEnvironment\n\n\tc := &http.Client{Transport: httpTransport}\n\tr, err := c.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Body.Close()\n\tif r.StatusCode >= 400 {\n\t\treturn fmt.Errorf(\"%v returned %d\", url, r.StatusCode)\n\t}\n\t_, err = io.Copy(writer, r.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif header != nil {\n\t\treq.Header = *header\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tklog.V(2).InfoS(\"Failed to read URL\", \"statusCode\", resp.StatusCode, \"URL\", url)\n\t\treturn nil, &HTTPError{\n\t\t\tStatusCode: resp.StatusCode,\n\t\t\tURL: url,\n\t\t}\n\t}\n\n\tlimitedReader := &io.LimitedReader{R: resp.Body, N: maxReadLength}\n\tcontents, err := io.ReadAll(limitedReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif limitedReader.N <= 0 {\n\t\treturn nil, errors.New(\"the read limit is reached\")\n\t}\n\n\treturn contents, nil\n}", "func ReadURL(url string) ([]byte, error) {\n response, err := http.Get(url)\n if err != nil {\n return nil, err\n }\n context, err := ioutil.ReadAll(response.Body)\n response.Body.Close()\n return context, err\n}", "func GetContentReader(url string) (io.ReadCloser, error) {\n\t// http.Get() allows up to 10 redirects\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode/100 != 2 {\n\t\treturn nil, errors.New(url + \" returned non-successful status: \" + res.Status)\n\t}\n\treturn res.Body, nil\n}", "func Request(url string) ([]byte, error) {\n\tvar err error\n\tclient := resty.New()\n\n\tresponse, err := client.R().Get(url)\n\n\tbytes := []byte(response.Body())\n\n\treturn bytes, err\n}", "func ReadUrl(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.New(url + \": \" + resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\t// log.Println(url + \":\", string(body))\n\n\treturn body, err\n}", "func Read(urlPath string) (*bytes.Buffer, error) {\n\n\tresponse, err := coreHTTP.Get(urlPath) // nolint:gosec\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif response != nil {\n\t\tdefer response.Body.Close()\n\t}\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &buf, nil\n}", "func performRequest(url string) (io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\tdefer func() {\n\t\t\tif err := resp.Body.Close(); err != nil {\n\t\t\t\tlog.Warnf(\"Failed to close response body: %s\", err)\n\t\t\t}\n\t\t}()\n\n\t\tresponseBytes, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"non success response code: %d, body: %s\", resp.StatusCode, string(responseBytes))\n\t}\n\n\treturn resp.Body, nil\n}", "func Get(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"wrong status code %d\\n\", resp.StatusCode)\n\t}\n\n\t//change io.Reader to bufio.Reader\n\tr := bufio.NewReader(resp.Body)\n\te := determinEncoding(r)\n\tuf8Reader := transform.NewReader(r, e.NewDecoder())\n\treturn ioutil.ReadAll(uf8Reader)\n}", "func Get(url string) ([]byte, error) {\n\trsp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\tdefer rsp.Body.Close()\n\treturn ioutil.ReadAll(rsp.Body)\n}", "func Get(url string) ([]byte, error) {\n\tclient := http.Client{\n\t\tTimeout: time.Second * 3,\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tdata, err := ioutil.ReadAll(resp.Body)\n\n\treturn data, err\n}", "func (c *Client) Open(rawurl, method string, in, out interface{}) (io.ReadCloser, error) {\n\turi, err := url.Parse(rawurl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(method, uri.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif in != nil {\n\t\tdecoded, derr := json.Marshal(in)\n\t\tif derr != nil {\n\t\t\treturn nil, derr\n\t\t}\n\t\tbuf := bytes.NewBuffer(decoded)\n\t\treq.Body = ioutil.NopCloser(buf)\n\t\treq.ContentLength = int64(len(decoded))\n\t\treq.Header.Set(\"Content-Length\", strconv.Itoa(len(decoded)))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\tresp, err := c.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode > http.StatusPartialContent {\n\t\tdefer resp.Body.Close()\n\t\tout, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"client error %d: %s\", resp.StatusCode, string(out))\n\t}\n\treturn resp.Body, nil\n}", "func getStreamFromURL(fileURI string) (io.ReadCloser, error) {\n\turl, err := url.Parse(fileURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch url.Scheme {\n\tcase \"http\", \"https\":\n\t\tresp, err := http.Get(fileURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp.Body, nil\n\tcase \"file\", \"\":\n\t\tf, err := os.Open(fileURI)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn f, nil\n\tdefault:\n\t\treturn nil, errors.New(\"URL Not supported\")\n\t}\n}", "func (e *EmailGetter) Request(url string) []byte {\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\treq.Header.Set(\"DNT\", \"1\")\n\treq.Header.Set(\"Connection\", \"keep-alive\")\n\treq.Header.Set(\"Upgrade-Insecure-Requests\", \"1\")\n\treq.Header.Set(\"Accept-Language\", \"en-US,en;q=0.8\")\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (KHTML, like Gecko) Safari/537.36\")\n\treq.Header.Set(\"Accept\", \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\t// I understand that ioutil.ReadAll is bad.\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn content\n}", "func readurl(url string) (data string, err error) {\n\tvar resp *http.Response\n\tresp, err = http.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\n\t// read data from url\n\tvar bytes []byte\n\tbytes, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata = string(bytes)\n\treturn\n}", "func GetURL(url string) (reply []byte, err error) {\n\tcli := &http.Client{\n\t\tTimeout: RequestTimeout * time.Second,\n\t}\n\tresp, err := cli.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\treply, err = ioutil.ReadAll(resp.Body)\n\treturn\n}", "func getRead(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, resp.Body.Close()\n}", "func Get(url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuner ...func(*http.Request)) error {\n\treturn Request(\"GET\", url, r, w, clientGenerator, reqTuner...)\n}", "func getHttp(url url.URL) (io.ReadCloser, error) {\n\tresp, err := http.Get(url.String())\n\tif err != nil {\n\t\tlog.Printf(\"HTTP failed to GET url=%s. error=%s\\n\", url.String(), err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func ReadURLContents(targetURL string) ([]byte, error) {\n\tresp, err := http.Get(targetURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"response status code is %v\", resp.StatusCode)\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading response body failed: %v\", err)\n\t}\n\n\treturn b, nil\n}", "func RequestWithURL(task *Task) (io.Reader, error) {\n\treq, err := http.NewRequest(\"GET\", task.Url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Println(fmt.Sprintf(\"%s [%d]\", task.Url, resp.StatusCode))\n\ttask.Context.Request = req\n\ttask.Context.Response = resp\n\treturn resp.Body, nil\n}", "func Open(url string, signer s3.Signer) (io.ReadCloser, error) {\n\tif signer == nil {\n\t\tsigner = DefaultConfig\n\t}\n\t// TODO(kr): maybe parallel range fetching\n\tr, _ := http.NewRequest(\"GET\", url, nil)\n\tr.Header.Set(\"Date\", time.Now().UTC().Format(http.TimeFormat))\n\tsigner.Sign(r)\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, newRespError(resp)\n\t}\n\treturn resp.Body, nil\n}", "func GetBodyFromURL(url string, client *http.Client) ([]byte, error) {\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer util.Close(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to load: %s\", resp.Status)\n\t}\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (api *API) GetReader(path string) (r io.Reader, statusCode int, err error) {\n\treq, err := http.NewRequest(\"GET\", api.host+path, nil)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn api.do(req)\n}", "func (p Parser) GetContents(url string, limit int) (string, error) {\n p.client = &http.Client{}\n resp, err := p.client.Get(url)\n if err != nil {\n return \"\", err\n }\n defer resp.Body.Close()\n\n if resp.StatusCode != http.StatusOK {\n return \"\", fmt.Errorf(\"Http code returned: %d\", resp.StatusCode)\n }\n\n data, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n return \"\", err\n }\n\n str := string(data)\n if limit > 0 {\n str = str[:limit]\n }\n\n return str, nil\n}", "func Request(method string, url url.URL, headers map[string]string) ([]byte, error) {\n\t// Custom request\n\treq, err := http.NewRequest(method, url.String(), strings.NewReader(\"q=test&b=\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Custom headers\n\tfor key, val := range headers {\n\t\treq.Header.Add(key, val)\n\t}\n\n\t// Makes request\n\tclient := http.DefaultClient\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If status code isn't 2xx\n\tif resp.StatusCode/100 != http.StatusOK/100 {\n\t\treturn nil, fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\t// Answer reading\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func readFileAtURL(url string) ([]byte, error) {\n\tclient := &http.Client{}\n\tlog.Printf(\"Fetching file at %q\", url)\n\treq, _ := http.NewRequest(http.MethodGet, url, nil)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"Request failed: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Request returned non-OK status: %s\", resp.Status)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Could not read file contents: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}", "func FromURL(url *nurl.URL, timeout time.Duration) (Article, error) {\n\t// Fetch page from URL\n\tclient := &http.Client{Timeout: timeout}\n\tresp, err := client.Get(url.String())\n\tif err != nil {\n\t\treturn Article{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Check content type. If not HTML, stop process\n\tcontentType := resp.Header.Get(\"Content-type\")\n\tif contentType == \"\" {\n\t\tcontentType = \"application/octet-stream\"\n\t}\n\n\tif !strings.HasPrefix(contentType, \"text/html\") {\n\t\treturn Article{}, fmt.Errorf(\"URL must be a text/html, found %s\", contentType)\n\t}\n\n\t// Parse response body\n\treturn FromReader(resp.Body, url)\n}", "func performRequest(url string) ([]byte, error) {\n\tres, err := http.Get(url)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func get(url string) ([]byte, 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\", userAgent)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"got status code: %s\", resp.Status)\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func read(url string, c chan *gofeed.Feed) {\n\tresp, err := request(url)\n\n\tif err != nil {\n\t\tc <- nil\n\t\treturn\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\tc <- nil\n\t\t\treturn\n\t\t}\n\n\t\tbodyString := string(bodyBytes)\n\t\tlogrus.WithField(\"body\", bodyString).Error(resp.Status)\n\t\tc <- nil\n\t\treturn\n\t}\n\n\tc <- parseRequest(resp)\n}", "func getURLContent(url string) ([]byte, error) {\n\tdur, err := time.ParseDuration(TimeoutDur)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tclient := http.Client{Timeout: dur}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn []byte{}, err\n\n\t}\n\tdefer resp.Body.Close()\n\treturn body, err\n\n}", "func (reader) ReadFromURL(url string) (img image.Image, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil || resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(\"The image url provided is invalid\")\n\t}\n\tdefer resp.Body.Close()\n\timg, _, err = image.Decode(resp.Body)\n\treturn\n}", "func (c *TLWClient) Open(ctx context.Context, gsURL string) (io.ReadCloser, error) {\n\turl, err := c.Stage(ctx, gsURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpReq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create new HTTP request: %s\", url)\n\t}\n\thttpReq = httpReq.WithContext(ctx)\n\n\tres, err := defaultHTTPClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get from download URL: %s\", url)\n\t}\n\n\tswitch res.StatusCode {\n\tcase http.StatusOK:\n\t\treturn res.Body, nil\n\tcase http.StatusNotFound:\n\t\tres.Body.Close()\n\t\treturn nil, os.ErrNotExist\n\tdefault:\n\t\tres.Body.Close()\n\t\treturn nil, fmt.Errorf(\"got status %d %v\", res.StatusCode, httpReq)\n\t}\n}", "func Get(url string) (*Feed, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, HTTPError(resp.StatusCode)\n\t}\n\n\treturn Read(resp.Body)\n}", "func GetResponse(url string) []byte {\n resp, err := http.Get(url)\n\n // handle the error if there is one\n if err != nil {\n panic(err)\n }\n\n // do this now so it won't be forgotten\n defer resp.Body.Close()\n\n // reads html as a slice of bytes\n html, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n panic(err)\n }\n\n return html\n}", "func Request(method string, url string, payload io.Reader) (*http.Response, error) {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(method, url, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.Do(req)\n}", "func (c *Client) Get(url string, header map[string]string) ([]byte, error) {\n\treq, err := c.newRequest(\"GET\", url, header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bytes, nil\n}", "func (c Client) request(method string, u *url.URL, body io.Reader) (io.ReadCloser, error) {\n\treq, err := http.NewRequest(method, u.String(), body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating request failed: %s\", err.Error())\n\t}\n\treq.Header.Add(tokenHeader, c.token)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed: %s\", err.Error())\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"status code: %d, message: %s\", resp.StatusCode, decodeError(resp.Body))\n\t}\n\n\treturn resp.Body, nil\n}", "func netread(url string) (io.ReadCloser, error) {\n\tclient := &http.Client{Timeout: 30 * time.Second}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"unable to retreive network data for %s (%s)\", url, resp.Status)\n\t}\n\treturn resp.Body, nil\n}", "func Get(rURL string, params map[string]string) (io.ReadCloser, error) {\n\n\t// Prepare GET request\n\treq, err := http.NewRequest(\"GET\", rURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create request: %s\", err)\n\t}\n\n\t// Add request options\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tq := req.URL.Query()\n\n\tfor k, v := range params {\n\t\tq.Add(k, v)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\t// Send the request\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to send request to the server: %s\", err)\n\t}\n\treturn resp.Body, nil\n}", "func (d *realDownloader) Get(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get for %v failed: %v\", url, err)\n\t}\n\tdefer resp.Body.Close()\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read body: %v\", err)\n\t}\n\treturn respBytes, nil\n}", "func getPage(url string) (body io.ReadCloser) {\n\t// Retrieve the page\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatalf(\"Response Error: %v\", err)\n\t}\n\tresp.Close = true\n\tbody = resp.Body\n\treturn\n}", "func fetch(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to read from URL\")\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (h *HTTPConventionReader) Reader(year int, promotion string) (io.Reader, error) {\n\t//only in dev mode\n\t\ttr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t\tclient := &http.Client{Transport : tr}\n\t/* in non dev mode}\n\telse{\n\t\tclient := &http.Client{}\n\t}*/\n\tclient.Timeout = time.Duration(10) * time.Second\n\tquery := fmt.Sprintf(\"%s%s&parcours=*\", h.url, promotion)\n\treq, err := http.NewRequest(\"GET\", query, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(h.login, h.password)\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode != 200 {\n\t\treturn nil, errors.New(\"Unexpected response status: \" + res.Status)\n\t}\n\tif h.Encoding == \"windows-1252\" {\n\t\treturn charmap.Windows1252.NewDecoder().Reader(res.Body), nil\n\t}\n\tif h.Encoding == \"UTF-8\" {\n\t\treturn unicode.UTF8.NewDecoder().Reader(res.Body), nil\n\t}\n\treturn nil, errors.New(\"Unsupported encoding: \" + h.Encoding)\n}", "func GetResource(uri string) (io.ReadCloser, error) {\n\tvar file io.ReadCloser\n\tif strings.HasPrefix(uri, \"http://\") || strings.HasPrefix(uri, \"https://\") {\n\t\tresp, err := http.Get(uri)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, errors.Errorf(\"http GET returned status %d for resource %s\", resp.StatusCode, uri)\n\t\t}\n\n\t\tfile = resp.Body\n\t} else {\n\t\tpath, err := filepath.Abs(uri)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"getting absolute path for %v\", uri)\n\t\t}\n\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"opening file %v\", path)\n\t\t}\n\t\tfile = f\n\t}\n\n\t// Write the body to file\n\treturn file, nil\n}", "func Get(c http.Client, url string) Result {\n\tres, err := c.Get(url)\n\tif err != nil {\n\t\treturn Result{url, \"\", nil, &ErrResult{err}}\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn Result{url, \"\", res, &ErrResult{err}}\n\t}\n\n\tif contentTypes, ok := res.Header[\"Content-Type\"]; ok {\n\t\treturn Result{url, Format(contentTypes[0], body), res, nil}\n\t} else {\n\t\treturn Result{url, Format(\"\", body), res, nil}\n\t}\n\n\tpanic(\"unreachable\")\n}", "func (c Crawler) getPage(url string) (io.ReadCloser, error) {\n res, err := http.Get(url)\n if err != nil {\n return nil, err\n }\n if res.StatusCode != 200 {\n return nil, errors.New(\"Page not available\")\n }\n return res.Body, err\n}", "func NewHTTPReader(\n\tproxy *url.URL,\n\tpath string,\n\taccountID int,\n\tlicenseKey string,\n\tretryFor time.Duration,\n\tverbose bool,\n) Reader {\n\ttransport := http.DefaultTransport\n\tif proxy != nil {\n\t\tproxyFunc := http.ProxyURL(proxy)\n\t\ttransport.(*http.Transport).Proxy = proxyFunc\n\t}\n\n\treturn &HTTPReader{\n\t\tclient: &http.Client{Transport: transport},\n\t\tpath: path,\n\t\taccountID: accountID,\n\t\tlicenseKey: licenseKey,\n\t\tretryFor: retryFor,\n\t\tverbose: verbose,\n\t}\n}", "func Request(url string, target interface{}) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn json.NewDecoder(resp.Body).Decode(target)\n}", "func get(cacheDir, url string) ([]byte, error) {\n\tclient := grab.NewClient()\n\treq, err := grab.NewRequest(cacheDir, url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp := client.Do(req)\n\t<-resp.Done\n\treturn ioutil.ReadFile(resp.Filename)\n}", "func Fetch(url string) ([]byte, error) {\n\trequest, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.Header.Add(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER\")\n\tresp, err := http.DefaultClient.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"wrong status code %d\\n\", resp.StatusCode)\n\t}\n\n\t//change io.Reader to bufio.Reader\n\tr := bufio.NewReader(resp.Body)\n\te := determinEncoding(r)\n\tuf8Reader := transform.NewReader(r, e.NewDecoder())\n\treturn ioutil.ReadAll(uf8Reader)\n}", "func Request(baseURL string, uri string) (int, []byte) {\n\tu, err := url.Parse(baseURL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.Path = path.Join(u.Path, uri)\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\t<-time.After(time.Second)\n\t\t\tresp, err = http.Get(u.String())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\tdefer resp.Body.Close()\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn resp.StatusCode, b\n}", "func _getReal(url string) (content []byte, err error) {\n\tvar req *http.Request\n\treq, err = http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tApplyHeaders(req, global.Conf.TranslatorAPIHeaders)\n\n\tvar resp *http.Response\n\tresp, err = http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn ioutil.ReadAll(resp.Body)\n}", "func MakeRequest(url string, ch chan string) {\n\ttimeOver := time.Duration(200 * time.Millisecond)\n\tclient := http.Client{\n\t\tTimeout: timeOver,\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tch <- string(body)\n}", "func (c *Client) Get(url string) (*http.Response, 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\", c.UserAgent)\n\n\tresp, err := c.client.Do(req)\n\treturn resp, err\n}", "func ReadRequest(path string) (req *Request) {\n\tvar content string\n\tvar err error\n\n\tif strings.HasPrefix(path, \"http\") {\n\t\tcontent, err = readurl(path)\n\t} else {\n\t\tcontent, err = readfile(path)\n\t}\n\n\treq = NewRequest(content).Report(err)\n\n\treturn\n}", "func Open(url string) (*Stream, error) {\n\tlog.Print(\"[INFO] Opening \", url)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"accept\", \"*/*\")\n\treq.Header.Add(\"user-agent\", \"iTunes/12.9.2 (Macintosh; OS X 10.14.3) AppleWebKit/606.4.5\")\n\treq.Header.Add(\"icy-metadata\", \"1\")\n\n\t// Timeout for establishing the connection.\n\t// We don't want for the stream to timeout while we're reading it, but\n\t// we do want a timeout for establishing the connection to the server.\n\tdialer := &net.Dialer{Timeout: 5 * time.Second}\n\ttransport := &http.Transport{Dial: dialer.Dial}\n\tclient := &http.Client{Transport: transport}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range resp.Header {\n\t\tlog.Print(\"[DEBUG] HTTP header \", k, \": \", v[0])\n\t}\n\n\tbitrate, err := strconv.Atoi(resp.Header.Get(\"icy-br\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse bitrate: %v\", err)\n\t}\n\n\tmetaint, err := strconv.Atoi(resp.Header.Get(\"icy-metaint\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse metaint: %v\", err)\n\t}\n\n\ts := &Stream{\n\t\tName: resp.Header.Get(\"icy-name\"),\n\t\tGenre: resp.Header.Get(\"icy-genre\"),\n\t\tDescription: resp.Header.Get(\"icy-description\"),\n\t\tURL: resp.Header.Get(\"icy-url\"),\n\t\tBitrate: bitrate,\n\t\tmetaint: metaint,\n\t\tmetadata: nil,\n\t\tpos: 0,\n\t\trc: resp.Body,\n\t}\n\n\treturn s, nil\n}", "func (c *Crawler) getPageContents(url string) (io.ReadCloser, error) {\n\tresponse, err := c.client.getResponse(url)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to fetch URL: %v\", c.hostnameWithProtocol)\n\t}\n\tif response != nil {\n\t\treturn response.Body, nil\n\t}\n\treturn nil, errors.Errorf(\"unable to read response body for URL %v\", url)\n}", "func (r *HTTPRetriever) retrieve(url string) []byte {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: %v\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\treturn body\n}", "func (c *Client) Get(url string) (*Response, error) {\n\treq, err := c.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq = c.Config.AddRequestHeader(req)\n\tresponse, err := c.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n}", "func FetchFromURI(uri string, limit int64) ([]byte, error) {\n\tresponse, err := http.Get(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\treturn ioutil.ReadAll(io.LimitReader(response.Body, limit))\n}", "func LoadFromHttp(source string) ([]byte, error) {\n\tvar resp *http.Response\n\n\tif !(strings.HasPrefix(source, \"http://\") || strings.HasPrefix(source, \"https://\")) {\n\t\treturn nil, WrongFormatError\n\t}\n\n\t// Create custom http transport\n\t// From: https://www.loginradius.com/blog/async/tune-the-go-http-client-for-high-performance/\n\thttpTransport := http.DefaultTransport.(*http.Transport).Clone()\n\thttpTransport.MaxIdleConns = 10\n\thttpTransport.MaxConnsPerHost = 10\n\thttpTransport.IdleConnTimeout = 60 * time.Second\n\thttpTransport.MaxIdleConnsPerHost = 10\n\thttpTransport.ResponseHeaderTimeout = httpResponseHeadersTimeout\n\n\t// Prepare request\n\tclient := http.Client{\n\t\tTransport: httpTransport,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", source, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Execute request\n\tctx, ctxCancel := context.WithTimeout(context.Background(), httpRequestTimeout)\n\tdefer ctxCancel()\n\tresp, err = client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if the request succeeded\n\tif resp.StatusCode != 200 {\n\t\t_ = resp.Body.Close()\n\n\t\treturn nil, fmt.Errorf(\"unexpected HTTP status code [http-status=%v]\", resp.Status)\n\t}\n\n\t// Read response body\n\tvar responseBody []byte\n\tresponseBody, err = ioutil.ReadAll(resp.Body)\n\t_ = resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Done\n\treturn responseBody, nil\n}", "func request(searchURL string) (*http.Response, error) {\r\n\r\n\tbaseClient := &http.Client{}\r\n\treq, _ := http.NewRequest(\"GET\", searchURL, nil)\r\n\treq.Header.Set(\"User-Agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\")\r\n\r\n\tres, err := baseClient.Do(req)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn res, nil\r\n}", "func NewFromURL(url string) (r *Recipe, err error) {\n\tclient := http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\thtml, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn NewFromHTML(url, string(html))\n}", "func FetchURL(url string) []byte {\n\tresp, err := http.Get(url)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tlog.Fatalf(\"Error fetching URL '%s': %s\", url, err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading body: %s\", err)\n\t}\n\treturn body\n}", "func GetContent(url string) ([]byte, error) {\n\tr, err := GetContentReader(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\treturn ioutil.ReadAll(r)\n}", "func (t *TestRuntime) GetData(url string) (io.ReadCloser, error) {\n\treturn t.request(\"GET\", url, nil)\n}", "func GetData(url string) []byte {\n\tlog.Println(\"getting data from URL: \", url)\n\n\tvar body []byte\n\n\t// define client with timeout of 10 seconds\n\tvar netClient = &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tresp, err := netClient.Get(url)\n\tdefer resp.Body.Close()\n\tif err != nil{\n\t\tlog.Println(err)\n\t\treturn []byte(\"\")\n\t}\n\n\t// check for gzip data, unzip if needed\n\tif strings.Contains(url, \".gz\") {\n\t\tlog.Println(\"content encoded with gzip\")\n\t\tbody = GUnzip(resp.Body)\n\t} else {\n\t\tlog.Println(\"content not encoded\")\n\t\tbody, err = ioutil.ReadAll(resp.Body)\n\t\tcheck(err)\n\t}\n\n\tlog.Println(\"data received\")\n\treturn body\n}", "func Read(url string, timeout time.Duration) (res *Response) {\n\tdone := make(chan *Response)\n\n\t// create a function pointer.\n\tworker := func(ch chan *Response) {\n\t\t//a new response is created in Get() and as long there's an reference to the object, the GC will not take it away.\n\t\tresp := Get(url)\n\t\t//200 is the http code for success.\n\t\t//http.StatusOK = 200\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn\n\t\t}\n\t\t//send the response.\n\t\tch <- resp\n\t}\n\t//launch goroutine to do the work.\n\tgo worker(done)\n\n\t//listen on values on the channel.\n\tselect {\n\tcase resp := <-done:\n\t\treturn resp\n\t//if the server is to slow...\n\tcase <-time.After(timeout):\n\t\treturn &Response{\"Gateway timeout\", http.StatusGatewayTimeout}\n\t}\n}", "func URL(url string) error {\n\treturn open(url)\n}", "func GetURL(url string) ([]byte, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func read(path string) ([]io.Reader, error) {\n\tif path == \"-\" {\n\t\treturn []io.Reader{os.Stdin}, nil\n\t}\n\n\tif url, ok := toURL(path); ok {\n\t\tif strings.ToLower(url.Scheme) != \"https\" {\n\t\t\treturn nil, fmt.Errorf(\"only HTTPS URLs are allowed\")\n\t\t}\n\t\tresp, err := http.Get(url.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn nil, fmt.Errorf(\"unable to read URL %q, server reported %s, status code=%d\", path, resp.Status, resp.StatusCode)\n\t\t}\n\n\t\t// Save to a buffer, so that response can be closed here\n\t\tbuf := new(bytes.Buffer)\n\t\t_, err = buf.ReadFrom(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn []io.Reader{buf}, nil\n\t}\n\n\treturn walk(path)\n}", "func contentFromServer(url string) string {\n resp, err := http.Get(url)\n checkError(err)\n\n defer resp.Body.Close()\n bytes, err := ioutil.ReadAll(resp.Body)\n checkError(err)\n\n return string(bytes)\n}", "func Request(method string, url string, r io.Reader, w io.Writer, clientGenerator func() *http.Client, reqTuners ...func(*http.Request)) error {\n\treq, err := http.NewRequest(method, url, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, reqTuner := range reqTuners {\n\t\treqTuner(req)\n\t}\n\n\tvar client *http.Client\n\tif clientGenerator == nil {\n\t\tclient = new(http.Client)\n\t} else {\n\t\tclient = clientGenerator()\n\t}\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treason, err := Reason(res)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn errors.New(reason)\n\t}\n\n\tif w == nil {\n\t\t_, err = io.Copy(devnull, res.Body)\n\t} else {\n\t\t_, err = io.Copy(w, res.Body)\n\t}\n\n\treturn err\n}", "func (c *Client) Get(rawurl string, out interface{}) error {\n\treturn c.Do(rawurl, \"GET\", nil, out)\n}", "func linkOpen(URL string) (io.ReadCloser, error) {\n\tresp, err := http.Get(URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"HTTP Get failed: %v\", resp.StatusCode)\n\t}\n\treturn resp.Body, nil\n}", "func getHTTP(uri string, sslVerify bool, timeout time.Duration) (io.ReadCloser, error) {\n\ttr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}}\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: tr,\n\t\tCheckRedirect: redirectPolicyFunc,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", uri, nil)\n\treq.Header.Add(\"Authorization\", \"Basic \"+globalBasicAuthString)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !(resp.StatusCode >= 200 && resp.StatusCode < 300) {\n\t\tresp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"HTTP status %d\", resp.StatusCode)\n\t}\n\treturn resp.Body, nil\n}", "func (c *Client) Request(ctx context.Context, endpoint string) (io.Reader, error) {\n\treq, err := http.NewRequest(\"GET\", c.baseURL+endpoint, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot create http get request\")\n\t}\n\treq = req.WithContext(ctx)\n\n\tacceptHeader := \"application/json\"\n\ttimestamp := time.Now().Format(time.RFC1123)\n\tauth := c.getHash(\"%s%s%s%s\", endpoint, acceptVersion, acceptHeader, timestamp)\n\n\t// FireEye required\n\treq.Header.Set(\"Accept\", acceptHeader)\n\treq.Header.Set(\"Accept-Version\", acceptVersion)\n\treq.Header.Set(\"X-Auth\", c.publicKey)\n\treq.Header.Set(\"X-Auth-Hash\", auth)\n\treq.Header.Set(\"Date\", timestamp)\n\n\t// execute the request\n\tstats.IncrementCounter(\"request\")\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\tstats.IncrementCounter(\"request.error\")\n\t\treturn nil, errors.Wrap(err, \"cannot get url\")\n\t}\n\tdefer resp.Body.Close()\n\n\tstats.IncrementCounter(fmt.Sprintf(\"request.code.%d\", resp.StatusCode))\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"%d - %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\t}\n\n\t// response is always {success:boolean, message:something}\n\t// First we decode this from response, and fail fast if success = false\n\t// Otherwise, we return the message only\n\n\tvar fireeyeResult schema.Result\n\tbody := io.LimitReader(resp.Body, 2<<30) // 1 GB\n\tif err := json.NewDecoder(body).Decode(&fireeyeResult); err != nil {\n\t\tstats.IncrementCounter(\"request.feed.error\")\n\t\treturn nil, errors.Wrap(err, \"couldn't decode result\")\n\t}\n\n\tvar buff bytes.Buffer\n\tif err := json.NewEncoder(&buff).Encode(fireeyeResult.Message); err != nil {\n\t\tstats.IncrementCounter(\"request.feed.error\")\n\t\treturn nil, errors.Wrap(err, \"couldn't encode message back to buffer\")\n\t}\n\n\tif !fireeyeResult.Success {\n\t\tstats.IncrementCounter(\"request.feed.error\")\n\t\tvar errorMessage schema.ResultErrorMessage\n\t\tif err := json.Unmarshal(buff.Bytes(), &errorMessage); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to decode error message\")\n\t\t}\n\t\treturn nil, fmt.Errorf(\"%s: %s\", errorMessage.Error, errorMessage.Description)\n\t}\n\n\tstats.IncrementCounter(\"request.success\")\n\n\treturn &buff, nil\n}", "func GetUrlContent(url string, depth int) ([]byte, error) {\n\tlog.Println(depth, url)\n\tvar result []byte\n\tvar err error\n\tclient := &http.Client{\n\t\tCheckRedirect: nil,\n\t}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlog.Println(\"http.NewRequest\", err)\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"User-Agent\", \"curl/7.50.3\")\n\treq.Header.Add(\"Accept\", \"*/*\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(\"client.Do\", err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tfinalUrl := resp.Request.URL.String()\n\tif finalUrl != url {\n\t\tdepth1 := depth + 1\n\t\tresult, err = GetUrlContent(finalUrl, depth1)\n\t\treturn result, err\n\t} else {\n\t\tif resp.StatusCode == 200 {\n\t\t\tresult, err = ioutil.ReadAll(resp.Body)\n\t\t\tlog.Println(\"S\", url)\n\t\t\treturn result, err\n\t\t} else {\n\t\t\tlog.Println(\"client.Do\", resp.StatusCode, url)\n\t\t\tfmt.Printf(resp.Status)\n\t\t\treturn nil, errors.New(\"Response Error\")\n\t\t}\n\t}\n}", "func (c *client) httpRequest(ctx context.Context, url string, timeout time.Duration) ([]byte, error) {\n\tlog.Debugf(\"httpRequest: %v\", url)\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create request: %v\", err)\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: timeout * time.Second,\n\t}\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"dcrdata error: %v %v %v\",\n\t\t\t\tresponse.StatusCode, url, err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"dcrdata error: %v %v %s\",\n\t\t\tresponse.StatusCode, url, body)\n\t}\n\n\treturn ioutil.ReadAll(response.Body)\n}", "func Request(method, url string, body io.Reader, deadline, dialTimeout time.Duration, header map[string]string) ([]byte, int, error) {\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: func(netw, addr string) (net.Conn, error) {\n\t\t\t\tdeadline := time.Now().Add(deadline)\n\t\t\t\tc, err := net.DialTimeout(netw, addr, dialTimeout)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tc.SetDeadline(deadline)\n\t\t\t\treturn c, nil\n\t\t\t},\n\t\t},\n\t}\n\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tif header != nil {\n\t\tfor key, value := range header {\n\t\t\treq.Header.Set(key, value)\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn data, resp.StatusCode, nil\n}", "func doDownloadRequest(ctx context.Context, url string, downloadFrom, totalContentLength int64, options *Options) (body io.ReadCloser, err error) {\n\tclient := http.Client{\n\t\tTimeout: options.Timeout,\n\t\tTransport: options.HTTPTransport,\n\t}\n\n\t// See: https://stackoverflow.com/a/29200933/3536354\n\treq, _ := http.NewRequest(http.MethodGet, url, nil)\n\treq = req.WithContext(ctx)\n\n\tif downloadFrom > 0 {\n\t\treq.Header.Set(rangeHeader, fmt.Sprintf(\"bytes=%d-\", downloadFrom))\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting url: %w\", err)\n\t}\n\n\tif downloadFrom <= 0 {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t_ = resp.Body.Close()\n\t\t\treturn nil, fmt.Errorf(\"unexpected download http status code %d\", resp.StatusCode)\n\t\t}\n\t\tif resp.ContentLength != totalContentLength {\n\t\t\t_ = resp.Body.Close()\n\t\t\treturn nil, fmt.Errorf(\"unexpected response content-length (expected %d, got %d)\", totalContentLength, resp.ContentLength)\n\t\t}\n\t\t// Return the body, done\n\t\treturn resp.Body, nil\n\t}\n\n\tif resp.StatusCode != http.StatusPartialContent {\n\t\treturn nil, fmt.Errorf(\"unexpected download http status code %d\", resp.StatusCode)\n\t}\n\n\t// Validate we are receiving the right portion of partial content\n\tvar respStart, respEnd, respTotal int64\n\t_, err = fmt.Sscanf(\n\t\tstrings.ToLower(resp.Header.Get(contentRangeHeader)),\n\t\t\"bytes %d-%d/%d\",\n\t\t&respStart, &respEnd, &respTotal,\n\t)\n\tif err != nil {\n\t\t_ = resp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"error parsing response content-range header: %w\", err)\n\t}\n\n\tif respStart != downloadFrom {\n\t\t_ = resp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"unexpected response range start (expected %d, got %d)\", downloadFrom, respStart)\n\t}\n\tif respEnd != totalContentLength-1 {\n\t\t_ = resp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"unexpected response range end (expected %d, got %d)\", totalContentLength-1, respEnd)\n\t}\n\tif respTotal != totalContentLength {\n\t\t_ = resp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"unexpected response range total (expected %d, got %d)\", totalContentLength, respTotal)\n\t}\n\n\treturn resp.Body, nil\n}", "func (d *driver) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {\n\toutput, err := d.Client.GetObject(&obs.GetObjectInput{\n\t\tGetObjectMetadataInput: obs.GetObjectMetadataInput{\n\t\t\tBucket: d.Bucket,\n\t\t\tKey: d.obsPath(path),\n\t\t},\n\t\tRangeStart: offset,\n\t})\n\n\tif err != nil {\n\t\tif obsErr, ok := err.(obs.ObsError); ok && obsErr.Code == \"InvalidRange\" {\n\t\t\treturn ioutil.NopCloser(bytes.NewReader(nil)), nil\n\t\t}\n\n\t\treturn nil, parseError(path, err)\n\t}\n\treturn output.Body, nil\n}", "func GetContent(url string, timeout uint) ([]byte, error) {\n\tresp, err := GetResp(url, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\treturn io.ReadAll(resp.Body)\n}", "func get(url string) (string, error) {\n\t//defer fetch.CatchPanic(\"Get()\")\n\tresp, err := httpClient.Get(url)\n\tif err != nil {\n\t\tpanic(\"Couldn't perform GET request to \" + url)\n\t}\n\tdefer resp.Body.Close()\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(\"Unable to read the response body\")\n\t}\n\ts := string(bytes)\n\treturn s, nil\n}", "func makeReq(url string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := doReq(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, err\n}", "func MakeRequest(str string) []byte {\n\tresp, err := http.Get(str)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn body\n}", "func Fetch(uri string, options ...ssh2.ClientOption) (*Reader, error) {\n\n\tif len(uri) == 0 {\n\t\treturn nil, errors.New(\"missing URI\")\n\t}\n\n\tsshClient, err := ssh2.Dial(uri, options...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating SSH client: %w\", err)\n\t}\n\n\tsftpClient, err := sftp.NewClient(sshClient.Client)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating SFTP client: %w\", err)\n\t}\n\n\t_, fullpath := splitter.SplitURI(uri)\n\tparts := strings.SplitN(fullpath, \"/\", 2)\n\n\tfile, err := sftpClient.Open(parts[1])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error opening file: %w\", err)\n\t}\n\n\treturn NewReader(file, sftpClient, sshClient.Client), nil\n\n}", "func (workCloud *WorkCloud) get(url string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", workCloud.agent)\n\n\tres, err := workCloud.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\tb, err := ioutil.ReadAll(res.Body)\n\n\treturn string(b), nil\n}", "func Get(url string) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\t//logger.Error(\"NewRequest error\", logger.Any(\"err\", err), logger.String(\"url\", url))\n\t\treturn nil, err\n\t}\n\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\t//logger.Error(\"Do error\", logger.Any(\"err\", err.Error()), logger.String(\"url\", url))\n\t\treturn nil, err\n\t}\n\t//if resp.StatusCode != http.StatusOK {\n\t//\t_, err := ioutil.ReadAll(resp.Body)\n\t//\tif err == nil {\n\t//\t\tresp.Body.Close()\n\t//\t\t//logger.Error(\"ReadAll error\", logger.Any(\"err\", string(bz2)), logger.String(\"url\", url))\n\t//\t}\n\t//}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == http.StatusOK {\n\t\tbz, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\t//logger.Error(\"ioutil.ReadAll err\", logger.Any(\"io\", err), logger.String(\"url\", url))\n\t\t\treturn nil, err\n\t\t}\n\t\treturn bz, nil\n\t}\n\treturn nil, nil\n}", "func (hs *HTTPScraper) Get(url string) (string, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", defaultUserAgent)\n\treq.Header.Set(\"sec-ch-ua\", \"\\\"Chromium\\\";v=\\\"86\\\", \\\"\\\"Not\\\\A;Brand\\\";v=\\\"99\\\", \\\"Google Chrome\\\";v=\\\"86\\\"\")\n\treq.Header.Set(\"Accept-Language\", \"en-US,en;q=0.9\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := hs.client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn FixForUTF8(body), nil\n}", "func (r *httpRetriever) get(uri *url.URL) (b []byte, err error) {\n\treturn r.getFile(uri)\n}", "func (client *Client) Get(\n\turl string,\n\tparams url.Values,\n\toptions ...interface{},\n) (io.ReadCloser, int, error) {\n\treply, err := client.request(\"GET\", url, params, nil, options...)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn reply.Body, reply.StatusCode, nil\n}", "func ReadUrl(url string) {\n\tval, err := ReadNewsFrom(url)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\trenderToSTDOUT(val)\n}", "func getRequest(url string) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := makeRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp == nil {\n\t\treturn nil, ErrResponseNil\n\t}\n\tdefer resp.Body.Close()\n\n\tbodyBytes, err := getBody(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, types.NewErrServiceClient(resp.StatusCode, bodyBytes)\n\t}\n\n\treturn bodyBytes, nil\n}", "func (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}", "func getHTML(link *url.URL) ([]byte, error) {\n resp, err := http.Get(link.String())\n if err != nil {\n return nil, err\n }\n defer resp.Body.Close()\n\n return ioutil.ReadAll(resp.Body)\n}", "func (d *driver) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {\n\tbaseUrl := d.getBaseUrl(path)\n\n\tinfo, err := d.Bucket.Stat(ctx, path)\n\tif err != nil {\n\t\treturn nil, err;\n\t}\n\n\tif offset > info.Fsize {\n\t\treturn ioutil.NopCloser(bytes.NewReader(nil)), nil\n\t}\n\n\thttpClient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", baseUrl, nil)\n\treq.Header.Add(\"Range\", \"bytes=\"+strconv.FormatInt(offset, 10)+\"-\")\n\tresp, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc,_ := ioutil.ReadAll(resp.Body)\n\n\tfmt.Print(\"content\"+string(c)+\"\\n\")\n\n\treturn resp.Body,err\n}", "func getBufferFromInputResource(inputPath string) ([]byte, error) {\n\n\turl, err := url.Parse(inputPath)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error parsing input file\")\n\t}\n\tif url.Scheme == \"http\" || url.Scheme == \"https\" {\n\t\tres, err := http.Get(inputPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\t\treturn ioutil.ReadAll(res.Body)\n\t} else if url.Scheme == \"ftp\" {\n\t\treturn nil, errors.New(\"ftp not supported yet\")\n\n\t} else {\n\t\treturn ioutil.ReadFile(inputPath)\n\t}\n}" ]
[ "0.7576013", "0.7265072", "0.7148855", "0.70467824", "0.7040002", "0.6826775", "0.67453367", "0.6693758", "0.6678494", "0.64908576", "0.6479455", "0.6471753", "0.64428675", "0.6437336", "0.6373478", "0.6368281", "0.63284236", "0.63129616", "0.6261887", "0.62561303", "0.62538636", "0.6251896", "0.6245528", "0.6237584", "0.6154005", "0.61101127", "0.61008304", "0.6062774", "0.6037839", "0.60337496", "0.6022368", "0.60148805", "0.59834886", "0.59794384", "0.59774363", "0.5961687", "0.5959285", "0.59516513", "0.5946684", "0.59440416", "0.5921241", "0.5897817", "0.5892446", "0.58555484", "0.58409286", "0.5818176", "0.58174473", "0.58088136", "0.5807981", "0.57689464", "0.57670933", "0.5757823", "0.57509285", "0.57485616", "0.57457924", "0.5714863", "0.5712343", "0.56938434", "0.56460893", "0.563268", "0.56310785", "0.562147", "0.5610607", "0.56071144", "0.5602705", "0.5587316", "0.5565876", "0.55608404", "0.5559019", "0.55550694", "0.5550903", "0.5546916", "0.5536855", "0.5534441", "0.55298805", "0.55291224", "0.55277276", "0.5517057", "0.5514123", "0.5507579", "0.549328", "0.5491023", "0.5489616", "0.54803604", "0.54769665", "0.54485375", "0.5441466", "0.5427707", "0.5424185", "0.54162455", "0.54140556", "0.54080933", "0.54069984", "0.54054904", "0.5402218", "0.5400728", "0.5394004", "0.5391737", "0.5391076", "0.5389876", "0.53824973" ]
0.0
-1
Figure out the absolute path of our own binary (if it's still around).
func SelfPath() string { path, err := exec.LookPath(os.Args[0]) if err != nil { if os.IsNotExist(err) { return "" } if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) { return "" } panic(err) } path, err = filepath.Abs(path) if err != nil { if os.IsNotExist(err) { return "" } panic(err) } return path }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func findAbsoluteBinary(name string) string {\n\tpath, err := exec.LookPath(name)\n\tif err != nil {\n\t\tpath = name\n\t}\n\tpath, err = filepath.Abs(path)\n\tif err != nil {\n\t\tpath = name\n\t}\n\treturn path\n}", "func getFullPath(binaryPath string) (string, error) {\n\t// NOTE(thomastaylor312): I am leaving this code commented out here. During\n\t// the implementation of post-render, it was brought up that if we are\n\t// relying on plugins, we should actually use the plugin system so it can\n\t// properly handle multiple OSs. This will be a feature add in the future,\n\t// so I left this code for reference. It can be deleted or reused once the\n\t// feature is implemented\n\n\t// Manually check the plugin dir first\n\t// if !strings.Contains(binaryPath, string(filepath.Separator)) {\n\t// \t// First check the plugin dir\n\t// \tpluginDir := helmpath.DataPath(\"plugins\") // Default location\n\t// \t// If location for plugins is explicitly set, check there\n\t// \tif v, ok := os.LookupEnv(\"HELM_PLUGINS\"); ok {\n\t// \t\tpluginDir = v\n\t// \t}\n\t// \t// The plugins variable can actually contain multiple paths, so loop through those\n\t// \tfor _, p := range filepath.SplitList(pluginDir) {\n\t// \t\t_, err := os.Stat(filepath.Join(p, binaryPath))\n\t// \t\tif err != nil && !os.IsNotExist(err) {\n\t// \t\t\treturn \"\", err\n\t// \t\t} else if err == nil {\n\t// \t\t\tbinaryPath = filepath.Join(p, binaryPath)\n\t// \t\t\tbreak\n\t// \t\t}\n\t// \t}\n\t// }\n\n\t// Now check for the binary using the given path or check if it exists in\n\t// the path and is executable\n\tcheckedPath, err := exec.LookPath(binaryPath)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"unable to find binary at %s\", binaryPath)\n\t}\n\n\treturn filepath.Abs(checkedPath)\n}", "func getCurrentAbPathByExecutable() string {\n\texePath, err := os.Executable()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tres, _ := filepath.EvalSymlinks(filepath.Dir(exePath))\n\treturn res\n}", "func getCurrentAbPathByExecutable() string {\n\texePath, err := os.Executable()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tres, _ := filepath.EvalSymlinks(filepath.Dir(exePath))\n\treturn res\n}", "func GetAbsolutePath(bin string) (string, error) {\n\tlp, err := exec.LookPath(bin)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to resolve path to %q executable: %v\", bin, err)\n\t}\n\n\treturn filepath.EvalSymlinks(lp)\n}", "func bin() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn filepath.Join(filepath.Dir(filename), \"../../bin\")\n}", "func getAbsInstallPath(relPath string) (string, error) {\n\tex, err := os.Executable()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(filepath.Dir(ex), \"..\", relPath), nil\n}", "func executableLocation(updateDirectory string, binary string) string {\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\tswitch binary {\n\t\tcase \"launcher\":\n\t\t\treturn filepath.Join(updateDirectory, \"Kolide.app\", \"Contents\", \"MacOS\", binary)\n\t\tcase \"osqueryd\":\n\t\t\treturn filepath.Join(updateDirectory, binary)\n\t\tdefault:\n\t\t\treturn \"\"\n\t\t}\n\tcase \"windows\":\n\t\treturn filepath.Join(updateDirectory, fmt.Sprintf(\"%s.exe\", binary))\n\tcase \"linux\":\n\t\treturn filepath.Join(updateDirectory, binary)\n\tdefault:\n\t\treturn filepath.Join(updateDirectory, binary)\n\t}\n}", "func BaseLocation() (string, error) {\n\tex, err := os.Executable()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"undetermined location of own executable: %s\", err)\n\t}\n\tex = filepath.Dir(ex)\n\t// TODO(yifan): Hardcode the parent dir name for now.\n\tif filepath.Base(ex) != \"installer\" {\n\t\treturn \"\", fmt.Errorf(\"%s executable in unknown location: %s\", filepath.Base(ex), err)\n\t}\n\treturn filepath.Dir(ex), nil\n}", "func EpinioBinaryPath() string {\n\tp, _ := filepath.Abs(filepath.Join(Root(), \"dist\", BinaryName()))\n\treturn p\n}", "func exePath() string {\n\texe, err := os.Executable()\n\n\tif err != nil {\n\t\tpanic(\"Could not get executable path!\")\n\t}\n\n\treturn exe\n}", "func execPath() (string, error) {\n\tfile, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Abs(file)\n}", "func resolveBitcodePath(bcPath string) string {\n\tif _, err := os.Stat(bcPath); os.IsNotExist(err) {\n\t\t// If the bitcode file does not exist, try to find it in the store\n\t\tif LLVMBitcodeStorePath != \"\" {\n\t\t\t// Compute absolute path hash\n\t\t\tabsBcPath, _ := filepath.Abs(bcPath)\n\t\t\tstoreBcPath := path.Join(LLVMBitcodeStorePath, getHashedPath(absBcPath))\n\t\t\tif _, err := os.Stat(storeBcPath); os.IsNotExist(err) {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn storeBcPath\n\t\t}\n\t\tLogWarning(\"Failed to find the file %v\\n\", bcPath)\n\t\treturn \"\"\n\t}\n\treturn bcPath\n}", "func fullPath(path string) (string, error) {\n\tpath = strings.Replace(path, \"~\", os.Getenv(\"HOME\"), 1)\n\n\treturn filepath.Abs(path)\n}", "func GetFullPathOfApp(chain uint64, name []byte) string {\n\tnameStr := hex.EncodeToString(name)\n\tnameStr = \"z\" + nameStr\n\tnameStr = path.Join(projectRoot, fmt.Sprintf(\"chain%d\", chain), nameStr)\n\treturn nameStr\n}", "func GetExecutableFilename() string {\n\t// try readlink first\n\tpath, err := os.Readlink(\"/proc/self/exe\")\n\tif err == nil {\n\t\treturn path\n\t}\n\t// use argv[0]\n\tpath = os.Args[0]\n\tif !filepath.IsAbs(path) {\n\t\tcwd, _ := os.Getwd()\n\t\tpath = filepath.Join(cwd, path)\n\t}\n\tif FileExists(path) {\n\t\treturn path\n\t}\n\t// Fallback : use \"gosemki\" and assume we are in the PATH...\n\tpath, err = exec.LookPath(\"gosemki\")\n\tif err == nil {\n\t\treturn path\n\t}\n\treturn \"\"\n}", "func getCurrentAbPath() string {\n\tdir := getCurrentAbPathByExecutable()\n\ttmpDir, _ := filepath.EvalSymlinks(os.TempDir())\n\tif strings.Contains(dir, tmpDir) {\n\t\treturn getCurrentAbPathByCaller()\n\t}\n\treturn dir\n}", "func getCurrentAbPath() string {\n\tdir := getCurrentAbPathByExecutable()\n\ttmpDir, _ := filepath.EvalSymlinks(os.TempDir())\n\tif strings.Contains(dir, tmpDir) {\n\t\treturn getCurrentAbPathByCaller()\n\t}\n\treturn dir\n}", "func (preProcPathCde PreProcessPathCode) AbsolutePath() PreProcessPathCode {\n return PreProcessPathCode(2)\n}", "func (tr *TelegrafRunner) exePath() string {\n\treturn filepath.Join(currentVerLink, binSubpath, \"telegraf\")\n}", "func getFullPath(fileName string) (string, error) {\n\t//from where i am calling the program\n\tworkingDir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Invalid working dir\")\n\t}\n\n\treturn workingDir + \"/\" + fileName, nil\n}", "func GetCurrentExecPath() (string, error) {\n\ts, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s, nil\n\t//i := strings.LastIndex(s, \"\\\\\")\n\t//p := string(s[0 : i+1])\n\t//return p, nil\n}", "func (c CrostiniGuestOS) GetBinPath() string {\n\treturn \"/tmp/trace_replay/bin\"\n}", "func GetSelfPath() (string, error) {\n\treturn filepath.Abs(filepath.Dir(os.Args[0]))\n}", "func getAbsPath(givenPath string) string {\n\tmanifestPath, err := filepath.Abs(givenPath)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Unable to convert to Absolute file path.\")\n\t}\n\treturn manifestPath\n}", "func (c *subprocessExec) getExecutablePath(logger client.LoggerProducer) (absPath string, err error) {\n\tdefaultPath, err := exec.LookPath(c.Binary)\n\tif defaultPath != \"\" {\n\t\treturn c.Binary, err\n\t}\n\n\tcmdPath := c.Env[\"PATH\"]\n\t// For non-Windows platforms, the filepath.Separator is always '/'. However,\n\t// for Windows, Go accepts both '\\' and '/' as valid file path separators,\n\t// even though the native filepath.Separator for Windows is really '\\'. This\n\t// detects both '\\' and '/' as valid Windows file path separators.\n\tbinaryIsFilePath := strings.Contains(c.Binary, string(filepath.Separator)) || runtime.GOOS == \"windows\" && strings.Contains(c.Binary, \"/\")\n\n\tif len(cmdPath) == 0 || binaryIsFilePath {\n\t\treturn c.Binary, nil\n\t}\n\n\tlogger.Execution().Debug(\"could not find executable binary in the default runtime environment PATH, falling back to trying the command's PATH\")\n\n\toriginalPath := os.Getenv(\"PATH\")\n\tdefer func() {\n\t\t// Try to reset the PATH back to its original state. If this fails, then\n\t\t// the agent may have a modified PATH, which will affect all future\n\t\t// agent operations that need to execute processes. However, given that\n\t\t// the potential ways this could fail to reset seem highly unlikely\n\t\t// (e.g. due to having insufficient memory to reset it) , it doesn't\n\t\t// seem worth handling in a better way.\n\t\tif resetErr := os.Setenv(\"PATH\", originalPath); resetErr != nil {\n\t\t\tlogger.Execution().Error(errors.Wrap(resetErr, \"resetting agent's PATH env var back to its original state\").Error())\n\t\t}\n\t}()\n\n\tif err := os.Setenv(\"PATH\", cmdPath); err != nil {\n\t\treturn c.Binary, errors.Wrap(err, \"setting command's PATH to try fallback executable paths\")\n\t}\n\n\treturn exec.LookPath(c.Binary)\n}", "func getAbsolutePath(p string) (string, error) {\n\troot, err := git.RootDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(root, p), nil\n}", "func SelfPath() string {\n\tpath, _ := filepath.Abs(os.Args[0])\n\treturn path\n}", "func SelfPath() string {\n\tpath, _ := filepath.Abs(os.Args[0])\n\treturn path\n}", "func SelfPath() string {\n\tpath, _ := filepath.Abs(os.Args[0])\n\treturn path\n}", "func AppPath() string {\n\tappPathOnce.Do(func() {\n\t\tvar err error\n\t\tappPath, err = exec.LookPath(os.Args[0])\n\t\tif err != nil {\n\t\t\tpanic(\"look executable path: \" + err.Error())\n\t\t}\n\n\t\tappPath, err = filepath.Abs(appPath)\n\t\tif err != nil {\n\t\t\tpanic(\"get absolute executable path: \" + err.Error())\n\t\t}\n\t})\n\n\treturn appPath\n}", "func (n *nodeImpl) BinPath() string {\n\treturn n.getBinPath()\n}", "func getAbsoluteBUILDPath(workspaceRoot, buildFilePath string) (string, error) {\n\tabsPath, err := filepath.Abs(buildFilePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tg3Path, err := filepath.Rel(workspaceRoot, absPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn platform.Normalize(g3Path), nil\n}", "func CurrentPath() string {\n\tvar dirAbsPath string\n\tex, err := os.Executable()\n\tif err == nil {\n\t\tdirAbsPath = filepath.Dir(ex)\n\t\treturn dirAbsPath\n\t}\n\n\texReal, err := filepath.EvalSymlinks(ex)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tdirAbsPath = filepath.Dir(exReal)\n\treturn dirAbsPath\n}", "func (ie *InitEnvironment) GetAbsFilePath(filename string) string {\n\t// Here IsAbs should be enough but unfortunately it doesn't handle absolute paths starting from\n\t// the current drive on windows like `\\users\\noname\\...`. Also it makes it more easy to test and\n\t// will probably be need for archive execution under windows if always consider '/...' as an\n\t// absolute path.\n\tif filename[0] != '/' && filename[0] != '\\\\' && !filepath.IsAbs(filename) {\n\t\tfilename = filepath.Join(ie.CWD.Path, filename)\n\t}\n\tfilename = filepath.Clean(filename)\n\tif filename[0:1] != afero.FilePathSeparator {\n\t\tfilename = afero.FilePathSeparator + filename\n\t}\n\treturn filename\n}", "func getExecPath(name string) string {\n\tif name == \"\" {\n\t\tlog.Println(\"invalid executable file name\")\n\t\tos.Exit(-1)\n\t}\n\tout, err := exec.Command(\"which\", name).Output()\n\tif err != nil {\n\t\tlog.Printf(\"executable file %s not found in $PATH\", name)\n\t\tos.Exit(-1)\n\t}\n\treturn string(bytes.TrimSpace(out))\n}", "func getCurrentAbPathByCaller() string {\n\tvar abPath string\n\t_, filename, _, ok := runtime.Caller(0)\n\tif ok {\n\t\tabPath = path.Dir(filename)\n\t}\n\treturn abPath\n}", "func getCurrentAbPathByCaller() string {\n\tvar abPath string\n\t_, filename, _, ok := runtime.Caller(0)\n\tif ok {\n\t\tabPath = path.Dir(filename)\n\t}\n\treturn abPath\n}", "func (env *LocalTestEnv) BinaryPath(binary string) string {\n\treturn path.Join(os.Getenv(\"VTROOT\"), \"bin\", binary)\n}", "func AppFilePath() string {\r\n\tpath, err := exec.LookPath(os.Args[0])\r\n\tif err != nil {\r\n\t\treturn \"\"\r\n\t}\r\n\r\n\tpath, err = filepath.Abs(path)\r\n\tif err != nil {\r\n\t\treturn \"\"\r\n\t}\r\n\treturn path\r\n}", "func Realpath(path string) string {\n\tp, _ := filepath.Abs(path)\n\treturn p\n}", "func (d *Distro) ExecutableSubPath() string {\n\tarch := d.Arch\n\tif d.UseLegacyAgent {\n\t\tarch += \"_legacy\"\n\t}\n\treturn filepath.Join(arch, d.BinaryName())\n}", "func lookupPath(exe string) string {\n\texePath, ok := commandPaths[exe]\n\tif ok {\n\t\treturn exePath\n\t}\n\n\tvar err error\n\texePath, err = exec.LookPath(exe)\n\tif err != nil {\n\t\tlog.Fatalf(\"Not installed: %s\\n\", exe)\n\t}\n\tcommandPaths[exe] = exePath\n\treturn exePath\n}", "func (conf *Config) LookupInitPath() (string, error) {\n\tbinary := conf.GetInitPath()\n\tif filepath.IsAbs(binary) {\n\t\treturn binary, nil\n\t}\n\n\tfor _, dir := range []string{\n\t\t// FHS 3.0: \"/usr/libexec includes internal binaries that are not intended to be executed directly by users or shell scripts. Applications may use a single subdirectory under /usr/libexec.\"\n\t\t// https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s07.html\n\t\t\"/usr/local/libexec/docker\",\n\t\t\"/usr/libexec/docker\",\n\n\t\t// FHS 2.3: \"/usr/lib includes object files, libraries, and internal binaries that are not intended to be executed directly by users or shell scripts.\"\n\t\t// https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA\n\t\t\"/usr/local/lib/docker\",\n\t\t\"/usr/lib/docker\",\n\t} {\n\t\t// exec.LookPath has a fast-path short-circuit for paths that contain \"/\" (skipping the PATH lookup) that then verifies whether the given path is likely to be an actual executable binary (so we invoke that instead of reimplementing the same checks)\n\t\tif file, err := exec.LookPath(filepath.Join(dir, binary)); err == nil {\n\t\t\treturn file, nil\n\t\t}\n\t}\n\n\t// if we checked all the \"libexec\" directories and found no matches, fall back to PATH\n\treturn exec.LookPath(binary)\n}", "func GetExecutablePath(executable Executable) (string, error) {\n\tpluginPath := GetPluginPath(executable.PluginName)\n\tinstallPath := path.Join(\n\t\tGetAsdfDataPath(),\n\t\t\"installs\",\n\t\texecutable.PluginName,\n\t\texecutable.PluginVersion,\n\t)\n\n\tlistBinPath := path.Join(pluginPath, \"bin\", listBinPathScript)\n\tif _, err := os.Stat(listBinPath); err != nil {\n\t\texePath := path.Join(installPath, \"bin\", executable.Name)\n\t\tif _, err := os.Stat(exePath); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"executable not found\")\n\t\t}\n\t\treturn exePath, nil\n\t}\n\n\trawBinPaths, err := exec.Command(\"bash\", listBinPath).Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpaths := strings.Split(string(rawBinPaths), \" \")\n\tfor _, binPath := range paths {\n\t\tbinPath = strings.TrimSpace(binPath)\n\t\texePath := path.Join(installPath, binPath, executable.Name)\n\t\tif _, err := os.Stat(exePath); err == nil {\n\t\t\treturn exePath, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"executable not found\")\n}", "func GetAbsPath(p string) (out string, err error) {\n\tif p == \"\" {\n\t\tout, err = os.Getwd()\n\t} else if strings.HasPrefix(p, \"~\") {\n\t\tout, err = homedir.Expand(p)\n\t} else if !filepath.IsAbs(p) {\n\t\tout, err = filepath.Abs(p)\n\t} else {\n\t\tout = p\n\t}\n\treturn\n}", "func (o *os) GetExecutablePath() gdnative.String {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetExecutablePath()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_executable_path\")\n\n\t// Call the parent method.\n\t// String\n\tretPtr := gdnative.NewEmptyString()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewStringFromPointer(retPtr)\n\treturn ret\n}", "func (store FileStore) binPath(id string) string {\n\treturn filepath.Join(store.Path, id)\n}", "func getInternalMountPath(workingMountDir string, vol *smbVolume) string {\n\tif vol == nil {\n\t\treturn \"\"\n\t}\n\tmountDir := vol.uuid\n\tif vol.uuid == \"\" {\n\t\tmountDir = vol.subDir\n\t}\n\treturn filepath.Join(workingMountDir, mountDir)\n}", "func socketPath(bundleDir string) (string, error) {\n\tnum := rand.Intn(10000)\n\tpath := filepath.Join(bundleDir, fmt.Sprintf(\"socket-%4d\", num))\n\tconst maxPathLen = 108\n\tif len(path) <= maxPathLen {\n\t\treturn path, nil\n\t}\n\n\t// Path is too large, try to make it smaller.\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error getting cwd: %v\", err)\n\t}\n\tpath, err = filepath.Rel(cwd, path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error getting relative path for %q from cwd %q: %v\", path, cwd, err)\n\t}\n\tif len(path) > maxPathLen {\n\t\treturn \"\", fmt.Errorf(\"could not get socket path under length limit %d: %s\", maxPathLen, path)\n\t}\n\treturn path, nil\n}", "func scriptPath() string {\n\tname, errPath := os.Executable()\n\tif errPath != nil {\n\t\tpanic(errPath)\n\t}\n\treturn name\n}", "func (pp *protoPackage) absPath() string {\n\treturn path.Join(pp.Path, pp.pkgPath())\n}", "func findExePath(pid int) (string, error) {\n\t// Original code suggested different approach (see below).\n\t// Maybe it could be useful in the future.\n\t//\n\t// Find executable path from PID/handle on Windows:\n\t// https://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx\n\n\tp, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer syscall.CloseHandle(p)\n\n\tn := uint32(128)\n\tfor {\n\t\tbuf := make([]uint16, int(n))\n\t\terr = _QueryFullProcessImageName(p, 0, &buf[0], &n)\n\t\tswitch err {\n\t\tcase syscall.ERROR_INSUFFICIENT_BUFFER:\n\t\t\t// try bigger buffer\n\t\t\tn *= 2\n\t\t\t// but stop if it gets too big\n\t\t\tif n > 10000 {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\tcase nil:\n\t\t\treturn syscall.UTF16ToString(buf[:n]), nil\n\t\tdefault:\n\t\t\treturn \"\", err\n\t\t}\n\t}\n}", "func computeProgramDirectory() string {\n\tlocation := js.Global().Get(\"location\")\n\turl := location.Get(\"href\").String()\n\turl = filepath.Dir(url)\n\turl = strings.TrimPrefix(url, \"file:/\")\n\tif strings.HasPrefix(url, \"http:/\") {\n\t\turl = strings.TrimPrefix(url, \"http:/\")\n\t\turl = \"http://\" + url\n\t}\n\tif strings.HasPrefix(url, \"https:/\") {\n\t\turl = strings.TrimPrefix(url, \"https:/\")\n\t\turl = \"https://\" + url\n\t}\n\treturn url\n}", "func fetchBinary(bin string) (string, error) {\n\tnomadBinaryDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create temp dir: %v\", err)\n\t}\n\n\tif bin == \"\" {\n\t\tbin, err = discover.NomadExecutable()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to discover nomad binary: %v\", err)\n\t\t}\n\t}\n\n\tdest := path.Join(nomadBinaryDir, \"nomad\")\n\tif runtime.GOOS == \"windows\" {\n\t\tdest = dest + \".exe\"\n\t}\n\n\tif err = getter.GetFile(dest, bin); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get nomad binary: %v\", err)\n\t}\n\n\treturn nomadBinaryDir, nil\n}", "func locatedBinaryFile(search, binary string) (string, bool) {\n\tInfof(\"Found & unzip the binary for the version %s: %s\", cmdOptions.Version, binary)\n\tremoveOldBinFiles(search)\n\terr := archiver.Unarchive(binary, Config.DOWNLOAD.DOWNLOADDIR)\n\tif err != nil {\n\t\tFatalf(\"Couldn't unzip the file, err: %v\", err)\n\t}\n\tDebugf(\"Unzipped the file %s completed successfully\", binary)\n\treturn obtainExecutableFilename(search), true\n}", "func ensureAbs(path string) string {\n\tif filepath.IsAbs(path) {\n\t\treturn path\n\t}\n\treturn filepath.Join(WorkDir(), path)\n}", "func Self() string {\n\tname := os.Args[0]\n\tif filepath.Base(name) == name {\n\t\tif lp, err := exec.LookPath(name); err == nil {\n\t\t\tname = lp\n\t\t}\n\t}\n\treturn name\n}", "func LookUp() (string, error) {\n\tbin, err := exec.LookPath(Command)\n\tif err != nil {\n\t\treturn bin, fmt.Errorf(\n\t\t\t\"could not find %s binary in path. Build and copy it to path\",\n\t\t\tCommand,\n\t\t)\n\t}\n\treturn bin, nil\n}", "func executablePathFinder() (string, error) {\n\tfullpath, err := os.Executable()\n\tfolderPath := filepath.Dir(fullpath)\n\treturn folderPath, err\n}", "func findAbsoluteDeviceByIDPath(volumeName string) (string, error) {\n\tpath := getDeviceByIDPath(volumeName)\n\n\t// EvalSymlinks returns relative link if the file is not a symlink\n\t// so we do not have to check if it is symlink prior to evaluation\n\tresolved, err := filepath.EvalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not resolve symlink %q: %v\", path, err)\n\t}\n\n\tif !strings.HasPrefix(resolved, \"/dev\") {\n\t\treturn \"\", fmt.Errorf(\"resolved symlink %q for %q was unexpected\", resolved, path)\n\t}\n\n\treturn resolved, nil\n}", "func toolPath(toolName string) string {\n\tgobin := Getenv(\"GOBIN\")\n\tif runtime.GOOS == \"windows\" {\n\t\ttoolName += \".exe\"\n\t}\n\tif gobin != \"\" {\n\t\treturn filepath.Join(gobin, toolName)\n\t}\n\treturn filepath.Join(Gopath(), \"bin\", toolName)\n}", "func GetSelfFilePath(relativePath string) string {\n\treturn path.Join(ProjectSelfPath, relativePath)\n}", "func (c *Config) GetAbsPath(relPath string) string {\n\treturn path.Join(c.workinkDir, relPath)\n}", "func (d *Distro) ExecutableSubPath() string {\n\treturn filepath.Join(d.Arch, d.BinaryName())\n}", "func (v *VFile) RealPath() string {\n\treturn filepath.Join(v.BaseDir, v.ShadowDir, v.FileName)\n}", "func (b *Binary) RemotePath() string {\n\treturn b.file.RemotePath()\n}", "func getProcPath(pid string, file string) ([]byte, error) {\n\tprocessPath := filepath.Join(\"/proc\", pid, file)\n\tdat, err := ioutil.ReadFile(processPath)\n\tif err != nil {\n\t\t//fmt.Println(\"error occured opening file:\", err)\n\t\treturn nil, err\n\t}\n\treturn dat, nil\n}", "func getOciBlobCachePath(c *Handle) (string, error) {\n\t// This function may act on an cache object that is not fully initialized\n\t// so it is not a method on a Handle but rather an independent\n\t// function\n\n\treturn updateCacheSubdir(c, OciBlobDir)\n}", "func discoverExecName() string {\n\tif DEBUG {\n\t\tlog.Print(\"Debug: discoverExecName\\n\")\n\t}\n\n\tf := os.Args[0]\n\tif path.IsAbs(f) {\n\t\treturn f\n\t}\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Getwd failed: %s\", err))\n\t}\n\n\t_, err = os.Stat(f)\n\tif err == nil { // relative file exists\n\t\treturn path.Clean(path.Join(wd, f))\n\t} // not exists? lookup in path\n\n\tf2, err := exec.LookPath(f)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"lookpath failed: %s\", err))\n\t}\n\n\tif path.IsAbs(f2) {\n\t\treturn f2\n\t}\n\n\treturn path.Clean(path.Join(wd, f2))\n}", "func absPath(name string) (string, error) {\n\tif name == \"\" {\n\t\treturn os.Getwd()\n\t}\n\n\tif filepath.IsAbs(name) {\n\t\treturn name, nil\n\t}\n\n\tif len(name) > 0 && name[0] == '~' && (len(name) == 1 || name[1] == '/' || name[1] == '\\\\') {\n\t\treturn expendHome(name)\n\t}\n\n\treturn filepath.Abs(name)\n}", "func getPhantomJSbinPath() string {\n\tpaths := []string{os.Getenv(\"PHANTOMJS_BIN\"), \"/usr/local/bin/phantomjs\", \"./phantomjs\"}\n\n\tfor _, p := range paths {\n\t\tif IsPathExists(p) && IsPathExecutable(p) {\n\t\t\treturn p\n\t\t}\n\t}\n\tlog.Fatalln(\"Failed to find phantomJS binary\")\n\treturn \"\"\n}", "func GetAbsoluteFilePath(relFilePath string, sheet string) (result string, err error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(sheet, \" : \", err)\n\t}\n\tabsFilePath := filepath.Join(dir, relFilePath)\n\n\treturn absFilePath, nil\n\n}", "func GetGobinPath(name string) (string, error) {\n\tgobinPath, err := GetGobin()\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"cannot get $GOPATH/bin path\")\n\t}\n\n\treturn path.Join(gobinPath, name), nil\n}", "func (b *Binary) LocalPath() string {\n\treturn b.file.LocalPath()\n}", "func getFullSavePath(imageName, saveImagePath string) (string, error) {\n\tsavePathLastChar := string(saveImagePath[len(saveImagePath)-1])\n\n\t// Check if path is closed with appropriate path separator (depending on OS)\n\tif savePathLastChar != string(os.PathSeparator) {\n\t\tif checkOS() == \"linux\" {\n\t\t\tsaveImagePath += \"/\"\n\t\t} else {\n\t\t\tsaveImagePath += \"\\\\\"\n\t\t}\n\t}\n\n\t// If path exists\n\tif _, err := os.Stat(saveImagePath); !os.IsNotExist(err) {\n\t\treturn saveImagePath + imageName, nil\n\t} else {\n\t\treturn \"\", err\n\t}\n}", "func fullFilePath2(fSys *afero.Afero, fn string) string {\n\txType := reflect.TypeOf(fSys)\n\txValue := reflect.ValueOf(fSys)\n\tfmt.Println(xType, xValue) // Os: *afero.Afero &{0x85d228} // MemMap: *afero.Afero &{0xc00007bb60}\n\tif fn == \"none\" || fn == \"off\" {\n\t\treturn fn\n\t}\n\tvar e error\n\tvar s string\n\t//if xValue < &{0xc000000000} {\n\ts, e = filepath.Abs(fn)\n\tmsg.InfoOnErr(e, fmt.Sprintf(\"failed to parse %s\\n\", fn))\n\t//}\n\treturn s\n}", "func RealPath(file string) (string, error) {\n\tif path.IsAbs(file) {\n\t\treturn file, nil\n\t}\n\twd, err := os.Getwd()\n\treturn path.Join(wd, file), err\n}", "func executableName() string {\n\t_, file := filepath.Split(os.Args[0])\n\treturn file\n}", "func (g git) GetRelativeLocation(currentDir string) (string, error) {\n\tcmd := exec.Exec(currentDir, \"git\", \"rev-parse\", \"--show-prefix\")\n\tif cmd.Err != nil {\n\t\treturn \"\", cmd.Err\n\t}\n\treturn cmd.StdOut, nil\n}", "func absoluteConfigPath(configPath string) string {\n\tif path.IsAbs(configPath) {\n\t\treturn configPath\n\t}\n\treturn path.Join(\"/usr/local/etc/virtual-usb-printer/\", configPath)\n}", "func Base() string {\n\treturn filepath.Join(path, \"../..\")\n}", "func (le *LazyExe) Path() (string, error) {\n\tle.mu.Lock()\n\tdefer le.mu.Unlock()\n\tif le.tmpFile != nil {\n\t\treturn le.tmpFile.Name(), nil\n\t}\n\n\tvar err error\n\tle.tmpFile, err = ioutil.TempFile(os.TempDir(), prefix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err = le.tmpFile.Write(le.bytes); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := le.tmpFile.Chmod(0700); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := le.tmpFile.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn le.tmpFile.Name(), nil\n}", "func cliCmdPath() (string, error) {\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"linux\":\n\t\treturn path.Join(cliArchiveDir, \"bin\", \"conjure\"), nil\n\tdefault:\n\t\treturn \"\", errors.Errorf(\"OS %s not supported\", runtime.GOOS)\n\t}\n}", "func (m *Win32LobAppFileSystemDetection) GetPath()(*string) {\n val, err := m.GetBackingStore().Get(\"path\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (e *Entry) realPath() string {\n\tparts := make([]string, 1, len(e.path)+1)\n\tparts[0] = e.root.realPath\n\tparts = append(parts, e.path...)\n\treturn filepath.Join(parts...)\n}", "func ProcessPathForPid(pid int) string {\n\treadPath := \"/proc/\" + strconv.Itoa(pid) + \"/exe\"\n\n\tresolved, err := filepath.EvalSymlinks(readPath)\n\tif err != nil {\n\t\tlog.Printf(\"Pid %d: Could not resolve path for %s\", pid, readPath)\n\t\treturn \"\"\n\t}\n\n\tif _, err := os.Stat(resolved); err != nil {\n\t\tlog.Printf(\"Pid %d: File %s does not exist\", pid, resolved)\n\t\treturn \"\"\n\t}\n\n\treturn resolved\n}", "func GetAbsPath(path string) string {\n\tif path != \"\" && path[0] == '/' {\n\t\treturn path\n\t}\n\treturn filepath.Join(*rootPath, path)\n}", "func (metadata EventMetadata) GetPath() (string, error) {\n\tpath, err := os.Readlink(\n\t\tfilepath.Join(\n\t\t\tProcFsFdInfo,\n\t\t\tstrconv.FormatUint(\n\t\t\t\tuint64(metadata.Fd),\n\t\t\t\t10,\n\t\t\t),\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"fanotify: %w\", err)\n\t}\n\n\treturn path, nil\n}", "func realPath(file string) string {\n\tif string(file[0]) == \"/\" {\n\t\treturn file\n\t}\n\n\tif string(file[0]) != \"/\" {\n\t\tfile = \"/\" + file\n\t}\n\n\t_, filename, _, _ := runtime.Caller(3)\n\tdir := path.Join(path.Dir(filename), file)\n\n\tif _, err := os.Stat(dir); err == nil && strings.HasSuffix(dir, file) {\n\t\treturn dir\n\t}\n\n\tcurrent, err := os.Getwd()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdir = file\n\n\tif strings.HasSuffix(dir, current) {\n\t\treturn dir\n\t}\n\n\treturn current + dir\n}", "func relativePath(storePath, shardPath string) (string, error) {\n\tpath, err := filepath.Abs(storePath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"store abs path: %s\", err)\n\t}\n\n\tfp, err := filepath.Abs(shardPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"file abs path: %s\", err)\n\t}\n\n\tname, err := filepath.Rel(path, fp)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"file rel path: %s\", err)\n\t}\n\n\treturn name, nil\n}", "func SearchBinaryPath(file string) string {\n\tarray := ([]string)(nil)\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tenvPath := genv.Get(\"PATH\", genv.Get(\"Path\")).String()\n\t\tif gstr.Contains(envPath, \";\") {\n\t\t\tarray = gstr.SplitAndTrim(envPath, \";\")\n\t\t} else if gstr.Contains(envPath, \":\") {\n\t\t\tarray = gstr.SplitAndTrim(envPath, \":\")\n\t\t}\n\t\tif gfile.Ext(file) != \".exe\" {\n\t\t\tfile += \".exe\"\n\t\t}\n\n\tdefault:\n\t\tarray = gstr.SplitAndTrim(genv.Get(\"PATH\").String(), \":\")\n\t}\n\tif len(array) > 0 {\n\t\tpath := \"\"\n\t\tfor _, v := range array {\n\t\t\tpath = v + gfile.Separator + file\n\t\t\tif gfile.Exists(path) && gfile.IsFile(path) {\n\t\t\t\treturn path\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func GetExecutablePath(executableName string) (string, error) {\n\texecutablePath, err := exec.LookPath(executableName)\n\tif err != nil {\n\t\treturn \"\", errorutils.CheckError(err)\n\t}\n\n\tif executablePath == \"\" {\n\t\treturn \"\", errorutils.CheckError(errors.New(fmt.Sprintf(\"Could not find '%s' executable\", executableName)))\n\t}\n\n\tlog.Debug(fmt.Sprintf(\"Found %s executable at: %s\", executableName, executablePath))\n\treturn executablePath, nil\n}", "func ExeFile() string {\n rootPath := filepath.Dir(os.Args[0])\n\n if rootPath == \".\" {\n rootPath, err := exec.LookPath(os.Args[0])\n if err != nil {\n return os.Args[0]\n }\n\n rootPath, err = filepath.Abs(rootPath)\n if err != nil {\n return os.Args[0]\n }\n\n return rootPath\n }\n \n return os.Args[0]\n}", "func get_target_path(arch string, version string) string {\n\tvar target_path string\n\tif version == \"nightly\" {\n\t\ttarget_path = arch\n\t} else {\n\t\tdirectories := get_directories(cache_instance, db, arch)\n\t\tmTime := time.Time(dropbox.DBTime{})\n\t\tvar latest_directory dropbox.Entry\n\t\tfor _, dir := range directories {\n\t\t\tif strings.Contains(dir.Path, version) {\n\t\t\t\tif time.Time(dir.Modified).After(mTime) {\n\t\t\t\t\tmTime = time.Time(dir.Modified)\n\t\t\t\t\tlatest_directory = dir\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttarget_path = latest_directory.Path\n\t}\n\treturn target_path\n}", "func (s *Settings) Binary() (string, error) {\n\t// List is in reverse order of priority - last one will be preferred.\n\tcandidates := []string{\n\t\t// Steam is a bit tricky to start/stop automatically, so ignore it for now.\n\t\t// `~/Library/Application Support/Steam/steamapps/common/Factorio/factorio.app/Contents`,\n\t\t`/opt/factorio/bin/x64/factorio`,\n\t\t`~/factorio/bin/x64/factorio`,\n\t\t`~/.factorio/bin/x64/factorio`,\n\t\t`/Applications/factorio.app/Contents`,\n\t}\n\t// Steam is a bit tricky to start/stop automatically, so ignore it for now.\n\t// if e := os.Getenv(\"ProgramFiles(x86)\"); e != \"\" {\n\t//\tcandidates = append(candidates, filepath.Join(e, \"Steam\", \"steamapps\", \"common\", \"Factorio\", \"bin\", \"x64\", \"factorio.exe\"))\n\t// }\n\tif e := os.Getenv(\"ProgramW6432\"); e != \"\" {\n\t\tcandidates = append(candidates, filepath.Join(e, \"Factorio\", \"bin\", \"x64\", \"factorio.exe\"))\n\t}\n\n\tif s.binary != \"\" {\n\t\tcandidates = []string{s.binary}\n\t}\n\tmatch := \"\"\n\tfor _, c := range candidates {\n\t\ts, err := homedir.Expand(c)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"Unable to expand %s: %v\", c, err)\n\t\t\tcontinue\n\t\t}\n\t\tinfo, err := os.Stat(s)\n\t\tif os.IsNotExist(err) {\n\t\t\tglog.Infof(\"Path %s does not exists, skipped\", s)\n\t\t\tcontinue\n\t\t}\n\t\tif info.IsDir() {\n\t\t\tglog.Infof(\"Path %s is a directory, skipped\", s)\n\t\t\tcontinue\n\t\t}\n\t\tglog.Infof(\"Factorio binary found: %s\", s)\n\t\tmatch = s\n\t}\n\tif match == \"\" {\n\t\tglog.Infof(\"No factorio binary found\")\n\t\treturn \"\", fmt.Errorf(\"no factorio binary found; use --alsologtostderr for more info and --%sbinary to specify its location\", s.flagPrefix)\n\t}\n\tglog.Infof(\"Using Factorio binary: %s\", match)\n\treturn match, nil\n}", "func (game *Game) Current2hFilepath() (string, error) {\n\tfileName, err := game.Current2hFile()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn path.Join(game.Directory, fileName), nil\n}", "func (s *BashScript) FullPath() string {\n\treturn path.Join(s.BasePath, s.Path)\n}", "func GetCurrentPath(filename string) (string, error) {\n\tif regexp.MustCompile(`[Dd]avidia`).MatchString(filename) {\n\t\tfile, err := exec.LookPath(filename)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpath, err := filepath.Abs(file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn filepath.Dir(path), nil\n\t}\n\treturn \".\", nil\n}", "func UCDPath(file string) string {\n\t_, pkgdir, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tpanic(\"no debug info\")\n\t}\n\n\treturn filepath.Join(filepath.Dir(pkgdir), \"ucd\", file)\n}" ]
[ "0.74649626", "0.7209479", "0.7023994", "0.7023994", "0.68828493", "0.6846727", "0.68185115", "0.6566839", "0.65325665", "0.6515926", "0.64555186", "0.64522815", "0.6449214", "0.64245594", "0.63662297", "0.6335743", "0.6331376", "0.6331376", "0.62726", "0.6272367", "0.6243562", "0.6240085", "0.6232403", "0.6154049", "0.6146508", "0.613089", "0.6077756", "0.60765344", "0.60765344", "0.60765344", "0.6063055", "0.6059052", "0.60536474", "0.60379505", "0.6027947", "0.6010107", "0.59939784", "0.59939784", "0.5982127", "0.5960539", "0.59476876", "0.5944298", "0.5919567", "0.59152067", "0.59109914", "0.59031236", "0.58983505", "0.5898215", "0.58934724", "0.58779013", "0.58599585", "0.58561236", "0.58428407", "0.58316386", "0.5826686", "0.5819657", "0.5819133", "0.5793145", "0.57918906", "0.5777754", "0.5777158", "0.5775735", "0.5760625", "0.5755128", "0.5750879", "0.5742521", "0.5729062", "0.5723064", "0.571424", "0.5712716", "0.57099414", "0.5703125", "0.5699568", "0.56981486", "0.56970763", "0.568622", "0.5683276", "0.5680423", "0.56769615", "0.56755275", "0.5668933", "0.56685734", "0.5665279", "0.5664073", "0.5659294", "0.5643983", "0.5643033", "0.56366754", "0.56360143", "0.5627208", "0.5624773", "0.5586959", "0.5586064", "0.5578007", "0.55696976", "0.5567116", "0.55650693", "0.5562589", "0.5560322", "0.5549894" ]
0.63925564
14
ReadSymlinkedDirectory returns the target directory of a symlink. The target of the symbolic link may not be a file.
func ReadSymlinkedDirectory(path string) (string, error) { var realPath string var err error if realPath, err = filepath.Abs(path); err != nil { return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) } if realPath, err = filepath.EvalSymlinks(realPath); err != nil { return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) } realPathInfo, err := os.Stat(realPath) if err != nil { return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) } if !realPathInfo.Mode().IsDir() { return "", fmt.Errorf("canonical path points to a file '%s'", realPath) } return realPath, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ReadSymlinkedDirectory(path string) (string, error) {\n\trealPath, err := ReadSymlink(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trealPathInfo, err := os.Stat(realPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to stat target '%s' of '%s': %s\", realPath, path, err)\n\t}\n\tif !realPathInfo.Mode().IsDir() {\n\t\treturn \"\", fmt.Errorf(\"canonical path points to a file '%s'\", realPath)\n\t}\n\treturn realPath, nil\n}", "func TestReadSymlinkedDirectoryToFile(t *testing.T) {\n\tvar err error\n\tvar file *os.File\n\n\tif file, err = os.Create(\"/tmp/testReadSymlinkToFile\"); err != nil {\n\t\tt.Fatalf(\"failed to create file: %s\", err)\n\t}\n\n\tfile.Close()\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToFile\", \"/tmp/fileLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/fileLinkTest\"); err == nil {\n\t\tt.Fatalf(\"ReadSymlinkedDirectory on a symlink to a file should've failed\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"path should've been empty: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToFile\"); err != nil {\n\t\tt.Errorf(\"failed to remove file: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/fileLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func TestReadSymlinkedDirectoryToFile(t *testing.T) {\n\tvar err error\n\tvar file *os.File\n\n\tif file, err = os.Create(\"/tmp/testReadSymlinkToFile\"); err != nil {\n\t\tt.Fatalf(\"failed to create file: %s\", err)\n\t}\n\n\tfile.Close()\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToFile\", \"/tmp/fileLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/fileLinkTest\"); err == nil {\n\t\tt.Fatalf(\"ReadSymlinkedDirectory on a symlink to a file should've failed\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"path should've been empty: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToFile\"); err != nil {\n\t\tt.Errorf(\"failed to remove file: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/fileLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {\n\tvar err error\n\tif err = os.Mkdir(\"/tmp/testReadSymlinkToExistingDirectory\", 0777); err != nil {\n\t\tt.Errorf(\"failed to create directory: %s\", err)\n\t}\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToExistingDirectory\", \"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Fatalf(\"failed to read symlink to directory: %s\", err)\n\t}\n\n\tif path != \"/tmp/testReadSymlinkToExistingDirectory\" {\n\t\tt.Fatalf(\"symlink returned unexpected directory: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToExistingDirectory\"); err != nil {\n\t\tt.Errorf(\"failed to remove temporary directory: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {\n\tvar err error\n\tif err = os.Mkdir(\"/tmp/testReadSymlinkToExistingDirectory\", 0777); err != nil {\n\t\tt.Errorf(\"failed to create directory: %s\", err)\n\t}\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToExistingDirectory\", \"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Fatalf(\"failed to read symlink to directory: %s\", err)\n\t}\n\n\tif path != \"/tmp/testReadSymlinkToExistingDirectory\" {\n\t\tt.Fatalf(\"symlink returned unexpected directory: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToExistingDirectory\"); err != nil {\n\t\tt.Errorf(\"failed to remove temporary directory: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {\n\tvar path string\n\tvar err error\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/test/foo/Non/ExistingPath\"); err == nil {\n\t\tt.Fatalf(\"error expected for non-existing symlink\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"expected empty path, but '%s' was returned\", path)\n\t}\n}", "func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {\n\tvar path string\n\tvar err error\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/test/foo/Non/ExistingPath\"); err == nil {\n\t\tt.Fatalf(\"error expected for non-existing symlink\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"expected empty path, but '%s' was returned\", path)\n\t}\n}", "func ReadSymlink(path string) (string, error) {\n\tvar realPath string\n\tvar err error\n\tif realPath, err = filepath.Abs(path); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to get absolute path for %s: %s\", path, err)\n\t}\n\tif realPath, err = filepath.EvalSymlinks(realPath); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to canonicalise path for %s: %s\", path, err)\n\t}\n\treturn realPath, nil\n}", "func ReadSymlinkedFile(path string) (string, error) {\n\trealPath, err := ReadSymlink(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trealPathInfo, err := os.Stat(realPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to stat target '%s' of '%s': %s\", realPath, path, err)\n\t}\n\tif !realPathInfo.Mode().IsRegular() {\n\t\treturn \"\", fmt.Errorf(\"canonical path points does not point to a file '%s'\", realPath)\n\t}\n\treturn realPath, nil\n}", "func (d Dir) Readlink(name string) (string, error) {\n\tname, err := d.fullName(name)\n\tif nil != err {\n\t\treturn \"\", err\n\t}\n\tname, err = os.Readlink(name)\n\tif err != nil {\n\t\treturn \"\", mapDirOpenError(err, name)\n\t}\n\treturn name, nil\n}", "func (imsl *Symlink) Readlink(ctx context.Context) (string, error) {\n\treturn imsl.target, nil\n}", "func (c *Container) resolveSymlinkDir(name string) (string, error) {\n\t// This is used to compare paths to ensure that they are exactly contained\n\t// completely within s.RootDirectory()\n\troot := c.stage3Path()\n\tcheckList := func(fn string) (string, bool) {\n\t\tfnPath := filepath.Join(root, fn)\n\t\tif len(fnPath) < len(root) {\n\t\t\treturn \"\", false\n\t\t} else if fnPath == root {\n\t\t\treturn fnPath, true\n\t\t} else if strings.HasPrefix(fnPath, root+string(os.PathSeparator)) {\n\t\t\treturn fnPath, true\n\t\t} else {\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\n\t// Loop until we have either walked too far, or we resolve the symlink. This\n\t// protects us from simple symlink loops.\n\tcheckRecurse := func(name string) (string, error) {\n\t\tfor depth := 0; depth < 64; depth++ {\n\t\t\t// Get the real path for the file.\n\t\t\tif newName, ok := checkList(name); !ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"Name resolved to an unsafe path: %s\", name)\n\t\t\t} else if fi, err := os.Lstat(newName); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t} else if fi.Mode()&os.ModeSymlink != 0 {\n\t\t\t\t// If the destination is a symlink then we need to resolve it in order to\n\t\t\t\t// walk down the chain.\n\t\t\t\tvar err error\n\t\t\t\tif name, err = os.Readlink(newName); err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t} else if !fi.IsDir() {\n\t\t\t\treturn \"\", fmt.Errorf(\"Resolved path is not a directory: %s\", newName)\n\t\t\t} else {\n\t\t\t\treturn newName, nil\n\t\t\t}\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Symlink depth too excessive.\")\n\t}\n\n\t// Loop over the portions of the path to see where they resolve to\n\tcontainerPath := \"\"\n\tparts := strings.Split(name, string(os.PathSeparator))\n\tfor _, p := range parts {\n\t\tif p == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontainerPath = filepath.Join(containerPath, p)\n\t\tnewName, allowed := checkList(containerPath)\n\t\tif !allowed {\n\t\t\treturn \"\", fmt.Errorf(\"Name resolved to an unsafe path: %s\", name)\n\t\t}\n\t\tfi, err := os.Lstat(newName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// if the portion is a symlink, we'll read it and then resolve it out\n\t\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\t\tname, err := os.Readlink(newName)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\t// handle if the path is not absolute, such as \"../dir\" or just \"dir\".\n\t\t\tif !filepath.IsAbs(name) {\n\t\t\t\tname = filepath.Join(filepath.Dir(newName), name)\n\t\t\t\tname = filepath.Clean(name)\n\t\t\t}\n\t\t\tcontainerPath = strings.Replace(name, root+string(os.PathSeparator), \"\", -1)\n\n\t\t\t// recurse the link to check for additional layers of links\n\t\t\tname, err = checkRecurse(containerPath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tcontainerPath = strings.Replace(name, root+string(os.PathSeparator), \"\", -1)\n\t\t}\n\t}\n\n\treturn filepath.Join(root, containerPath), nil\n}", "func isSameDirSymlink(fi os.FileInfo, dir string) bool {\n\tif fi.Mode()&os.ModeSymlink == 0 {\n\t\treturn false\n\t}\n\ttarget, err := os.Readlink(filepath.Join(dir, fi.Name()))\n\treturn err == nil && !strings.Contains(target, \"/\")\n}", "func isSameDirSymlink(fi os.FileInfo, dir string) bool {\n\tif fi.Mode()&os.ModeSymlink == 0 {\n\t\treturn false\n\t}\n\ttarget, err := os.Readlink(filepath.Join(dir, fi.Name()))\n\treturn err == nil && !strings.Contains(target, \"/\")\n}", "func (fs *Mysqlfs) Readlink(link string) (string, error) {\n\tf, err := fs.storage.GetFile(link)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif f == nil {\n\t\treturn \"\", os.ErrNotExist\n\t}\n\n\tif !isSymlink(f.Mode) {\n\t\treturn \"\", &os.PathError{\n\t\t\tOp: \"readlink\",\n\t\t\tPath: link,\n\t\t\tErr: fmt.Errorf(\"not a symlink\"),\n\t\t}\n\t}\n\n\treturn string(f.Content), nil\n}", "func linkDir(src, dst string) error {\n\treturn syscall.Link(src, dst)\n}", "func (r *Reader) ReadLink(path string) (string, error) {\n\treturn r.rootFS.readLink(path)\n}", "func (w *wrapper) Readlink(path string) (int, string) {\n\tif sfs, ok := w.underlying.(billy.Symlink); ok {\n\t\tfn, err := sfs.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn convertError(err), \"\"\n\t\t}\n\t\treturn 0, fn\n\t}\n\treturn -fuse.ENOSYS, \"\"\n}", "func symlinkDir(srcDir string, destDir string) (err error) {\n\tsrcInfo, err := os.Stat(srcDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(destDir, srcInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdirectory, _ := os.Open(srcDir)\n\tdefer directory.Close()\n\tobjects, err := directory.Readdir(-1)\n\n\tfor _, obj := range objects {\n\t\tsrcPath := filepath.Join(srcDir, obj.Name())\n\t\tdestPath := filepath.Join(destDir, obj.Name())\n\n\t\tif obj.IsDir() {\n\t\t\terr = symlinkDir(srcPath, destPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr = symlinkFile(srcPath, destPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}", "func (w *walker) walkSymlink(ctx context.Context, relPath string, finishedChan chan<- ScanResult) error {\n\t// Symlinks are not supported on Windows. We ignore instead of returning\n\t// an error.\n\tif runtime.GOOS == \"windows\" {\n\t\treturn nil\n\t}\n\n\t// We always rehash symlinks as they have no modtime or\n\t// permissions. We check if they point to the old target by\n\t// checking that their existing blocks match with the blocks in\n\t// the index.\n\n\ttarget, err := w.Filesystem.ReadSymlink(relPath)\n\tif err != nil {\n\t\tw.handleError(ctx, \"reading link:\", relPath, err, finishedChan)\n\t\treturn nil\n\t}\n\n\tcurFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)\n\n\tf := protocol.FileInfo{\n\t\tName: relPath,\n\t\tType: protocol.FileInfoTypeSymlink,\n\t\tNoPermissions: true, // Symlinks don't have permissions of their own\n\t\tSymlinkTarget: target,\n\t}\n\tf = w.updateFileInfo(f, curFile)\n\n\tif hasCurFile {\n\t\tif curFile.IsEquivalentOptional(f, w.IgnorePerms, true, w.LocalFlags) {\n\t\t\treturn nil\n\t\t}\n\t\tif curFile.ShouldConflict() {\n\t\t\t// The old file was invalid for whatever reason and probably not\n\t\t\t// up to date with what was out there in the cluster. Drop all\n\t\t\t// others from the version vector to indicate that we haven't\n\t\t\t// taken their version into account, and possibly cause a\n\t\t\t// conflict.\n\t\t\tf.Version = f.Version.DropOthers(w.ShortID)\n\t\t}\n\t}\n\n\tl.Debugln(\"symlink changedb:\", relPath, f)\n\n\tselect {\n\tcase finishedChan <- ScanResult{File: f}:\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn nil\n}", "func (fs osFsEval) Readlink(path string) (string, error) {\n\treturn os.Readlink(path)\n}", "func (f *UserSettableSymlink) Readlink() (string, error) {\n\treturn \"\", status.Error(codes.InvalidArgument, \"Target of user settable symlinks can only be obtained through the virtual file system\")\n}", "func Link(packageDirectory, mountDirectory, outDirectory string) error {\n\tif fi, err := os.Stat(packageDirectory); err != nil {\n\t\treturn err\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn NotADirectory\n\t\t}\n\t}\n\tif fi, err := os.Stat(mountDirectory); err != nil {\n\t\treturn err\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn NotADirectory\n\t\t}\n\t}\n\tif fi, err := os.Stat(outDirectory); err != nil {\n\t\treturn err\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn NotADirectory\n\t\t}\n\t}\n\terr := Unlink(mountDirectory, outDirectory)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfis, err := ioutil.ReadDir(packageDirectory)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar pkgs []pkg.Package\n\tfor _, fi := range fis {\n\t\tif fi.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tpkgPath := path.Join(packageDirectory, fi.Name())\n\t\tvar data pkg.PackageMetadata\n\t\terr := xattr.ReadXattrs(pkgPath, &data)\n\t\tpkgs = append(pkgs, pkg.Package{data, pkgPath})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif exists(path.Join(mountDirectory, data.NV())) {\n\t\t\tcontinue\n\t\t}\n\t\terr = mount(pkgPath, path.Join(mountDirectory, data.NV()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmnt, err := filepath.Abs(path.Join(mountDirectory, data.NV()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tout, err := filepath.Abs(path.Join(outDirectory, data.NV()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = os.Symlink(mnt, out)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, root := range roots {\n\t\tif _, err := mkdirp(path.Join(outDirectory, root)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tvar etcDirs []string\n\tvar usrDirs []string\n\tvar varDirs []string\n\tvar optDirs []string\n\tfor _, pkg := range pkgs {\n\t\tetc, usr, Var, opt, etcs, usrs, Vars, opts := checkpackage(mountDirectory, pkg)\n\t\tif etc {\n\t\t\tetcDirs = append(etcDirs, etcs)\n\t\t}\n\t\tif usr {\n\t\t\tusrDirs = append(usrDirs, usrs)\n\t\t}\n\t\tif Var {\n\t\t\tvarDirs = append(varDirs, Vars)\n\t\t}\n\t\tif opt {\n\t\t\toptDirs = append(optDirs, opts)\n\t\t}\n\t}\n\n\tetcDirWork, err := mkdirp(path.Join(mountDirectory, \"etc\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tusrDirWork, err := mkdirp(path.Join(mountDirectory, \"usr\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tvarDirWork, err := mkdirp(path.Join(mountDirectory, \"var\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\toptDirWork, err := mkdirp(path.Join(mountDirectory, \"opt\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tetcDirUpper, err := mkdirp(path.Join(mountDirectory, \"etc-upper\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tusrDirUpper, err := mkdirp(path.Join(mountDirectory, \"usr-upper\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tvarDirUpper, err := mkdirp(path.Join(mountDirectory, \"var-upper\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\toptDirUpper, err := mkdirp(path.Join(mountDirectory, \"opt-upper\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar e errorer\n\te.Call(func() error { return overlay(path.Join(outDirectory, \"etc\"), etcDirs, etcDirWork, etcDirUpper) })\n\te.Call(func() error { return overlay(path.Join(outDirectory, \"var\"), varDirs, varDirWork, varDirUpper) })\n\te.Call(func() error { return overlay(path.Join(outDirectory, \"opt\"), optDirs, optDirWork, optDirUpper) })\n\te.Call(func() error { return overlay(path.Join(outDirectory, \"usr\"), usrDirs, usrDirWork, usrDirUpper) })\n\tif e.Error() != nil {\n\t\treturn e.Error()\n\t}\n\treturn nil\n}", "func symlinkTargetPath(targetDir string, path string) string {\n\ttarget := filepath.Clean(filepath.Join(targetDir, filepath.Base(path)))\n\tif rt.GOOS != \"windows\" {\n\t\treturn target\n\t}\n\n\toldExt := filepath.Ext(target)\n\treturn target[0:len(target)-len(oldExt)] + \".lnk\"\n}", "func (f *FakeFileSystem) Readlink(name string) (string, error) {\n\treturn f.ReadlinkName, f.ReadlinkError\n}", "func Readlink(name string) (string, error)", "func walk(filename string, linkDirname string, walkFn filepath.WalkFunc) error {\n\tsymWalkFunc := func(path string, info os.FileInfo, err error) error {\n\n\t\tif fname, err := filepath.Rel(filename, path); err == nil {\n\t\t\tpath = filepath.Join(linkDirname, fname)\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\n\t\tif err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {\n\t\t\tfinalPath, err := filepath.EvalSymlinks(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tinfo, err := os.Lstat(finalPath)\n\t\t\tif err != nil {\n\t\t\t\treturn walkFn(path, info, err)\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn walk(finalPath, path, walkFn)\n\t\t\t}\n\t\t}\n\n\t\treturn walkFn(path, info, err)\n\t}\n\treturn filepath.Walk(filename, symWalkFunc)\n}", "func RequireReadLink(t *testing.T, path string) string {\n\ttarget, err := os.Readlink(path)\n\trequire.NoError(t, err)\n\treturn target\n}", "func IsSymlink(fs fsa.FileSystem, path string) bool {\n\t_, err := fs.Lstat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\t_, err = fs.Readlink(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func TestSymlinkedCipherdir(t *testing.T) {\n\tdir := test_helpers.InitFS(t)\n\tdirSymlink := dir + \".symlink\"\n\terr := os.Symlink(dir, dirSymlink)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmnt := dir + \".mnt\"\n\ttest_helpers.MountOrFatal(t, dirSymlink, mnt, \"-extpass=echo test\")\n\tdefer test_helpers.UnmountPanic(mnt)\n\n\tfile := mnt + \"/file\"\n\tf, err := os.Create(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\n\tf, err = os.Open(mnt)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\tnames, err := f.Readdirnames(0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(names) != 1 || names[0] != \"file\" {\n\t\tt.Errorf(\"wrong Readdirnames result: %v\", names)\n\t}\n}", "func (v *VFS) Readlink(name string) (string, error) {\n\tf, err := v.FileSystem.Open(name)\n\tif nil != err {\n\t\treturn \"\", err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif nil != err {\n\t\treturn \"\", err\n\t}\n\treturn string(b), nil\n}", "func (d *Directory) Symlink(oldname, newname string, modTime time.Time, mode os.FileMode) error {\n\tstartBlock := d.w.inodeBuf.Len() / metadataBlockSize\n\toffset := d.w.inodeBuf.Len() - startBlock*metadataBlockSize\n\n\tif err := binary.Write(&d.w.inodeBuf, binary.LittleEndian, symlinkInodeHeader{\n\t\tinodeHeader: inodeHeader{\n\t\t\tInodeType: symlinkType,\n\t\t\tMode: uint16(mode),\n\t\t\tUid: 0,\n\t\t\tGid: 0,\n\t\t\tMtime: int32(modTime.Unix()),\n\t\t\tInodeNumber: d.w.sb.Inodes + 1,\n\t\t},\n\t\tNlink: 1, // TODO(later): when is this not 1?\n\t\tSymlinkSize: uint32(len(oldname)),\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.w.inodeBuf.Write([]byte(oldname)); err != nil {\n\t\treturn err\n\t}\n\n\td.dirEntries = append(d.dirEntries, fullDirEntry{\n\t\tstartBlock: uint32(startBlock),\n\t\toffset: uint16(offset),\n\t\tinodeNumber: d.w.sb.Inodes + 1,\n\t\tentryType: symlinkType,\n\t\tname: newname,\n\t})\n\n\td.w.sb.Inodes++\n\treturn nil\n}", "func IsDirOrSymlink(fi os.FileInfo) bool {\n\treturn fi.IsDir() || (fi.Mode()&os.ModeSymlink == os.ModeSymlink)\n}", "func Dirname(fd uintptr) (string, error) {\n\tproc := fmt.Sprintf(\"/proc/self/fd/%d\", fd)\n\ts, err := os.Readlink(proc)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn path.Dir(s), nil\n}", "func (cl *Client) Readlink(linkPath string) (node fs.DirEntry, err error) {\n\tvar (\n\t\tlogp = \"Readlink\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpReadlink(linkPath)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind == packetKindFxpStatus {\n\t\treturn nil, handleStatusCode(res.code, res.message)\n\t}\n\tif res.kind != packetKindFxpName {\n\t\treturn nil, errUnexpectedResponse(packetKindFxpName, res.kind)\n\t}\n\tnode = res.nodes[0]\n\tres.nodes = nil\n\treturn node, nil\n}", "func (n *node) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) {\n\tif n.te.Type != \"symlink\" {\n\t\treturn \"\", syscall.EINVAL\n\t}\n\treturn n.te.LinkName, nil\n}", "func (fsys *FS) Readlink(path string) (errc int, linkPath string) {\n\tdefer fs.Trace(path, \"\")(\"linkPath=%q, errc=%d\", &linkPath, &errc)\n\treturn -fuse.ENOSYS, \"\"\n}", "func (m *MockFs) followLinks(path string, followLastLink bool, count int) (canonicalPath string, err error) {\n\tif path == \"/\" {\n\t\treturn path, nil\n\t}\n\n\tparentPath, leaf := pathSplit(path)\n\tif parentPath == path {\n\t\terr = fmt.Errorf(\"Internal error: %v yields itself as a parent\", path)\n\t\tpanic(err.Error())\n\t}\n\n\tparentPath, err = m.followLinks(parentPath, true, count)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tparentNode, err := m.getDir(parentPath, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif parentNode.readErr != nil {\n\t\treturn \"\", &os.PathError{\n\t\t\tOp: \"read\",\n\t\t\tPath: path,\n\t\t\tErr: parentNode.readErr,\n\t\t}\n\t}\n\n\tlink, isLink := parentNode.symlinks[leaf]\n\tif isLink && followLastLink {\n\t\tif count <= 0 {\n\t\t\t// probably a loop\n\t\t\treturn \"\", &os.PathError{\n\t\t\t\tOp: \"read\",\n\t\t\t\tPath: path,\n\t\t\t\tErr: fmt.Errorf(\"too many levels of symbolic links\"),\n\t\t\t}\n\t\t}\n\n\t\tif link.readErr != nil {\n\t\t\treturn \"\", &os.PathError{\n\t\t\t\tOp: \"read\",\n\t\t\t\tPath: path,\n\t\t\t\tErr: link.readErr,\n\t\t\t}\n\t\t}\n\n\t\ttarget := m.followLink(link, parentPath)\n\t\treturn m.followLinks(target, followLastLink, count-1)\n\t}\n\treturn path, nil\n}", "func (te *TarExtractor) isDirlink(root string, path string) (bool, error) {\n\t// Make sure it exists and is a symlink.\n\tif _, err := te.fsEval.Readlink(path); err != nil {\n\t\treturn false, errors.Wrap(err, \"read dirlink\")\n\t}\n\n\t// Technically a string.TrimPrefix would also work...\n\tunsafePath, err := filepath.Rel(root, path)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"get relative-to-root path\")\n\t}\n\n\t// It should be noted that SecureJoin will evaluate all symlinks in the\n\t// path, so we don't need to loop over it or anything like that. It'll just\n\t// be done for us (in UnpackEntry only the dirname(3) is evaluated but here\n\t// we evaluate the whole thing).\n\ttargetPath, err := securejoin.SecureJoinVFS(root, unsafePath, te.fsEval)\n\tif err != nil {\n\t\t// We hit a symlink loop -- which is fine but that means that this\n\t\t// cannot be considered a dirlink.\n\t\tif errno := InnerErrno(err); errno == unix.ELOOP {\n\t\t\terr = nil\n\t\t}\n\t\treturn false, errors.Wrap(err, \"sanitize old target\")\n\t}\n\n\ttargetInfo, err := te.fsEval.Lstat(targetPath)\n\tif err != nil {\n\t\t// ENOENT or similar just means that it's a broken symlink, which\n\t\t// means we have to overwrite it (but it's an allowed case).\n\t\tif securejoin.IsNotExist(err) {\n\t\t\terr = nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn targetInfo.IsDir(), nil\n}", "func symlinkDirectoriesOnly(srcDir string, destDir string) (err error) {\n\tsrcInfo, err := os.Stat(srcDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(destDir, srcInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdirectory, err := os.Open(srcDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer directory.Close()\n\tobjects, err := directory.Readdir(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, obj := range objects {\n\t\tsrcPath := filepath.Join(srcDir, obj.Name())\n\t\tdestPath := filepath.Join(destDir, obj.Name())\n\n\t\tif obj.IsDir() {\n\t\t\terr = symlinkFile(srcPath, destPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}", "func (fs osFsEval) Symlink(target, linkname string) error {\n\treturn os.Symlink(target, linkname)\n}", "func (fl *FolderList) Symlink(\n\t_ context.Context, _ *fuse.SymlinkRequest) (fs.Node, error) {\n\treturn nil, fuse.ENOTSUP\n}", "func (fs *Mysqlfs) Symlink(target, link string) error {\n\t_, err := fs.Stat(link)\n\tif err == nil {\n\t\treturn os.ErrExist\n\t}\n\n\tif !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\treturn util.WriteFile(fs, link, []byte(target), 0777|os.ModeSymlink)\n}", "func Symlink(target, link string) error {\n\treturn os.Symlink(target, link)\n}", "func (_Bfs *BfsCaller) Readlink(opts *bind.CallOpts, absolutePath string) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Bfs.contract.Call(opts, out, \"readlink\", absolutePath)\n\treturn *ret0, err\n}", "func (fs FileSystem) Symlink(oldname, newname string) error {\n\tfs.testDriver()\n\toldname = filepath.FromSlash(oldname)\n\tnewname = filepath.FromSlash(newname)\n\treturn fs.drv.Symlink(oldname, newname)\n}", "func (*FileSystemBase) Readlink(path string) (int, string) {\n\treturn -ENOSYS, \"\"\n}", "func (RealOS) Symlink(oldname string, newname string) error {\n\treturn os.Symlink(oldname, newname)\n}", "func (suite *fileTestSuite) TestLinkRead() {\n\tfileName := suite.testPath + \"/small_write1.txt\"\n\tf, err := os.Create(fileName)\n\tsuite.Equal(nil, err)\n\tf.Close()\n\n\tsymName := suite.testPath + \"/small.lnk\"\n\terr = os.Symlink(fileName, symName)\n\tsuite.Equal(nil, err)\n\n\terr = ioutil.WriteFile(fileName, suite.minBuff, 0777)\n\tsuite.Equal(nil, err)\n\tdata, err := ioutil.ReadFile(fileName)\n\tsuite.Equal(nil, err)\n\tsuite.Equal(len(data), len(suite.minBuff))\n\tsuite.fileTestCleanup([]string{fileName})\n\terr = os.Remove(symName)\n\tsuite.Equal(nil, err)\n}", "func collectLinkPaths(target string) ([]string, error) {\n\tcontents, err := ioutil.ReadFile(target)\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"Failure to read file '%s'. Err: %s\", string(contents), err)\n\t}\n\n\tm := mdlinkparser.New(string(contents))\n\tm.ParseLinks()\n\n\treturn m.Links, nil\n}", "func (fs *Mysqlfs) ReadDir(path string) ([]os.FileInfo, error) {\n\tf, err := fs.storage.GetFile(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f != nil {\n\t\tif target, isLink := fs.resolveLink(path, f); isLink {\n\t\t\treturn fs.ReadDir(target)\n\t\t}\n\t}\n\n\tvar entries []os.FileInfo\n\tchildren, err := fs.storage.Children(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, f := range children {\n\t\tfi, _ := f.Stat()\n\t\tentries = append(entries, fi)\n\t}\n\n\treturn entries, nil\n}", "func (util copyHandlerUtil) evaluateSymlinkPath(path string) (string, error) {\n\tif len(path) == 0 {\n\t\treturn \"\", fmt.Errorf(\"cannot evaluate empty symlinkPath\")\n\t}\n\tsymLinkPath, err := filepath.EvalSymlinks(path)\n\tif err != nil {\n\t\t// Network drives are not evaluated using the api \"filepath.EvalSymlinks\" since it returns error for the network drives.\n\t\t// So readlink api is used to evaluate the symlinks.\n\t\tsymLinkPath, err = os.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error %s evaluating symlink path %s\", err.Error(), path)\n\t\t}\n\t}\n\t// If the evaluated symlinkPath is same as the given path,\n\t// then path cannot be evaluated due to some reason and to avoid\n\t// indefinite recursive calls, this check is added.\n\tif symLinkPath == path {\n\t\treturn \"\", fmt.Errorf(\"symlink path %s evaluated back to itself\", path)\n\t}\n\treturn symLinkPath, nil\n}", "func (w *wrapper) Symlink(target, newpath string) int {\n\tif sfs, ok := w.underlying.(billy.Symlink); ok {\n\t\treturn convertError(sfs.Symlink(target, newpath))\n\t}\n\treturn -fuse.ENOSYS\n}", "func Link(s, d string) error {\n\tif err := createDir(d); err != nil {\n\t\treturn err\n\t}\n\tif err := link(s, d); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func readlinkat(directory int, path string, buffer []byte) (int, error) {\n\t// Extract a raw pointer to the path bytes.\n\tvar pathBytes *byte\n\tpathBytes, err := unix.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Extract a raw pointer to the buffer bytes.\n\tvar bufferBytes *byte\n\tif len(buffer) > 0 {\n\t\tbufferBytes = &buffer[0]\n\t}\n\n\t// Perform the system call.\n\tn, _, errnoErr := sysvicall6(uintptr(unsafe.Pointer(&procReadlinkat)), 4, uintptr(directory), uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(bufferBytes)), uintptr(len(buffer)), 0, 0)\n\tif errnoErr != 0 {\n\t\treturn 0, errnoErr\n\t}\n\n\t// Success.\n\treturn int(n), nil\n}", "func (fsys *FS) Symlink(target string, newpath string) (errc int) {\n\tdefer fs.Trace(target, \"newpath=%q\", newpath)(\"errc=%d\", &errc)\n\treturn -fuse.ENOSYS\n}", "func (storage *PublishedStorage) ReadLink(path string) (string, error) {\n\tparams := &s3.HeadObjectInput{\n\t\tBucket: aws.String(storage.bucket),\n\t\tKey: aws.String(filepath.Join(storage.prefix, path)),\n\t}\n\toutput, err := storage.s3.HeadObject(params)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn aws.StringValue(output.Metadata[\"SymLink\"]), nil\n}", "func (c *ldcache) resolve(target string) (string, error) {\n\tname := filepath.Join(c.root, target)\n\n\tc.logger.Debugf(\"checking %v\", string(name))\n\n\tinfo, err := os.Lstat(name)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get file info: %v\", info)\n\t}\n\tif info.Mode()&os.ModeSymlink == 0 {\n\t\tc.logger.Debugf(\"Resolved regular file: %v\", name)\n\t\treturn name, nil\n\t}\n\n\tlink, err := os.Readlink(name)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to resolve symlink: %v\", err)\n\t}\n\n\t// We return absolute paths for all targets\n\tif !filepath.IsAbs(link) || strings.HasPrefix(link, \".\") {\n\t\tlink = filepath.Join(filepath.Dir(target), link)\n\t}\n\n\treturn c.resolve(link)\n}", "func (fs osFsEval) Link(target, linkname string) error {\n\t// We need to explicitly pass 0 as a flag because POSIX allows the default\n\t// behaviour of link(2) when it comes to target being a symlink to be\n\t// implementation-defined. Only linkat(2) allows us to guarantee the right\n\t// behaviour.\n\t// <https://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html>\n\treturn unix.Linkat(unix.AT_FDCWD, target, unix.AT_FDCWD, linkname, 0)\n}", "func (f *File) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) {\n\tino := f.info.Inode\n\tinfo, err := f.super.InodeGet(ino)\n\tif err != nil {\n\t\tlog.LogErrorf(\"Readlink: ino(%v) err(%v)\", ino, err)\n\t\treturn \"\", ParseError(err)\n\t}\n\tlog.LogDebugf(\"TRACE Readlink: ino(%v) target(%v)\", ino, string(info.Target))\n\treturn string(info.Target), nil\n}", "func (wfs *WFS) Symlink(cancel <-chan struct{}, header *fuse.InHeader, target string, name string, out *fuse.EntryOut) (code fuse.Status) {\n\n\tif wfs.IsOverQuota {\n\t\treturn fuse.Status(syscall.ENOSPC)\n\t}\n\tif s := checkName(name); s != fuse.OK {\n\t\treturn s\n\t}\n\n\tdirPath, code := wfs.inodeToPath.GetPath(header.NodeId)\n\tif code != fuse.OK {\n\t\treturn\n\t}\n\tentryFullPath := dirPath.Child(name)\n\n\trequest := &filer_pb.CreateEntryRequest{\n\t\tDirectory: string(dirPath),\n\t\tEntry: &filer_pb.Entry{\n\t\t\tName: name,\n\t\t\tIsDirectory: false,\n\t\t\tAttributes: &filer_pb.FuseAttributes{\n\t\t\t\tMtime: time.Now().Unix(),\n\t\t\t\tCrtime: time.Now().Unix(),\n\t\t\t\tFileMode: uint32(os.FileMode(0777) | os.ModeSymlink),\n\t\t\t\tUid: header.Uid,\n\t\t\t\tGid: header.Gid,\n\t\t\t\tSymlinkTarget: target,\n\t\t\t},\n\t\t},\n\t\tSignatures: []int32{wfs.signature},\n\t\tSkipCheckParentDirectory: true,\n\t}\n\n\terr := wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {\n\n\t\twfs.mapPbIdFromLocalToFiler(request.Entry)\n\t\tdefer wfs.mapPbIdFromFilerToLocal(request.Entry)\n\n\t\tif err := filer_pb.CreateEntry(client, request); err != nil {\n\t\t\treturn fmt.Errorf(\"symlink %s: %v\", entryFullPath, err)\n\t\t}\n\n\t\twfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tglog.V(0).Infof(\"Symlink %s => %s: %v\", entryFullPath, target, err)\n\t\treturn fuse.EIO\n\t}\n\n\tinode := wfs.inodeToPath.Lookup(entryFullPath, request.Entry.Attributes.Crtime, false, false, 0, true)\n\n\twfs.outputPbEntry(out, inode, request.Entry)\n\n\treturn fuse.OK\n}", "func resolveSymlinkAncestor(path string) (string, error) {\n\tif !filepath.IsAbs(path) {\n\t\treturn \"\", errors.New(\"dest path must be abs\")\n\t}\n\n\tlast := \"\"\n\tnewPath := filepath.Clean(path)\n\nloop:\n\tfor newPath != config.RootDir {\n\t\tfi, err := os.Lstat(newPath)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"resolvePaths: failed to lstat\")\n\t\t}\n\n\t\tif util.IsSymlink(fi) {\n\t\t\tlast = filepath.Base(newPath)\n\t\t\tnewPath = filepath.Dir(newPath)\n\t\t} else {\n\t\t\t// Even if the filenode pointed to by newPath is a regular file,\n\t\t\t// one of its ancestors could be a symlink. We call filepath.EvalSymlinks\n\t\t\t// to test whether there are any links in the path. If the output of\n\t\t\t// EvalSymlinks is different than the input we know one of the nodes in the\n\t\t\t// path is a link.\n\t\t\ttarget, err := filepath.EvalSymlinks(newPath)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tif target != newPath {\n\t\t\t\tlast = filepath.Base(newPath)\n\t\t\t\tnewPath = filepath.Dir(newPath)\n\t\t\t} else {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}\n\tnewPath = filepath.Join(newPath, last)\n\treturn filepath.Clean(newPath), nil\n}", "func ListSymlink(root string) (entries []*FilePathInfo, err error) {\n\treturn listCondEntries(root, func(info os.FileInfo) (bool, error) { return isSymlinkFi(&info), nil })\n}", "func TestEvalSymlinksAboveRootChdir(t *testing.T) {\n\ttestenv.MustHaveSymlink(t)\n\n\ttmpDir, err := os.MkdirTemp(\"\", \"TestEvalSymlinksAboveRootChdir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\tchdir(t, tmpDir)\n\n\tsubdir := filepath.Join(\"a\", \"b\")\n\tif err := os.MkdirAll(subdir, 0777); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Symlink(subdir, \"c\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.WriteFile(filepath.Join(subdir, \"file\"), nil, 0666); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tsubdir = filepath.Join(\"d\", \"e\", \"f\")\n\tif err := os.MkdirAll(subdir, 0777); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Chdir(subdir); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcheck := filepath.Join(\"..\", \"..\", \"..\", \"c\", \"file\")\n\twantSuffix := filepath.Join(\"a\", \"b\", \"file\")\n\tif resolved, err := filepath.EvalSymlinks(check); err != nil {\n\t\tt.Errorf(\"EvalSymlinks(%q) failed: %v\", check, err)\n\t} else if !strings.HasSuffix(resolved, wantSuffix) {\n\t\tt.Errorf(\"EvalSymlinks(%q) = %q does not end with %q\", check, resolved, wantSuffix)\n\t} else {\n\t\tt.Logf(\"EvalSymlinks(%q) = %q\", check, resolved)\n\t}\n}", "func (l *LinuxFileSystem) ReadDir(dirname string) ([]os.FileInfo, error) {\n\treturn ioutil.ReadDir(dirname)\n}", "func (suite *fileTestSuite) TestLinkDeleteReadTarget() {\n\tfileName := suite.testPath + \"/small_write1.txt\"\n\tsymName := suite.testPath + \"/small.lnk\"\n\tf, err := os.Create(fileName)\n\tsuite.Equal(nil, err)\n\tf.Close()\n\terr = os.Symlink(fileName, symName)\n\tsuite.Equal(nil, err)\n\terr = ioutil.WriteFile(fileName, suite.minBuff, 0777)\n\tsuite.Equal(nil, err)\n\n\terr = os.Remove(symName)\n\tsuite.Equal(nil, err)\n\n\tdata, err := ioutil.ReadFile(fileName)\n\tsuite.Equal(nil, err)\n\tsuite.Equal(len(data), len(suite.minBuff))\n\n\terr = os.Symlink(fileName, symName)\n\tsuite.Equal(nil, err)\n\tsuite.fileTestCleanup([]string{fileName})\n\terr = os.Remove(symName)\n\tsuite.Equal(nil, err)\n}", "func dDirectory() (string, error) {\n\tpath, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to find homedir: %v\", err)\n\t}\n\n\tdDir := filepath.Join(path, anchovies)\n\t// ignore errors here - just try to create it\n\terr = os.Mkdir(dDir, fileMode)\n\tif err != nil {\n\t\tlogger.Debug(err.Error())\n\t}\n\t// Lstat will follow sym links\n\t_, err = os.Lstat(dDir)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to Stat(): %v\", err)\n\t}\n\treturn dDir, nil\n}", "func (o ApplicationStatusSyncComparedToSourcePtrOutput) Directory() ApplicationStatusSyncComparedToSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToSource) *ApplicationStatusSyncComparedToSourceDirectory {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Directory\n\t}).(ApplicationStatusSyncComparedToSourceDirectoryPtrOutput)\n}", "func (nm2md NM2MD) Symlink(destMaildir *maildir.Maildir, fileList []string) []error {\n\tvar errs []error\n\tvar swg sizedwaitgroup.SizedWaitGroup = sizedwaitgroup.New(swgLimit)\n\tfor _, file := range fileList {\n\t\tswg.Add()\n\t\tgo func(file string) {\n\t\t\tdefer swg.Done()\n\t\t\terr := destMaildir.SymlinkFile(file)\n\t\t\tif err != nil {\n\t\t\t\tutils.PrintDebugErrorMsg(err, nm2md.ApplicationOptions.Debug)\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t}(file)\n\t}\n\tswg.Wait()\n\tif len(errs) > 0 {\n\t\tutils.PrintDebugMsg(\"Some files can not be linked - this usually happens if the maildir and the notmuch index are not synced. Try to run `notmuch new'\", nm2md.ApplicationOptions.Debug)\n\t}\n\treturn errs\n}", "func TestSymlinkat(t *testing.T) {\n\terr := unix.Symlinkat(\"/foo/bar/baz\", tmpDirFd, \"symlink1\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar st syscall.Stat_t\n\terr = syscall.Lstat(tmpDir+\"/symlink1\", &st)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsymlinkCheckMode(t, st)\n\t// Test with absolute path\n\terr = unix.Symlinkat(\"/foo/bar/baz\", -1, tmpDir+\"/symlink2\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = syscall.Lstat(tmpDir+\"/symlink2\", &st)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsymlinkCheckMode(t, st)\n}", "func SymlinkRelative(srcPath, dstPath string) error {\n\tbaseDir := filepath.Dir(dstPath)\n\tsrcPathRel, err := filepath.Rel(baseDir, srcPath)\n\tif err != nil {\n\t\treturn stacktrace.Propagate(err, \"cannot make relative path for srcPath=%q: %w\", srcPath, err)\n\t}\n\terr = os.Symlink(srcPathRel, dstPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Link(target, link string) error {\n\treturn os.Link(target, link)\n}", "func (imd *Directory) AddSymlink(name, target string, permissions os.FileMode) *Symlink {\n\timd, name = imd.resolveSubdir(name)\n\tsl := &Symlink{\n\t\tentry: entry{\n\t\t\tname: name,\n\t\t\tmode: permissions | os.ModeSymlink,\n\t\t\tsize: int64(len(target)),\n\t\t\tmodTime: DefaultModTime,\n\t\t},\n\t\ttarget: target,\n\t}\n\n\timd.addChild(sl)\n\n\treturn sl\n}", "func Link() error {\n\tmg.Deps(Build)\n\n\tfmt.Println(\"linking ./build to workflow directory ...\")\n\ttarget := filepath.Join(info.AlfredWorkflowDir, info.BundleID)\n\t// fmt.Printf(\"target: %s\\n\", target)\n\n\tif util.PathExists(target) {\n\t\tfmt.Println(\"removing existing workflow ...\")\n\t}\n\t// try to remove it anyway, as dangling symlinks register as existing\n\tif err := os.RemoveAll(target); err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tsrc, err := filepath.Abs(buildDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn build.Symlink(target, src, true)\n}", "func (o ApplicationStatusHistorySourceOutput) Directory() ApplicationStatusHistorySourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusHistorySource) *ApplicationStatusHistorySourceDirectory { return v.Directory }).(ApplicationStatusHistorySourceDirectoryPtrOutput)\n}", "func (f *FakeFileSystem) Symlink(oldname, newname string) error {\n\tf.SymlinkOldname, f.SymlinkNewname = oldname, newname\n\treturn f.SymlinkError\n}", "func IsLink(f string) bool {\n\tinfoL, _ := os.Lstat(f)\n\treturn infoL.Mode()&os.ModeSymlink == os.ModeSymlink\n}", "func (o ApplicationOperationSyncSourceOutput) Directory() ApplicationOperationSyncSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSource) *ApplicationOperationSyncSourceDirectory { return v.Directory }).(ApplicationOperationSyncSourceDirectoryPtrOutput)\n}", "func (*FileSystemBase) Symlink(target string, newpath string) int {\n\treturn -ENOSYS\n}", "func (dr *dependencyResolver) readDir(\n\trelPath string) (entries []os.FileInfo, err error) {\n\t// Note that ioutil.ReadDir guarantees that the output is sorted by name.\n\tentries, err = ioutil.ReadDir(path.Join(dr.basePath, relPath))\n\treturn\n}", "func (options *ConformanceTestOptions) GetLinkerdPath() string {\n\treturn options.LinkerdBinaryPath\n}", "func (fs StdFileSystem) readDir(curFile filesystem.File, parent *filesystem.FileTree) *filesystem.FileTree {\n\ttree := &filesystem.FileTree{}\n\ttree.StdFile = curFile\n\ttree.StdParentNode = parent\n\n\t// TODO: Symlink check not working...\n\tif curFile.IsDir() || curFile.Mode() == os.ModeSymlink {\n\n\t\ttree.StdChildNodes = make([]*filesystem.FileTree, 0)\n\t\tdirListing, _ := fs.Dir(curFile.Path())\n\t\tif dirListing != nil && len(dirListing) > 0 {\n\t\t\tfor _, file := range dirListing {\n\t\t\t\ttree.StdChildNodes = append(tree.StdChildNodes, fs.readDir(file, tree))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tree\n}", "func (m *wasiSnapshotPreview1Impl) pathReadlink(pfd wasiFd, ppath list, pbuf pointer, pbufLen wasiSize) (rv wasiSize, err wasiErrno) {\n\tpath, err := m.loadPath(ppath)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\tdir, err := m.files.getDirectory(pfd, wasiRightsPathReadlink)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\tdest, ferr := dir.ReadLink(path)\n\tif ferr != nil {\n\t\treturn 0, fileErrno(ferr)\n\t}\n\treturn wasiSize(copy(m.slice(pbuf, pbufLen), dest)), wasiErrnoSuccess\n}", "func (o ApplicationOperationSyncSourcePtrOutput) Directory() ApplicationOperationSyncSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationOperationSyncSource) *ApplicationOperationSyncSourceDirectory {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Directory\n\t}).(ApplicationOperationSyncSourceDirectoryPtrOutput)\n}", "func (o ApplicationStatusSyncComparedToSourceOutput) Directory() ApplicationStatusSyncComparedToSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSource) *ApplicationStatusSyncComparedToSourceDirectory {\n\t\treturn v.Directory\n\t}).(ApplicationStatusSyncComparedToSourceDirectoryPtrOutput)\n}", "func symlinkat(target string, directory int, path string) error {\n\t// Extract a raw pointer to the target path bytes.\n\tvar targetBytes *byte\n\ttargetBytes, err := unix.BytePtrFromString(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Extract a raw pointer to the path bytes.\n\tvar pathBytes *byte\n\tpathBytes, err = unix.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Perform the system call.\n\t_, _, errnoErr := sysvicall6(uintptr(unsafe.Pointer(&procSymlinkat)), 3, uintptr(unsafe.Pointer(targetBytes)), uintptr(directory), uintptr(unsafe.Pointer(pathBytes)), 0, 0, 0)\n\tif errnoErr != 0 {\n\t\treturn errnoErr\n\t}\n\n\t// Success.\n\treturn nil\n}", "func (o FunctionBuildConfigSourceRepoSourcePtrOutput) Dir() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FunctionBuildConfigSourceRepoSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Dir\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusHistorySourcePtrOutput) Directory() ApplicationStatusHistorySourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusHistorySource) *ApplicationStatusHistorySourceDirectory {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Directory\n\t}).(ApplicationStatusHistorySourceDirectoryPtrOutput)\n}", "func (o ApplicationSpecSourceOutput) Directory() ApplicationSpecSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSource) *ApplicationSpecSourceDirectory { return v.Directory }).(ApplicationSpecSourceDirectoryPtrOutput)\n}", "func (o ApplicationSpecSourcePtrOutput) Directory() ApplicationSpecSourceDirectoryPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecSource) *ApplicationSpecSourceDirectory {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Directory\n\t}).(ApplicationSpecSourceDirectoryPtrOutput)\n}", "func symlink(source string, target string) error {\n\tsourceTmp := source + \".tmp\"\n\n\tif err := os.Remove(sourceTmp); err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tif err := os.Symlink(target, sourceTmp); err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.Rename(sourceTmp, source); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o TriggerBuildSourceRepoSourcePtrOutput) Dir() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuildSourceRepoSource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Dir\n\t}).(pulumi.StringPtrOutput)\n}", "func GetSampleSymlinksEval(vfs avfs.Featurer) []*SymlinkEval {\n\tif !vfs.HasFeature(avfs.FeatSymlink) {\n\t\treturn nil\n\t}\n\n\tsl := []*SymlinkEval{\n\t\t{NewName: \"/A/lroot/\", OldName: \"/\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o777},\n\t\t{NewName: \"/A/lroot/B\", OldName: \"/B\", WantErr: nil, IsSymlink: false, Mode: os.ModeDir | 0o755},\n\t\t{NewName: \"/C/lNonExist\", OldName: \"A/path\", WantErr: avfs.ErrNoSuchFileOrDir, IsSymlink: true},\n\t\t{NewName: \"/\", OldName: \"/\", WantErr: nil, IsSymlink: false, Mode: os.ModeDir | 0o777},\n\t\t{NewName: \"/lC\", OldName: \"/C\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o750},\n\t\t{NewName: \"/B/1/lafile2.txt\", OldName: \"/A/afile2.txt\", WantErr: nil, IsSymlink: true, Mode: 0o644},\n\t\t{NewName: \"/B/2/lf\", OldName: \"/B/2/F\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o755},\n\t\t{NewName: \"/B/2/F/3/llf\", OldName: \"/B/2/F\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o755},\n\t\t{NewName: \"/C/lllf\", OldName: \"/B/2/F\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o755},\n\t\t{NewName: \"/B/2/F/3/llf\", OldName: \"/B/2/F\", WantErr: nil, IsSymlink: true, Mode: os.ModeDir | 0o755},\n\t\t{NewName: \"/C/lllf/3/3file1.txt\", OldName: \"/B/2/F/3/3file1.txt\", WantErr: nil, IsSymlink: false, Mode: 0o640},\n\t}\n\n\treturn sl\n}", "func Symlink(handler handlers.SymlinkHandler) starlark.Fn {\n\treturn func(thread *lib.Thread, b *lib.Builtin, args lib.Tuple, kwargs []lib.Tuple) (lib.Value, error) {\n\t\tctx := starlark.GetCtx(thread)\n\t\tdryrun := starlark.GetDryRunMode(thread)\n\t\tparams, err := parseSymlinkArgs(b, args, kwargs)\n\t\tif err != nil {\n\t\t\treturn lib.None, xerrors.Errorf(\": %w\", err)\n\t\t}\n\n\t\tzap.L().Debug(\n\t\t\t\"params\",\n\t\t\tzap.String(\"source\", params.Src),\n\t\t\tzap.String(\"destination\", params.Dest),\n\t\t)\n\t\tui.Infof(\"Creating symbolic link. Source: %s, Destination: %s\\n\", params.Src, params.Dest)\n\t\tif err := handler.Symlink(ctx, dryrun, params); err != nil {\n\t\t\treturn lib.None, xerrors.Errorf(\": %w\", err)\n\t\t}\n\t\treturn lib.None, nil\n\t}\n}", "func (f *attachEmbedFS) ReadDir(name string) ([]fs.DirEntry, error) {\n\treturn f.EmbedFS.ReadDir(f.path(name))\n}", "func (bucket Bucket) GetSymlink(objectKey string) (http.Header, error) {\n\tparams := map[string]interface{}{}\n\tparams[\"symlink\"] = nil\n\tresp, err := bucket.do(\"GET\", objectKey, params, nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\ttargetObjectKey := resp.Headers.Get(HTTPHeaderOssSymlinkTarget)\n\ttargetObjectKey, err = url.QueryUnescape(targetObjectKey)\n\tif err != nil {\n\t\treturn resp.Headers, err\n\t}\n\tresp.Headers.Set(HTTPHeaderOssSymlinkTarget, targetObjectKey)\n\treturn resp.Headers, err\n}", "func (v *Module) GetDirectory() (o string) {\n\tif v != nil {\n\t\to = v.Directory\n\t}\n\treturn\n}", "func (md *MetaData) RelativeDateDirectory() string {\n\tt := md.PreferredDate()\n\n\treturn filepath.Join(fmt.Sprintf(\"%d\", t.Year()), fmt.Sprintf(\"%02d-%s\", t.Month(), shortmonths[t.Month()-1]), fmt.Sprintf(\"%d\", t.Day()))\n\n}", "func tempDirCanonical(t *testing.T) string {\n\tdir := t.TempDir()\n\n\tcdir, err := filepath.EvalSymlinks(dir)\n\tif err != nil {\n\t\tt.Errorf(\"tempDirCanonical: %v\", err)\n\t}\n\n\treturn cdir\n}" ]
[ "0.82489735", "0.74302715", "0.74302715", "0.72412324", "0.72412324", "0.70619404", "0.70619404", "0.65928644", "0.64262915", "0.626165", "0.6092517", "0.5905284", "0.5882868", "0.5882868", "0.5813754", "0.56942576", "0.5689624", "0.5641771", "0.5584948", "0.55402905", "0.55207586", "0.5493676", "0.54837865", "0.54592365", "0.544412", "0.53991497", "0.5371465", "0.53444463", "0.5272275", "0.524755", "0.52412194", "0.52343565", "0.52333516", "0.5227327", "0.52025765", "0.5180966", "0.51669085", "0.51132697", "0.50998473", "0.50976217", "0.5075351", "0.50728506", "0.50649434", "0.5056412", "0.50487745", "0.5048446", "0.5033712", "0.50191456", "0.50075686", "0.5004168", "0.4992681", "0.4982091", "0.49816588", "0.49717915", "0.49248418", "0.49131018", "0.4886294", "0.48753348", "0.48692596", "0.48562846", "0.48375183", "0.48357654", "0.48354056", "0.48347384", "0.4833555", "0.48321122", "0.4791642", "0.47733393", "0.47730464", "0.4765726", "0.47654563", "0.47567162", "0.47359115", "0.4730205", "0.4729917", "0.4725138", "0.4724769", "0.47243708", "0.47167554", "0.47161552", "0.47090533", "0.4701615", "0.46971077", "0.46935403", "0.46901745", "0.4689066", "0.46864596", "0.46848184", "0.4675551", "0.46721905", "0.46672067", "0.46670973", "0.46541965", "0.46535367", "0.46530813", "0.46451068", "0.46445286", "0.46435466", "0.46184495" ]
0.81918585
2
TreeSize walks a directory tree and returns its total size in bytes.
func TreeSize(dir string) (size int64, err error) { data := make(map[uint64]struct{}) err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { // Ignore directory sizes if fileInfo == nil { return nil } s := fileInfo.Size() if fileInfo.IsDir() || s == 0 { return nil } // Check inode to handle hard links correctly inode := fileInfo.Sys().(*syscall.Stat_t).Ino // inode is not a uint64 on all platforms. Cast it to avoid issues. if _, exists := data[uint64(inode)]; exists { return nil } // inode is not a uint64 on all platforms. Cast it to avoid issues. data[uint64(inode)] = struct{}{} size += s return nil }) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (te *TreeEntry) Size() int64 {\n\tif te.IsDir() {\n\t\treturn 0\n\t} else if te.sized {\n\t\treturn te.size\n\t}\n\n\tfile, err := te.ptree.gogitTree.TreeEntryFile(te.gogitTreeEntry)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tte.sized = true\n\tte.size = file.Size\n\treturn te.size\n}", "func (n *Node) GetTreeSize() (treesize uint64, err error) {\n\tvar b []byte\n\tif b, err = xattr.Get(n.InternalPath(), xattrs.TreesizeAttr); err != nil {\n\t\treturn\n\t}\n\treturn strconv.ParseUint(string(b), 10, 64)\n}", "func (te *TreeEntry) Size() int64 {\n\tif te.IsDir() {\n\t\treturn 0\n\t} else if te.sized {\n\t\treturn te.size\n\t}\n\n\twr, rd, cancel := te.ptree.repo.CatFileBatchCheck(te.ptree.repo.Ctx)\n\tdefer cancel()\n\t_, err := wr.Write([]byte(te.ID.String() + \"\\n\"))\n\tif err != nil {\n\t\tlog.Debug(\"error whilst reading size for %s in %s. Error: %v\", te.ID.String(), te.ptree.repo.Path, err)\n\t\treturn 0\n\t}\n\t_, _, te.size, err = ReadBatchLine(rd)\n\tif err != nil {\n\t\tlog.Debug(\"error whilst reading size for %s in %s. Error: %v\", te.ID.String(), te.ptree.repo.Path, err)\n\t\treturn 0\n\t}\n\n\tte.sized = true\n\treturn te.size\n}", "func (n *Node) GetTreeSize(ctx context.Context) (treesize uint64, err error) {\n\tctx, span := tracer.Start(ctx, \"GetTreeSize\")\n\tdefer span.End()\n\ts, err := n.XattrUint64(ctx, prefixes.TreesizeAttr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn s, nil\n}", "func Size(targetDir string) (int64, error) {\n\tfm, err := Walk(targetDir)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar size int64\n\tfor _, v := range fm {\n\t\tsize += v.Size()\n\t}\n\treturn size, nil\n}", "func DirSize(path string) (size int64, err error) {\n\terr = filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}", "func DirSize(path string) (int64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}", "func getDirSizeRecursive(root string, fs *afero.Afero) (uint64, map[string]int, map[string]uint64, error) {\n\tvar totalSize uint64\n\tvar extFileCount = make(map[string]int)\n\tvar extByteCount = make(map[string]uint64)\n\n\terr := fs.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif info == nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\ttotalSize += uint64(info.Size())\n\t\t\text := filepath.Ext(path)\n\t\t\textFileCount[ext] += 1\n\t\t\textByteCount[ext] += uint64(info.Size())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, extFileCount, extByteCount, err\n\t}\n\n\treturn totalSize, extFileCount, extByteCount, nil\n}", "func DirSize(path string) (int64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}", "func dirSize(path string) (float64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tsize += 0\n\t\t} else {\n\t\t\tif !info.IsDir() {\n\t\t\t\tsize += info.Size()\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tr, _ := decimal.NewFromFloat(float64(size) / (1024 * 1024 * 1024)).Round(2).Float64()\n\treturn r, err\n}", "func (tree *UTree) Size() int {\r\n\treturn tree.size\r\n}", "func (t *Tree) Size() uint {\n\tif t.Safe {\n\t\tdefer t.mtx.RUnlock()\n\t\tt.mtx.RLock()\n\t}\n\n\treturn t.size + 1\n}", "func (t *Tree) Size() int {\n\treturn t.root.Size()\n}", "func (tree *BinaryTree) Size() int {\n\treturn Size(tree.root)\n}", "func (tree *Tree) Size() int {\n\treturn tree.size\n}", "func (e *BackupEnv) GetDirSize(source string) (int64) {\n directory, _ := os.Open(source);\n var sum int64 = 0;\n defer directory.Close();\n\n objects, _ := directory.Readdir(-1)\n for _, obj := range objects {\n if obj.IsDir() {\n sum += e.GetDirSize(source + \"/\" + obj.Name());\n } else {\n stat, _ := os.Stat(source + \"/\" + obj.Name());\n sum += stat.Size();\n }\n }\n\n return sum;\n}", "func folderSize(startPath string) (totalSize int64) {\n\terr := filepath.WalkDir(startPath,\n\t\tfunc(path string, entry os.DirEntry, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !entry.IsDir() {\n\t\t\t\tinfo, err := entry.Info()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttotalSize += info.Size()\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\tlogger.Print(err)\n\t}\n\treturn\n}", "func DirSizeB(path string) (int64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}", "func DirSize2(path string) (int64, error) {\r\n\tvar size int64\r\n\tadjSize := func(_ string, info os.FileInfo, err error) error {\r\n\t\tif !info.IsDir() {\r\n\t\t\tsize += info.Size()\r\n\t\t}\r\n\t\treturn err\r\n\t}\r\n\terr := filepath.Walk(path, adjSize)\r\n\r\n\treturn size, err\r\n}", "func (d Directory) Size() int { return binary.Size(d) }", "func (n *TreeNode) GetSize() (size uint64) {\n\tn.mutex.RLock()\n\tsize = n.size\n\tn.mutex.RUnlock()\n\treturn\n}", "func (t *AATree) Size() int {\n\tif t.root == nil {\n\t\treturn 0\n\t}\n\t// return t.root\n\treturn 0\n}", "func (t Tree) Size() int {\n\tif t.Symbol.Kind == NIL {\n\t\treturn 0\n\t}\n\n\tcount := 1\n\tfor _, child := range t.Children {\n\t\tif child != nil {\n\t\t\tcount += child.Size()\n\t\t}\n\t}\n\n\treturn count\n}", "func getDirSize(path string) (float64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\tsizeGB := float64(size) / 1024.0 / 1024.0 / 1024.0\n\treturn toFixed(sizeGB, 3), err\n}", "func (t *BinaryTree) Size() int { return t.count }", "func (r *StorageImpl) GetDelayedTreeSize(ctx context.Context, qid string) (int64, error) {\n\tvar res int64\n\tif err := retry(ctx, func() error {\n\t\tvar err error\n\t\tif res, err = r.client.ZCount(keyTreeDelayed(qid), \"-inf\", \"+inf\").Result(); err != nil {\n\t\t\treturn newTempError(err)\n\t\t}\n\t\treturn nil\n\t}, defaultRetryLimit); err != nil {\n\t\treturn -1, errors.Wrap(err, \"ZCOUNT\")\n\t}\n\n\treturn res, nil\n}", "func (d *Dtrie) Size() (size int) {\n\tfor _ = range iterate(d.root, nil) {\n\t\tsize++\n\t}\n\treturn size\n}", "func DirSize(dir string, excludes []string) (int, error) {\n\targs := []string{\"-bs\", dir}\n\tfor _, s := range excludes {\n\t\targs = append(args, fmt.Sprintf(\"--exclude=\\\"%s\\\"\", s))\n\t}\n\n\tcmd := exec.Command(\"/usr/bin/du\", args...)\n\tdata, err := cmd.Output()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn strconv.Atoi(strings.Split(string(data), \"\\t\")[0])\n}", "func DirSizeByte(path string) uint64 {\n\tdirSize = 0\n\tfilepath.Walk(path, readSize)\n\treturn dirSize\n}", "func (t *RedBlackTree) Size() int {\n\treturn t.size\n}", "func (n *ModuleTreeNode) Size() int {\n\ts := len(n.Modules)\n\tfor _, c := range n.Children {\n\t\ts += c.Size()\n\t}\n\treturn s\n}", "func (h *BSTHandler) CalculateTreeWidth() {\n\n}", "func HashTreeSize(leafs Nodes) int64 {\n\treturn HashNumber(leafs, Levels(leafs), 0)\n}", "func (s *FileSet) TotalFileSize() int64 {\n\tvar result int64\n\ts.Walk(func(f string) {\n\t\tinfo, err := os.Stat(f)\n\t\tif err != nil {\n\t\t\tlog.Error().Str(\"file\", f).Msg(\"Could not stat\")\n\t\t}\n\t\tresult += info.Size()\n\t})\n\treturn result\n}", "func (t *TreeEntry) GetSize() int {\n\tif t == nil || t.Size == nil {\n\t\treturn 0\n\t}\n\treturn *t.Size\n}", "func (e DirectoryEntry) Size() int { return binary.Size(e) }", "func (mts *MapTreeState) TreeSize() int64 {\n\treturn mts.MapTreeHead.MutationLog.TreeSize\n}", "func (p *Trie) Size() (sz int) {\n\tsz = len(p.children)\n\n\tfor _, child := range p.children {\n\t\tsz += child.Size()\n\t}\n\n\treturn\n}", "func (d *Dirent) Size() int {\n\treturn direntSize + len(d.Name) + 8\n}", "func GetDirSizeMB(path string) float64 {\n\tvar dirSize int64\n\treadSize := func(path string, file os.FileInfo, err error) error {\n\t\tif !file.IsDir() {\n\t\t\tdirSize += file.Size()\n\t\t}\n\t\treturn nil\n\t}\n\tfilepath.Walk(path, readSize)\n\tsizeMB := float64(dirSize) / 1024.0 / 1024.0\n\treturn sizeMB\n}", "func Size() int {\n\treturn len(directory)\n}", "func (i *Item) Size() int64 { return int64(i.directoryEntry.FileSize) }", "func (n *TreeBuilderNode) Size() uint64 { return n.size }", "func (t *RbTree[K, V]) Size() int {\n\treturn t.size\n}", "func scanDir(path string, depth int) int64 {\n\t//read content of folder\n\tosfiles, _ := ioutil.ReadDir(path)\n\n\tvar dirsize int64\n\n\t//calc total size throught folder content\n\tfor _, osfile := range osfiles {\n\n\t\tfile := scanFile(path, osfile.Name(), depth)\n\t\tif file.IsDir {\n\t\t\tnewpath := addPathSeparator(path + osfile.Name())\n\t\t\tfile.Size = scanDir(newpath, depth+1)\n\t\t}\n\n\t\tsetAdaptedFileSize(file, units)\n\t\tdirsize += file.Size\n\t\t*Files = append(*Files, *file)\n\t}\n\n\treturn dirsize\n}", "func (w *RootWalker) Size() int {\n\treturn len(w.stack)\n}", "func (w *RootWalker) Size() int {\n\treturn len(w.stack)\n}", "func (s *Service) dagSize(ctx context.Context, root path.Path) (int64, error) {\n\tif root == nil {\n\t\treturn 0, nil\n\t}\n\tstat, err := s.IPFSClient.Object().Stat(ctx, root)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"getting dag size: %v\", err)\n\t}\n\treturn int64(stat.CumulativeSize), nil\n}", "func (i *Inode) Size() int64 {\n\tif i.IsDir() {\n\t\treturn 0\n\t}\n\treturn i.dataStore.GetSize(i.path)\n}", "func (t *BinarySearchTree) Size() int {\n\treturn 0\n}", "func (t *Tree) GetTreeTotal() int {\n\treturn t.Total\n}", "func (d *Directory) updateDirectorySize(p string) {\n\tpathParams := strings.Split(p, \"/\")\n\td.Size = 0\n\td.lock()\n\tdefer d.unlock()\n\tfor i := 0; i < len(d.INodes); i++ {\n\t\tswitch d.INodes[i].(type) {\n\t\tcase *Directory:\n\t\t\tif d.INodes[i].GetName() == pathParams[1] {\n\t\t\t\tsubPath := strings.Join(pathParams[2:], \"/\")\n\t\t\t\tsubPath = \"/\" + subPath\n\t\t\t\td.INodes[i].(*Directory).updateDirectorySize(subPath)\n\t\t\t}\n\t\t\td.Size += d.INodes[i].GetSize()\n\t\tcase *File:\n\t\t\td.Size += d.INodes[i].GetSize()\n\t\t}\n\t}\n}", "func (t *Tree) Size(lo, hi int) int {\n\tresult := rank(t.Tree, hi) - rank(t.Tree, lo)\n\tif contains(t.Tree, hi) {\n\t\tresult++\n\t}\n\treturn result\n}", "func (n *Node) SetTreeSize(ts uint64) (err error) {\n\treturn xattr.Set(n.InternalPath(), xattrs.TreesizeAttr, []byte(strconv.FormatUint(ts, 10)))\n}", "func Size(root *BinaryNode) int {\n\tif root != nil {\n\t\treturn Size(root.Left) + Size(root.Right) + 1\n\t}\n\treturn 0\n\n}", "func (t *Tree) Len() int { return t.Count }", "func (dm *DagModifier) Size() (int64, error) {\n\tfileSize, err := FileSize(dm.curNode)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif dm.wrBuf != nil && int64(dm.wrBuf.Len())+int64(dm.writeStart) > int64(fileSize) {\n\t\treturn int64(dm.wrBuf.Len()) + int64(dm.writeStart), nil\n\t}\n\treturn int64(fileSize), nil\n}", "func (bst *BST) Size() int {\n\treturn bst.size\n}", "func subtreeSize(x uint, n uint) uint {\n\tw := nodeWidth(n)\n\tlr := uint((1 << level(x)) - 1)\n\trr := uint(lr)\n\tif x+rr >= w {\n\t\trr = w - x - 1\n\t}\n\n\treturn (lr+rr)/2 + 1\n}", "func (c *DirentCache) Size() uint64 {\n\tif c == nil {\n\t\treturn 0\n\t}\n\tc.mu.Lock()\n\tsize := c.currentSize\n\tc.mu.Unlock()\n\treturn size\n}", "func (t *Tree) Count() int {\n\tif t.root != nil {\n\t\treturn t.root.size\n\t}\n\n\treturn 0\n}", "func (n *RuleTreeNode) Size() int {\n\ts := len(n.Rules)\n\tfor _, c := range n.Children {\n\t\ts += c.Size()\n\t}\n\treturn s\n}", "func (f *file) Size() (size int64) {\n\tif f.Object != nil {\n\t\tsize = *f.Object.Size\n\t} else {\n\t\tfor _, ff := range f.files {\n\t\t\tsize += ff.Size()\n\t\t}\n\t}\n\treturn\n}", "func (oe *OrderEngine) Size() int {\n\tif oe == nil || oe.Tree == nil {\n\t\treturn 0\n\t}\n\n\tvar size int\n\n\tit := oe.Tree.Iterator()\n\tfor it.Next() {\n\t\torderTree := it.Value().(*rbt.Tree)\n\t\tsize += orderTree.Size()\n\t}\n\treturn size\n}", "func (n node) GetSize() int {\n\treturn n.size\n}", "func (d Dir) Len() int { return len(d.contents) }", "func (db *DB) FileSize() (int64, error) {\n\tvar size int64\n\tfiles, err := db.opts.FileSystem.ReadDir(\".\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor _, file := range files {\n\t\tsize += file.Size()\n\t}\n\treturn size, nil\n}", "func (node *Node) Size() int {\n\tif node == nil {\n\t\treturn 0\n\t}\n\tsize := 1\n\tif node.Left != nil {\n\t\tsize += node.Left.Size()\n\t}\n\tif node.Right != nil {\n\t\tsize += node.Right.Size()\n\t}\n\treturn size\n}", "func (f *FileList) SubSize(dir string) uint64 {\n\t_, _, size := f.NSubDirsAndFiles(dir)\n\treturn size\n}", "func (fc FileCollection) totalFileSize() (uint64,error)\t{\n\tvar tfsize uint64\n\tfor _,fsize := range fc.fileSizes {\n\t\tdirectory := fmt.Sprintf(\"%s/d-%d\",fc.frandi,fsize)\n\t\tfileList,err := getFilesInDir(directory)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"totalSizeFiles(): Error listing directory: %s\\n%s\",directory,err.Error())\n\t\t\treturn 0,err\n\t\t}\n\t\tfor _,v := range fileList {\n\t\t\ttfsize += uint64(v.Size())\n\t\t}\n\t}\n\treturn tfsize,nil\n}", "func (t *Trie) Size() int {\n\treturn t.root.pass\n}", "func (me *TrieNode) Size() int {\n\tif me == nil {\n\t\treturn 0\n\t}\n\treturn int(me.size)\n}", "func (hat *HashedArrayTree) Size() int {\n\treturn hat.size\n}", "func (t *TreeMap) Size() int {\n\treturn t.size\n}", "func (n *Node) GetBlobSize(ctx context.Context) (treesize uint64, err error) {\n\ts, err := n.XattrInt64(ctx, prefixes.BlobsizeAttr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(s), nil\n}", "func walkDir(root, dir string, n *sync.WaitGroup, fileSizes chan<- size) {\n\tdefer n.Done()\n\tfor _, entry := range dirents(dir) {\n\t\tif entry.IsDir() {\n\t\t\tn.Add(1)\n\t\t\tsubdir := filepath.Join(dir, entry.Name())\n\t\t\tgo walkDir(root, subdir, n, fileSizes)\n\t\t} else {\n\t\t\tfileSizes <- size{\n\t\t\t\troot: root,\n\t\t\t\tsz: entry.Size(),\n\t\t\t}\n\t\t}\n\t}\n}", "func (o ClusterNodeGroupDataDiskOutput) Size() pulumi.IntOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupDataDisk) int { return v.Size }).(pulumi.IntOutput)\n}", "func walkDir(dir string, fileSizes chan<- int64) {\n\tfor _, entry := range dirents(dir) {\n\t\tif entry.IsDir() {\n\t\t\tsubdir := filepath.Join(dir, entry.Name())\n\t\t\twalkDir(subdir, fileSizes)\n\t\t} else {\n\t\t\tfileSizes <- entry.Size()\n\t\t}\n\t}\n}", "func (tf tFiles) size() (sum int64) {\n\tfor _, t := range tf {\n\t\tsum += t.size\n\t}\n\treturn sum\n}", "func (t *Tree) Len() int {\n\treturn t.Count\n}", "func readSize(path string, file os.FileInfo, err error) error {\n\tif !file.IsDir() {\n\t\tdirSize += uint64(file.Size())\n\t}\n\treturn nil\n}", "func (lh *LHash) Size() (int64, error) {\n\tres, _, err := lh.Conn.RunTransaction(func(txn *client.Txn) (interface{}, error) {\n\t\terr := lh.populate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn lh.root.Size, nil\n\t})\n\tif err == nil {\n\t\treturn res.(int64), nil\n\t} else {\n\t\treturn -1, err\n\t}\n}", "func (tree *BTree) Length() int {\n\tif tree.isset {\n\t\tif tree.length == 0 {\n\t\t\ttree.length = tree.uncachedLength()\n\t\t}\n\t\treturn tree.length\n\t}\n\treturn 0\n}", "func (n *Node) Size() int {\n\tif n == nil {\n\t\treturn 0\n\t}\n\treturn n.size\n}", "func (bt *Tree) Length() int {\n\treturn bt.length\n}", "func (b *BTree) Len() int {\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\treturn int(b.rootNod.GetLength())\n}", "func (d *dataUsageCache) sizeRecursive(path string) *dataUsageEntry {\n\troot := d.find(path)\n\tif root == nil || len(root.Children) == 0 {\n\t\treturn root\n\t}\n\tflat := d.flatten(*root)\n\treturn &flat\n}", "func (bst *Bst) Size() float64 {\n\treturn bst.size\n}", "func (s *Store) StorageSize(path string) (uint64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\t// if err is not nil, info will be nil and makes agent panic\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn uint64(size), err\n}", "func (o ClusterNodeGroupSystemDiskOutput) Size() pulumi.IntOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroupSystemDisk) int { return v.Size }).(pulumi.IntOutput)\n}", "func (n *FileEntry) GetSize() uint64 {\n\treturn n.size\n}", "func (me *inode) TotalOpenCount() int {\n\to := 0\n\tif me.mountPoint != nil {\n\t\tme.mountPoint.treeLock.RLock()\n\t\tdefer me.mountPoint.treeLock.RUnlock()\n\n\t\tme.mountPoint.openFilesLock.RLock()\n\t\tdefer me.mountPoint.openFilesLock.RUnlock()\n\n\t\to += len(me.mountPoint.openFiles)\n\t}\n\n\tfor _, v := range me.Children {\n\t\to += v.TotalOpenCount()\n\t}\n\treturn o\n}", "func findSize(root *binaryTree.BinaryTree) int {\n\tif root == nil {\n\t\treturn 0\n\t} else {\n\t\treturn findSize(root.LeftNode) + 1 + findSize(root.RightNode)\n\t}\n}", "func (ftp *FTP) Size(path string) (size int, err error) {\n\tline, err := ftp.cmd(\"213\", \"SIZE %s\", path)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn strconv.Atoi(line[4 : len(line)-2])\n}", "func (f *File) Size() (uint64, error) {\n\tattr, err := f.getObjectAttrs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(attr.Size), nil\n}", "func (i *FileInfo) Size() int64 { return i.size }", "func (d DirEntries) Len() int { return len(d) }", "func calculateTarballSize(imageToTags map[v1.Image][]string, mBytes []byte) (size int64, err error) {\n\tseenLayerDigests := make(map[string]struct{})\n\tfor img, name := range imageToTags {\n\t\tmanifest, err := img.Manifest()\n\t\tif err != nil {\n\t\t\treturn size, fmt.Errorf(\"unable to get manifest for img %s: %w\", name, err)\n\t\t}\n\t\tsize += calculateSingleFileInTarSize(manifest.Config.Size)\n\t\tfor _, l := range manifest.Layers {\n\t\t\thex := l.Digest.Hex\n\t\t\tif _, ok := seenLayerDigests[hex]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseenLayerDigests[hex] = struct{}{}\n\t\t\tsize += calculateSingleFileInTarSize(l.Size)\n\t\t}\n\t}\n\t// add the manifest\n\tsize += calculateSingleFileInTarSize(int64(len(mBytes)))\n\n\t// add the two padding blocks that indicate end of a tar file\n\tsize += 1024\n\treturn size, nil\n}", "func (st *Store) Size() float64 {\n\tvar size int64\n\tfor i := 1; uint64(i) < st.StoreId; i++ {\n\t\tif info, err := os.Lstat(fmt.Sprintf(\"db/%s/%d.json\", st.Name, i)); err == nil {\n\t\t\tsize += info.Size()\n\t\t}\n\t}\n\treturn toFixed(float64(size)/float64(1<<10), 2)\n}", "func (fi *fileInfo) Size() int64 { return fi.size }" ]
[ "0.7321087", "0.72382784", "0.7166616", "0.7147079", "0.70924777", "0.684575", "0.68154067", "0.6787004", "0.6782293", "0.67177826", "0.6700878", "0.6695152", "0.66194427", "0.6565779", "0.65331274", "0.65112704", "0.64923567", "0.64891195", "0.647969", "0.6475776", "0.64737433", "0.6454866", "0.644595", "0.6442725", "0.64251775", "0.6376061", "0.6349387", "0.63284034", "0.6264622", "0.6243342", "0.6219023", "0.62136847", "0.61656994", "0.6153651", "0.6135345", "0.6133842", "0.6116016", "0.61058515", "0.6073275", "0.605533", "0.60125923", "0.6005805", "0.60011595", "0.5964049", "0.59600776", "0.593966", "0.593966", "0.5936687", "0.59200853", "0.5897703", "0.58761626", "0.58683026", "0.57905185", "0.5780541", "0.5772738", "0.5750868", "0.57506526", "0.5744253", "0.57413876", "0.5740639", "0.57039404", "0.5674402", "0.56575894", "0.5595862", "0.5569924", "0.5554517", "0.5546633", "0.5539363", "0.55328655", "0.5517681", "0.55144006", "0.55091596", "0.54993254", "0.5485958", "0.5485392", "0.54697585", "0.54630107", "0.5458726", "0.544763", "0.5438241", "0.54257536", "0.5425141", "0.5411507", "0.5401817", "0.53991", "0.53899914", "0.5387048", "0.5384494", "0.537481", "0.53722984", "0.5372131", "0.5365719", "0.5364041", "0.5336897", "0.53354216", "0.5334874", "0.53312147", "0.5322984", "0.5317141", "0.5305686" ]
0.83847123
0
ValidateContextDirectory checks if all the contents of the directory can be read and returns an error if some files can't be read symlinks which point to nonexisting files don't trigger an error
func ValidateContextDirectory(srcPath string) error { var finalError error filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { // skip this directory/file if it's not in the path, it won't get added to the context _, err = filepath.Rel(srcPath, filePath) if err != nil && os.IsPermission(err) { return nil } if _, err = os.Stat(filePath); err != nil && os.IsPermission(err) { finalError = fmt.Errorf("can't stat '%s'", filePath) return err } // skip checking if symlinks point to non-existing files, such symlinks can be useful lstat, _ := os.Lstat(filePath) if lstat.Mode()&os.ModeSymlink == os.ModeSymlink { return err } if !f.IsDir() { currentFile, err := os.Open(filePath) if err != nil && os.IsPermission(err) { finalError = fmt.Errorf("no permission to read from '%s'", filePath) return err } else { currentFile.Close() } } return nil }) return finalError }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func validateDockerContextDirectory(srcPath string, excludes []string) error {\n\n\treturn filepath.Walk(filepath.Join(srcPath, \".\"), func(filePath string, f os.FileInfo, err error) error {\n\t\t// skip this directory/file if it's not in the path, it won't get added to the context\n\t\tif relFilePath, err := filepath.Rel(srcPath, filePath); err != nil {\n\t\t\treturn err\n\t\t} else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {\n\t\t\treturn err\n\t\t} else if skip {\n\t\t\tif f.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif os.IsPermission(err) {\n\t\t\t\treturn fmt.Errorf(\"can't stat '%s'\", filePath)\n\t\t\t}\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// skip checking if symlinks point to non-existing files, such symlinks can be useful\n\t\t// also skip named pipes, because they hanging on open\n\t\tif f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !f.IsDir() {\n\t\t\tcurrentFile, err := os.Open(filePath)\n\t\t\tif err != nil && os.IsPermission(err) {\n\t\t\t\treturn fmt.Errorf(\"no permission to read from '%s'\", filePath)\n\t\t\t}\n\t\t\tcurrentFile.Close()\n\t\t}\n\t\treturn nil\n\t})\n}", "func ValidateDir(src string) string {\n\td, err := ioutil.ReadDir(src)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err.Error()\n\t}\n\n\t// totalFiles := len(d)\n\t// fmt.Println(\"Total Files\", totalFiles)\n\t// fmt.Println(\"Start Validating files...\")\n\n\ttmpReport := \"\"\n\tfor _, v := range d {\n\t\ttmpfilepath := src + \"/\" + v.Name()\n\t\t// fmt.Println(\"tmpfilepath\", tmpfilepath)\n\t\ttmpReport += ValidateFile(src, tmpfilepath)\n\t\t// err, _ =\n\t\t// if err != nil {\n\t\t// \tfmt.Println(\"\\n\", v.Name())\n\t\t// \tfmt.Println(err)\n\t\t// }\n\t}\n\n\treturn tmpReport\n}", "func checkDirectory(dir *Directory, fileSize uint64) error {\n\tfiles := map[string]struct{}{}\n\n\tfor filename, info := range dir.Files {\n\t\tvar err error\n\n\t\t// validate filename (not duplicate, canonical, etc)\n\t\tif _, dup := files[filename]; dup {\n\t\t\terr = fmt.Errorf(\"duplicate path %q\", filename)\n\t\t}\n\t\tfiles[filename] = struct{}{}\n\n\t\tif !path.IsAbs(filename) {\n\t\t\terr = fmt.Errorf(\"relative path %q\", filename)\n\t\t}\n\t\tif path.Clean(filename) != filename {\n\t\t\terr = fmt.Errorf(\"non-canonical path %q\", filename)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn &LoadError{\n\t\t\t\tCause: InvalidPath,\n\t\t\t\tUnderlying: err,\n\t\t\t\tPath: filename,\n\t\t\t}\n\t\t}\n\n\t\t// ensure uncompressed data is present\n\t\tif info.Uncompressed == nil {\n\t\t\treturn &LoadError{\n\t\t\t\tCause: MissingUncompressed,\n\t\t\t\tPath: filename,\n\t\t\t}\n\t\t}\n\n\t\t// validate offsets\n\t\tcheckOffset(&err, filename, info.Uncompressed, fileSize)\n\t\tcheckOffset(&err, filename, info.Gzip, fileSize)\n\t\tcheckOffset(&err, filename, info.Brotli, fileSize)\n\t\tif err != nil {\n\t\t\treturn &LoadError{\n\t\t\t\tCause: BadOffsetError,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func checkValidDirWithContents(name string) bool {\n\titems, err := ioutil.ReadDir(name)\n\tif os.IsNotExist(err) {\n\t\tglog.Warningf(\"Unable to access directory %q: %v\", name, err)\n\t}\n\treturn !(err != nil || len(items) == 0)\n}", "func (m *ShadowcopyAddFiles) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func Validate(d interface{}) error {\n\tnames := make(map[string]bool)\n\n\tsubs, err := subdirs(d)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not get subdirectories: %w\", err)\n\t}\n\n\tfor _, nd := range subs {\n\t\tif nd.name == \"\" {\n\t\t\treturn fmt.Errorf(\"subdirectory with empty name\")\n\t\t}\n\t\tif strings.Contains(nd.name, \"/\") {\n\t\t\treturn fmt.Errorf(\"subdirectory with invalid path: %q\", nd.name)\n\t\t}\n\t\tif names[nd.name] {\n\t\t\treturn fmt.Errorf(\"subdirectory with duplicate name: %q\", nd.name)\n\t\t}\n\t\tnames[nd.name] = true\n\n\t\terr := Validate(nd.directory)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: %w\", nd.name, err)\n\t\t}\n\t}\n\n\tfilelist, err := files(d)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not get files: %w\", err)\n\t}\n\n\tfor _, nf := range filelist {\n\t\tif nf.name == \"\" {\n\t\t\treturn fmt.Errorf(\"file with empty name\")\n\t\t}\n\t\tif strings.Contains(nf.name, \"/\") {\n\t\t\treturn fmt.Errorf(\"file with invalid path: %q\", nf.name)\n\t\t}\n\t\tif names[nf.name] {\n\t\t\treturn fmt.Errorf(\"file with duplicate name: %q\", nf.name)\n\t\t}\n\t\tnames[nf.name] = true\n\t}\n\treturn nil\n}", "func (m *MountNfs) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func validateFilesInDir(src string, expectedFilesInDir []string) {\n\t// List all files in the folder recursively\n\tfilesInDir := make([]string, 0)\n\terr := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Don't include the folder itself\n\t\tif filepath.Clean(path) == filepath.Clean(src) {\n\t\t\treturn nil\n\t\t}\n\t\trelPath, err := filepath.Rel(src, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trelPath = filepath.ToSlash(relPath)\n\t\tif info.IsDir() {\n\t\t\trelPath += \"/\"\n\t\t}\n\t\tfilesInDir = append(filesInDir, relPath)\n\t\treturn nil\n\t})\n\tΩ(err).Should(Succeed())\n\n\tfor _, expectedFile := range expectedFilesInDir {\n\t\tΩ(contains(expectedFile, filesInDir)).Should(BeTrue(), fmt.Sprintf(\"expected %s to be in the directory; directory contains %v\", expectedFile, filesInDir))\n\t}\n\tfor _, existingFile := range filesInDir {\n\t\tΩ(contains(existingFile, expectedFilesInDir)).Should(BeTrue(), fmt.Sprintf(\"did not expect %s to be in the directory; directory contains %v\", existingFile, filesInDir))\n\t}\n}", "func (m *QuarantineQuarantinedFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidatePaths(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *FileMoveFileInlineVolume) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *FileMoveFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSvm(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVolume(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func checkDir(dataDir string) {\n\tif !fsutil.IsDir(dataDir) {\n\t\tprintError(\"Target %s is not a directory\", dataDir)\n\t\tos.Exit(1)\n\t}\n\n\tif !fsutil.IsExist(dataDir) {\n\t\tprintError(\"Directory %s is not exist\", dataDir)\n\t\tos.Exit(1)\n\t}\n\n\tif !fsutil.IsReadable(dataDir) {\n\t\tprintError(\"Directory %s is not readable\", dataDir)\n\t\tos.Exit(1)\n\t}\n\n\tif !fsutil.IsExecutable(dataDir) {\n\t\tprintError(\"Directory %s is not exectable\", dataDir)\n\t\tos.Exit(1)\n\t}\n\n\tif arg.GetS(ARG_OUTPUT) == \"\" && !fsutil.IsWritable(dataDir) {\n\t\tprintError(\"Directory %s is not writable\", dataDir)\n\t\tos.Exit(1)\n\t}\n}", "func (m *LunAttribute) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLun(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ElfDataStore) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateCluster(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIscsiTarget(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNfsExport(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNvmfSubsystem(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateManifestDir(dir string) error {\n\tinfo, err := os.Stat(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) { // don't return error if there is no such a dir, just ignore it\n\t\t\treturn NewProcessingError(nil) // return error, but don't stop processing\n\t\t}\n\t\treturn NewProcessingError(err)\n\t}\n\n\tif !info.IsDir() {\n\t\terr := fmt.Errorf(\"%s is not a directory\", dir)\n\t\treturn NewProcessingError(err) // return error\n\t}\n\n\treturn nil\n}", "func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {\n\tvar path string\n\tvar err error\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/test/foo/Non/ExistingPath\"); err == nil {\n\t\tt.Fatalf(\"error expected for non-existing symlink\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"expected empty path, but '%s' was returned\", path)\n\t}\n}", "func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) {\n\tvar path string\n\tvar err error\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/test/foo/Non/ExistingPath\"); err == nil {\n\t\tt.Fatalf(\"error expected for non-existing symlink\")\n\t}\n\n\tif path != \"\" {\n\t\tt.Fatalf(\"expected empty path, but '%s' was returned\", path)\n\t}\n}", "func (m *FileMoveFileInlineSvm) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateDir(dir string) (validationErrors []string, err error) {\n\tmpath := yamlPath(dir)\n\tyml, err := os.ReadFile(mpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dat any\n\terr = yaml.Unmarshal(yml, &dat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn util.ValidateSchemaFromFS(\"schemas/choria/machine/v1/manifest.json\", dat)\n}", "func (c *Config) validate() error {\n\tdataDir, err := filepath.Abs(c.DataDir)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tlogFile, err := filepath.Abs(c.Log.File.Filename)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\trel, err := filepath.Rel(dataDir, filepath.Dir(logFile))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif !strings.HasPrefix(rel, \"..\") {\n\t\treturn errors.New(\"log directory shouldn't be the subdirectory of data directory\")\n\t}\n\n\treturn nil\n}", "func (m *FileMoveFileInlineVolumeInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *SnaplockLitigationFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func TestValidateSourceDirThatExists(t *testing.T) {\n\ta := assert.New(t)\n\tbsc := getBlobServiceClient()\n\n\t// Generate source container and blobs\n\tcc, containerName := createNewContainer(a, bsc)\n\tdefer deleteContainer(a, cc)\n\ta.NotNil(cc)\n\n\tdirName := \"source_dir\"\n\tcreateNewDirectoryStub(a, cc, dirName)\n\t// set up to create blob traverser\n\tctx := context.WithValue(context.TODO(), ste.ServiceAPIVersionOverride, ste.DefaultServiceApiVersion)\n\n\t// List\n\trawBlobURLWithSAS := scenarioHelper{}.getBlobClientWithSAS(a, containerName, dirName).URL()\n\tserviceClientWithSAS := scenarioHelper{}.getBlobServiceClientWithSASFromURL(a, rawBlobURLWithSAS)\n\tblobTraverser := newBlobTraverser(rawBlobURLWithSAS, serviceClientWithSAS, ctx, true, true, func(common.EntityType) {}, false, common.CpkOptions{}, false, false, false, common.EPreservePermissionsOption.None(), false)\n\n\t// dir but recursive flag not set - fail\n\tcca := CookedCopyCmdArgs{StripTopDir: false, Recursive: false}\n\terr := cca.validateSourceDir(blobTraverser)\n\ta.Equal(\"cannot use directory as source without --recursive or a trailing wildcard (/*)\", err.Error())\n\n\t// dir but recursive flag set - pass\n\tcca.Recursive = true\n\terr = cca.validateSourceDir(blobTraverser)\n\ta.Nil(err)\n\ta.True(cca.IsSourceDir)\n}", "func ValidateContext(ctx *scheduler.Context, errChan ...*chan error) {\n\tdefer func() {\n\t\tif len(errChan) > 0 {\n\t\t\tclose(*errChan[0])\n\t\t}\n\t}()\n\tginkgo.Describe(fmt.Sprintf(\"For validation of %s app\", ctx.App.Key), func() {\n\t\tvar timeout time.Duration\n\t\tappScaleFactor := time.Duration(Inst().GlobalScaleFactor)\n\t\tif ctx.ReadinessTimeout == time.Duration(0) {\n\t\t\ttimeout = appScaleFactor * defaultTimeout\n\t\t} else {\n\t\t\ttimeout = appScaleFactor * ctx.ReadinessTimeout\n\t\t}\n\n\t\tStep(fmt.Sprintf(\"validate %s app's volumes\", ctx.App.Key), func() {\n\t\t\tif !ctx.SkipVolumeValidation {\n\t\t\t\tValidateVolumes(ctx, errChan...)\n\t\t\t}\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"wait for %s app to start running\", ctx.App.Key), func() {\n\t\t\terr := Inst().S.WaitForRunning(ctx, timeout, defaultRetryInterval)\n\t\t\tif err != nil {\n\t\t\t\tprocessError(err, errChan...)\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\n\t\tStep(fmt.Sprintf(\"validate if %s app's volumes are setup\", ctx.App.Key), func() {\n\t\t\tif ctx.SkipVolumeValidation {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvols, err := Inst().S.GetVolumes(ctx)\n\t\t\tprocessError(err, errChan...)\n\n\t\t\tfor _, vol := range vols {\n\t\t\t\tStep(fmt.Sprintf(\"validate if %s app's volume: %v is setup\", ctx.App.Key, vol), func() {\n\t\t\t\t\terr := Inst().V.ValidateVolumeSetup(vol)\n\t\t\t\t\tprocessError(err, errChan...)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t})\n}", "func (m *ServiceBindingVolumeMount) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateDevice(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *LunAttributeInlineLun) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateUUID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (d *Dir) Valid() bool {\n\treturn len(d.Filename) > 0 && len(d.Package) > 0\n}", "func samplesValidatedDirectory(samplesDirectory string) string {\n\treturn filepath.Join(samplesDirectory, \"validated\")\n}", "func check_dir() {\n\tnames := []string{\n\t\t\"conf.json\",\n\t\t\"templates/index.html\",\n\t\t\"templates/cat-index.html\",\n\t\t\"templates/category-index.html\",\n\t\t\"templates/post.html\",\n\t\t\"templates/base.html\",\n\t\t\"templates/archive.html\",\n\t\t\"templates/page.html\",\n\t\t\"templates/year.html\"}\n\tfor i := range names {\n\t\tif !exists(names[i]) {\n\t\t\tfmt.Println(names[i], \"is missing from current directory.\")\n\t\t\tos.Exit(-10)\n\t\t}\n\t}\n\n}", "func (m *ElfImageWhereInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAND(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNOT(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateOR(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCluster(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateContentLibraryImage(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatus(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusIn(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusNot(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusNotIn(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsEvery(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsNone(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsSome(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMDisksEvery(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMDisksNone(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMDisksSome(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMSnapshotsEvery(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMSnapshotsNone(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMSnapshotsSome(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMTemplatesEvery(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMTemplatesNone(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMTemplatesSome(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (options *OptionsDirectory) Check() error {\n\n\tif options.Config != \"\" {\n\t\terr := ensureDirExists(options.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := ensureOrCreateDir(options.Runtime)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ensureOrCreateDir(options.Storage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ensureOrCreateDir(options.Data)\n}", "func (o *ListPeerFoldersBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func samplesToBeValidatedDirectory(samplesDirectory string) string {\n\treturn filepath.Join(samplesDirectory, \"to_be_validated\")\n}", "func (m *Coredump) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIsPartial(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIsSaved(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMd5DataChecksum(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateName(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNode(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidatePanicTime(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSize(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateFile(src, file, want, dir string) error {\n\tf, err := os.Stat(src)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to stat %s\", src)\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn errors.Wrapf(err, \"wrong OCI output format; got: %v, want: %s\", err, file)\n\t}\n\tif f.Size() == 0 {\n\t\treturn fmt.Errorf(\"error occured: empty %s, size: %d\", file, f.Size())\n\t}\n\tif err = compareSHA(path.Join(dir, file), want); err != nil {\n\t\treturn errors.Wrapf(err, \"sha256 hex code for %s did not match\", src)\n\t}\n\n\treturn nil\n}", "func (m *FileMoveFileInlineSvmInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *VersionedFlow) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateBucketName(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCreatedTimestamp(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIdentifier(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLink(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateModifiedTimestamp(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidatePermissions(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateRevision(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVersionCount(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *MountBind) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateMount(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateDataDirectory(directory string) (string, error) {\n\tif directory == \"\" {\n\t\treturn os.Getwd()\n\t}\n\t// Further validation of the data directory will happen implicitly\n\t// when Boltdb tries to access or create its data file\n\t// This value should be ignored if memorydb is used\n\treturn directory, nil\n}", "func checkForNonDirectories(path string) error {\n\tp := \"/\"\n\tfor _, component := range util.SplitPath(path) {\n\t\tp = filepath.Join(p, component)\n\t\tst, err := os.Lstat(p)\n\t\tif err != nil && os.IsNotExist(err) {\n\t\t\treturn nil // nonexistent is ok\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !st.Mode().IsDir() {\n\t\t\treturn fmt.Errorf(\"mount path %q contains non-directory component %q\", path, p)\n\t\t}\n\t}\n\treturn nil\n}", "func checkProviderTargetDir(dir string) error {\n\tif !fsutil.CheckPerms(\"DRWX\", dir) {\n\t\treturn fmt.Errorf(\"This utility requires read/write access to directory %s\", dir)\n\t}\n\n\treturn nil\n}", "func (m *TopMetricsSvmDirectoryExcludedVolumeInlineVolume) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *WriterOptions) Validate() error {\n\tif _, err := o.inFs.Stat(o.InputDir); err != nil {\n\t\treturn fmt.Errorf(\"invalid input directory '%s' %v\", o.InputDir, err)\n\t}\n\treturn nil\n}", "func (m *NfsInodeWhereInput) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAND(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNOT(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateOR(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatus(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusIn(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusNot(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateEntityAsyncStatusNotIn(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsEvery(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsNone(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabelsSome(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNfsExport(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *WritableL2VPN) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateCreated(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDisplay(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLastUpdated(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateTags(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateURL(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *KibanaDeeplink) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *ExtensionMetadata) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateBundleInfo(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDeprecationNotice(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLink(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLinkDocs(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateProvidedServiceAPIs(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateRestricted(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ensureDirectory(dir string) bool {\n if _, err := os.Stat(dir); os.IsNotExist(err) {\n return false\n }\n return true\n}", "func (m *LunAttributeInlineLunInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ro *ReaderOptions) Validate() error {\n\t// if there is no working dir, create one\n\tif ro.WorkDir == \"\" {\n\t\tdir, err := os.MkdirTemp(\"\", \"license-reader-\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"creating working dir: %w\", err)\n\t\t}\n\t\tro.WorkDir = dir\n\t\t// Otherwise, check it exists\n\t} else if _, err := os.Stat(ro.WorkDir); err != nil {\n\t\treturn fmt.Errorf(\"checking working directory: %w\", err)\n\t}\n\n\t// TODO check dirs\n\treturn nil\n}", "func CheckContext(c *cli.Context) {\n\tcontextFiles, err := project.ContextFiles(\".\")\n\tif err != nil {\n\t\tfmt.Print(err)\n\t}\n\n\tfor _, contextFile := range contextFiles {\n\t\tfmt.Println(contextFile)\n\t}\n\n\tfmt.Println(\"\")\n\tfmt.Println(\"============================================================\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Total files: \" + strconv.Itoa(len(contextFiles)))\n}", "func CheckDir(dir string) error {\n\tif dir == \"\" {\n\t\treturn fmt.Errorf(\"no directory specified\")\n\t}\n\tif _, err := os.Stat(dir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"directory does not exist: %v\", dir)\n\t\t}\n\t\treturn fmt.Errorf(\"can't access adirectory (check permissions): %v\", dir)\n\t}\n\treturn nil\n}", "func validateOpenFDs(passFDs []boot.FDMapping) {\n\tpassHostFDs := make(map[int]struct{})\n\tfor _, passFD := range passFDs {\n\t\tpassHostFDs[passFD.Host] = struct{}{}\n\t}\n\tconst selfFDDir = \"/proc/self/fd\"\n\tif err := filepath.WalkDir(selfFDDir, func(path string, d os.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif d.Type() != os.ModeSymlink {\n\t\t\t// All entries are symlinks. Ignore the callback for fd directory itself.\n\t\t\treturn nil\n\t\t}\n\t\tif fdInfo, err := os.Stat(path); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\t// Ignore FDs that are now closed. For example, the FD to selfFDDir that\n\t\t\t\t// was opened by filepath.WalkDir() to read dirents.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"os.Stat(%s) failed: %v\", path, err)\n\t\t} else if !fdInfo.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\t// Uh-oh. This is a directory FD.\n\t\tfdNo, err := strconv.Atoi(d.Name())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"strconv.Atoi(%s) failed: %v\", d.Name(), err)\n\t\t}\n\t\tdirLink, err := os.Readlink(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"os.Readlink(%s) failed: %v\", path, err)\n\t\t}\n\t\tif _, ok := passHostFDs[fdNo]; ok {\n\t\t\t// Passed FDs are allowed to be directories. The user must be knowing\n\t\t\t// what they are doing. Log a warning regardless.\n\t\t\tlog.Warningf(\"Sandbox has access to FD %d, which is a directory for %s\", fdNo, dirLink)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"FD %d is a directory for %s\", fdNo, dirLink)\n\t}); err != nil {\n\t\tutil.Fatalf(\"WalkDir(%s) failed: %v\", selfFDDir, err)\n\t}\n}", "func (m *LunAttributeInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *JVMSystemDiagnosticsSnapshotDTO) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateContentRepositoryStorageUsage(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateFlowFileRepositoryStorageUsage(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateGarbageCollectionDiagnostics(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateProvenanceRepositoryStorageUsage(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *TapeDeviceReference) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNode(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CoredumpResponseInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateNext(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *FullVMConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateBalloon(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateBootSource(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDrives(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLogger(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMachineConfig(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMetrics(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMmdsConfig(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNetworkInterfaces(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVsock(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CifsService) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateAdDomain(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMetric(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNetbios(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateOptions(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSecurity(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateStatistics(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSvm(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *TopMetricsSvmDirectoryExcludedVolumeInlineVolumeInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVMFoldersItems0) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *DockerAttributes) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *NestedModule) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateDevice(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDisplay(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateModuleBay(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateModuleType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateURL(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func assertDirectory(filename string) error {\n\tinfo, err := os.Stat(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting info for %v: %v\", filename, err)\n\t}\n\n\tif !info.IsDir() {\n\t\treturn fmt.Errorf(\"specified path '%v' is not a directory\", filename)\n\t}\n\n\treturn nil\n}", "func ensureDirectory(dir string) bool {\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *ApplicationComponentSnapshot) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateApplication(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateComponent(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCreateTime(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIsPartial(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSvm(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateUUID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *DomainPermission) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *VolumeEfficiencyPolicy) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSchedule(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSvm(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateUUID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (rf *HTTPResFile) IsDirectory() bool {\n\treturn false\n}", "func CheckDir(d string) CheckFn {\n\treturn func(logger LogFn) error {\n\t\tif fi, err := os.Stat(d); err == nil {\n\t\t\tif fi.Mode().IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn errors.ErrFileNotDir\n\t}\n}", "func CheckBatchPaths(batch *base.AdminBatch) error {\n\tvar ErrorString string\n\tfor _, filepaths := range batch.Files {\n\t\tfor _, batchFile := range filepaths {\n\t\t\tfilepath := viper.GetString(\"APP_DATA\") + batchFile.FilePath() // TODO: don't forget to prepend with batchFile.Prefix(), to support files with the \"gzip:\" prefix\n\t\t\tif _, err := os.Stat(filepath); err != nil {\n\t\t\t\tErrorString += filepath + \" is missing (\" + err.Error() + \").\\n\"\n\t\t\t}\n\t\t}\n\t}\n\tif ErrorString != \"\" {\n\t\treturn errors.New(ErrorString)\n\t}\n\treturn nil\n\n}", "func (m *DataResponseV1) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateArchive(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCurrent(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *LatestTimestamp) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CoredumpInlineNode) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *DeviceMappedDevicePolicies) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateAirlock(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateAutomox(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateAwsVerifiedAccess(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDataProtection(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDeviceControl(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateFim(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateFirewall(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateGlobalConfig(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateIdentityProtection(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateJumpcloud(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateKubernetesAdmissionControl(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMobile(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateNetskope(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidatePrevention(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateRemoteResponse(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSca(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSensorUpdate(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSystemTray(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateZtl(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *VolumeEfficiencyPolicyInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CoredumpInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func checkMountDestination(rootfs, dest string) error {\n\tinvalidDestinations := []string{\n\t\t\"/proc\",\n\t}\n\t// White list, it should be sub directories of invalid destinations\n\tvalidDestinations := []string{\n\t\t// These entries can be bind mounted by files emulated by fuse,\n\t\t// so commands like top, free displays stats in container.\n\t\t\"/proc/cpuinfo\",\n\t\t\"/proc/diskstats\",\n\t\t\"/proc/meminfo\",\n\t\t\"/proc/stat\",\n\t\t\"/proc/net/dev\",\n\t}\n\tfor _, valid := range validDestinations {\n\t\tpath, err := filepath.Rel(filepath.Join(rootfs, valid), dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif path == \".\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\tfor _, invalid := range invalidDestinations {\n\t\tpath, err := filepath.Rel(filepath.Join(rootfs, invalid), dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif path == \".\" || !strings.HasPrefix(path, \"..\") {\n\t\t\treturn fmt.Errorf(\"%q cannot be mounted because it is located inside %q\", dest, invalid)\n\t\t}\n\n\t}\n\treturn nil\n}", "func (m *JobJobFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *VMAddDiskParamsData) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateIoPolicy(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMaxBandwidthPolicy(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMaxBandwidthUnit(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMaxIopsPolicy(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMDisks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *VMAddDiskParamsDataVMDisks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateMountDisks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMountNewCreateDisks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {\n\tvar err error\n\tif err = os.Mkdir(\"/tmp/testReadSymlinkToExistingDirectory\", 0777); err != nil {\n\t\tt.Errorf(\"failed to create directory: %s\", err)\n\t}\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToExistingDirectory\", \"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Fatalf(\"failed to read symlink to directory: %s\", err)\n\t}\n\n\tif path != \"/tmp/testReadSymlinkToExistingDirectory\" {\n\t\tt.Fatalf(\"symlink returned unexpected directory: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToExistingDirectory\"); err != nil {\n\t\tt.Errorf(\"failed to remove temporary directory: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) {\n\tvar err error\n\tif err = os.Mkdir(\"/tmp/testReadSymlinkToExistingDirectory\", 0777); err != nil {\n\t\tt.Errorf(\"failed to create directory: %s\", err)\n\t}\n\n\tif err = os.Symlink(\"/tmp/testReadSymlinkToExistingDirectory\", \"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to create symlink: %s\", err)\n\t}\n\n\tvar path string\n\tif path, err = ReadSymlinkedDirectory(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Fatalf(\"failed to read symlink to directory: %s\", err)\n\t}\n\n\tif path != \"/tmp/testReadSymlinkToExistingDirectory\" {\n\t\tt.Fatalf(\"symlink returned unexpected directory: %s\", path)\n\t}\n\n\tif err = os.Remove(\"/tmp/testReadSymlinkToExistingDirectory\"); err != nil {\n\t\tt.Errorf(\"failed to remove temporary directory: %s\", err)\n\t}\n\n\tif err = os.Remove(\"/tmp/dirLinkTest\"); err != nil {\n\t\tt.Errorf(\"failed to remove symlink: %s\", err)\n\t}\n}", "func (rt *renterTester) checkDirInitialized(siaPath string) error {\n\tfullpath := filepath.Join(rt.renter.filesDir, siaPath, siadir.SiaDirExtension)\n\tif _, err := os.Stat(fullpath); err != nil {\n\t\treturn err\n\t}\n\tsiaDir, err := rt.renter.staticDirSet.Open(siaPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to load directory %v metadata: %v\", siaPath, err)\n\t}\n\tdefer siaDir.Close()\n\n\t// Check that health is default value\n\thealth, stuckHealth, lastCheck := siaDir.Health()\n\tif health != siadir.DefaultDirHealth {\n\t\treturn fmt.Errorf(\"Expected Health to be %v, but instead was %v\", siadir.DefaultDirHealth, health)\n\t}\n\tif lastCheck.IsZero() {\n\t\treturn errors.New(\"LastHealthCheckTime was not initialized\")\n\t}\n\tif stuckHealth != siadir.DefaultDirHealth {\n\t\treturn fmt.Errorf(\"Expected Stuck Health to be %v, but instead was %v\", siadir.DefaultDirHealth, stuckHealth)\n\t}\n\t// Check that the HyperspacePath was initialized properly\n\tif siaDir.HyperspacePath() != siaPath {\n\t\treturn fmt.Errorf(\"Expected hyperspacepath to be %v, got %v\", siaPath, siaDir.HyperspacePath())\n\t}\n\treturn nil\n}", "func (m *StoragePoolInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *WritablePowerOutlet) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateOccupied(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCable(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCablePeer(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCablePeerType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateConnectedEndpoint(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateConnectedEndpointReachable(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateConnectedEndpointType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateCreated(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDisplay(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLastUpdated(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateTags(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateURL(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func CheckReadFromPath(f *framework.Framework, pod *v1.Pod, volMode v1.PersistentVolumeMode, directIO bool, path string, len int, seed int64) {\n\tvar pathForVolMode string\n\tvar iflag string\n\n\tif volMode == v1.PersistentVolumeBlock {\n\t\tpathForVolMode = path\n\t} else {\n\t\tpathForVolMode = filepath.Join(path, \"file1.txt\")\n\t}\n\n\tif directIO {\n\t\tiflag = \"iflag=direct\"\n\t}\n\n\tsum := sha256.Sum256(genBinDataFromSeed(len, seed))\n\n\te2evolume.VerifyExecInPodSucceed(f, pod, fmt.Sprintf(\"dd if=%s %s bs=%d count=1 | sha256sum\", pathForVolMode, iflag, len))\n\te2evolume.VerifyExecInPodSucceed(f, pod, fmt.Sprintf(\"dd if=%s %s bs=%d count=1 | sha256sum | grep -Fq %x\", pathForVolMode, iflag, len, sum))\n}", "func validateClassLoaderContextRec(sdkVer int, clcs []*ClassLoaderContext) (bool, error) {\n\tfor _, clc := range clcs {\n\t\tif clc.Host == nil || clc.Device == UnknownInstallLibraryPath {\n\t\t\tif sdkVer == AnySdkVersion {\n\t\t\t\t// Return error if dexpreopt doesn't know paths to one of the <uses-library>\n\t\t\t\t// dependencies. In the future we may need to relax this and just disable dexpreopt.\n\t\t\t\tif clc.Host == nil {\n\t\t\t\t\treturn false, fmt.Errorf(\"invalid build path for <uses-library> \\\"%s\\\"\", clc.Name)\n\t\t\t\t} else {\n\t\t\t\t\treturn false, fmt.Errorf(\"invalid install path for <uses-library> \\\"%s\\\"\", clc.Name)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// No error for compatibility libraries, as Soong doesn't know if they are needed\n\t\t\t\t// (this depends on the targetSdkVersion in the manifest), but the CLC is invalid.\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t\tif valid, err := validateClassLoaderContextRec(sdkVer, clc.Subcontexts); !valid || err != nil {\n\t\t\treturn valid, err\n\t\t}\n\t}\n\treturn true, nil\n}", "func (m *VlanVds) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Cluster) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateApplications(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateArchitecture(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateConnectState(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateConsistencyGroups(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateDatacenters(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateHosts(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateLabels(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateMetroAvailabilityChecklist(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSettings(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateType(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVcenterAccount(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVdses(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMFolders(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVMTemplates(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateVms(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateWitness(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateZones(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func checkBadPath(t *testing.T, file string, desc string, open func(string) error) {\n\tbad := []string{\n\t\t\"/\" + file,\n\t\tfile + \"/.\",\n\t}\n\tif file == \".\" {\n\t\tbad = append(bad, \"/\")\n\t}\n\tif i := strings.Index(file, \"/\"); i >= 0 {\n\t\tbad = append(bad,\n\t\t\tfile[:i]+\"//\"+file[i+1:],\n\t\t\tfile[:i]+\"/./\"+file[i+1:],\n\t\t\tfile[:i]+`\\`+file[i+1:],\n\t\t\tfile[:i]+\"/../\"+file,\n\t\t)\n\t}\n\tif i := strings.LastIndex(file, \"/\"); i >= 0 {\n\t\tbad = append(bad,\n\t\t\tfile[:i]+\"//\"+file[i+1:],\n\t\t\tfile[:i]+\"/./\"+file[i+1:],\n\t\t\tfile[:i]+`\\`+file[i+1:],\n\t\t\tfile+\"/../\"+file[i+1:],\n\t\t)\n\t}\n\n\tfor _, b := range bad {\n\t\tassert.Error(t, open(b))\n\t}\n}", "func (m *AbstractAPIRepository) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m PartitionUsage) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *VolumeEfficiencyPolicyInlineSvm) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *SnapshotPolicyInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidDir(dir string) (valid bool) {\n\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\tlog.Println(\"directory does not exist\")\n\t\treturn\n\t}\n\n\tnew := filepath.Join(dir, \"tempDir\")\n\n\tif err := os.Mkdir(new, 0755); err != nil {\n\t\tlog.Println(\"unable to create directory\")\n\t\treturn\n\t}\n\n\tif err := os.Remove(new); err != nil {\n\t\tlog.Println(\"unable to remove directory\")\n\t\treturn\n\t}\n\n\treturn true\n\n}", "func (m *PerformanceLunMetricInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *SnapshotPolicy) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateScope(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSnapshotPolicyInlineCopies(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateSvm(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.contextValidateUUID(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CoredumpInlineNodeInlineLinks) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.contextValidateSelf(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *SecurityKeyManagerMigrateBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.contextValidateLinks(ctx, formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}" ]
[ "0.7595964", "0.60312414", "0.6006986", "0.5960197", "0.5775893", "0.57498467", "0.57472736", "0.56880873", "0.5684063", "0.5655543", "0.555198", "0.55472845", "0.54989684", "0.5491394", "0.54874235", "0.5484576", "0.5484576", "0.54740316", "0.54457545", "0.5443489", "0.54378897", "0.54165447", "0.5411492", "0.5392576", "0.5389828", "0.5380118", "0.5359856", "0.53572476", "0.53403294", "0.53344107", "0.5334055", "0.5329726", "0.53271574", "0.53186834", "0.53126496", "0.52854633", "0.5277667", "0.52645236", "0.52583945", "0.5256963", "0.5243464", "0.5228434", "0.5225735", "0.5221996", "0.52217", "0.52174824", "0.5214175", "0.5206703", "0.5194909", "0.5168206", "0.5157802", "0.5140925", "0.5137781", "0.5134769", "0.51188266", "0.5109819", "0.5099016", "0.5086891", "0.5081001", "0.50761783", "0.5067064", "0.5066329", "0.5063621", "0.5058042", "0.5057017", "0.50552857", "0.505419", "0.5043057", "0.5038122", "0.5032065", "0.5029418", "0.5022959", "0.50180906", "0.5017884", "0.5017084", "0.5014915", "0.5006907", "0.5001441", "0.4991119", "0.49909997", "0.4990201", "0.49848074", "0.49848074", "0.49836937", "0.4975559", "0.49710605", "0.49614704", "0.49591288", "0.49582374", "0.49549076", "0.49540892", "0.49531236", "0.49528784", "0.4951486", "0.4950412", "0.49480283", "0.49454427", "0.49427906", "0.4938775", "0.49378207" ]
0.8247805
0
Encodes a URL to a shortened URL.
func (this *Codec) encode(longUrl string) string { if _, ok := this.encodeMap[longUrl]; !ok { shortUrl := base + strconv.Itoa(len(this.encodeMap) + 1) this.encodeMap[longUrl] = shortUrl this.decodeMap[shortUrl] = longUrl } return this.encodeMap[longUrl] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func shorten(url string) string {\n // TODO: what is the good way to get the shortened url? (short & unique)\n return \"localhost/\" + fmt.Sprint(hash(url))\n}", "func (ush *UrlShortenerHandler) UrlShorten(w http.ResponseWriter, r *http.Request) {\n\tvar shortenReq model.ShortenReq\n\n\terr := json.NewDecoder(r.Body).Decode(&shortenReq)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\thttpStatus := http.StatusCreated\n\n\tresp, errResp := ush.UrlShortUseCase.StoreShorten(ctx, shortenReq.URL, shortenReq.Slug)\n\tif errResp != nil {\n\t\trespErrResp := model.ResponseError{\n\t\t\tMessage: errResp.Error(),\n\t\t}\n\n\t\thttpStatus = utils.GetStatusCode(errResp)\n\n\t\tmarshallingResponse(w, respErrResp, errResp, httpStatus)\n\n\t\treturn\n\t}\n\n\tmarshallingResponse(w, resp, nil, httpStatus)\n}", "func (this *Codec) encode(longUrl string) string {\n\tshortUrl := \"\"\n\tfor {\n\t\tstr := genShort()\n\t\tif _, ok := this.used[str]; ok {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tthis.used[str] = struct{}{}\n\t\t\tshortUrl = str\n\t\t\tbreak\n\t\t}\n\t}\n\tthis.m[shortUrl] = longUrl\n\treturn shortUrl\n}", "func ShortenHandler(w http.ResponseWriter, r *http.Request) {\n\tlink := Myurl{}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr := json.NewDecoder(r.Body).Decode(&link)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tlog.Println(link)\n\t// Check if the url parameter has been sent along (and is not empty)\n\n\tif link.URL == \"\" {\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Get the short URL out of the config\n\tif !viper.IsSet(\"short_url\") {\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tshort_url := viper.GetString(\"short_url\")\n\n\t// Check if url already exists in the database\n\terr1 := db.QueryRow(\"SELECT `shortid` FROM `tiny_urls` WHERE `url` = ?\", link.URL).Scan(&link.Shortid)\n\tif err1 == nil {\n\t\t// The URL already exists! Return the shortened URL.\n\t\tw.Write([]byte(short_url + \"/\" + link.Shortid))\n\t\treturn\n\t}\n\n\t// generate a shortid and validate it doesn't\n\t// exist until we find a valid one.\n\tvar exists = true\n\tfor exists == true {\n\t\tlink.Shortid = generateshortid()\n\t\terr, exists = shortidExists(link.Shortid)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Insert it into the database\n\tstmt, err := db.Prepare(\"INSERT INTO `tiny_urls` (`shortid`, `url`, `created_at`, `hits`) VALUES (?, ?, NOW(), ?)\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = stmt.Exec(link.Shortid, link.URL, 0)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\te := db.QueryRow(\"SELECT shortid,url,created_at FROM `tiny_urls` WHERE `shortid` = ?\", link.Shortid).Scan(&link)\n\tif e != nil {\n\t\tlog.Println(err)\n\t}\n\tlog.Println(link)\n\tlink.ShortURL = short_url + \"/\" + link.Shortid\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(link)\n\t//w.Write([]byte(short_url + \"/\" + shortid))\n}", "func (s Service) ShortenURL(long string) (short string, err error) {\n\tif short, err = hash.Hash(long); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := s.repo.findByShort(short); err == nil {\n\t\treturn short, nil\n\t}\n\n\ts.repo.Save(&url{\n\t\tLong: long,\n\t\tShort: short,\n\t})\n\n\treturn short, nil\n}", "func (a *App) Shorten(w http.ResponseWriter, r *http.Request) {\n\tvar id int64\n\tvar body Body\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\turl := body.URL\n\n\tif !isValidURL(url) {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid url\")\n\t\treturn\n\t}\n\n\ta.DB.QueryRow(\"SELECT id FROM shortened_urls WHERE long_url = ?\", url).Scan(&id)\n\tif id == 0 {\n\t\tres, err := a.DB.Exec(`INSERT INTO shortened_urls (long_url, created) VALUES(?, now())`, url)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\tid, _ = res.LastInsertId()\n\t}\n\thash := encode(id)\n\tbody.URL = r.Host + \"/\" + hash\n\tsendResponse(w, http.StatusOK, body)\n}", "func BitlyURLShorten(urlStr string) string {\n\tapiKey := os.Getenv(\"BITLY_TOKEN\")\n\tb := bitly.New(apiKey)\n\tshortURL, err := b.Links.Shorten(urlStr)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to sign request\", err)\n\t} else {\n\t\tlog.Debug(\"The bitly URL is\", shortURL)\n\t}\n\treturn shortURL.URL\n}", "func (g * GoogleUrlShortener) ShortenedUrl(longUrl string) (string, error) {\n\tif strings.HasPrefix(longUrl, \"https://goo.gl\") && strings.HasPrefix(longUrl, \"http://goo.gl\") {\n\t\treturn \"\", errors.New(\"cannot shorten already shortened url\")\n\t}\n\t\n\tbody_reader := httputils.Post(g.postUrl(), strings.NewReader(\"{\\\"longUrl\\\": \\\"\" + longUrl + \"/\\\"}\"), \"application/json\")\n\tdefer body_reader.Close()\n\n\tshort_resp := deJsonifyShortenedResponse(body_reader)\n\treturn short_resp.Id, nil\n}", "func (s Shortener) Shorten(uri string) string {\n\t// Is this check needed here?\n\t_, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tid, err := s.db.AddURL(uri)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn s.domain + \"/\" + id\n}", "func EncodeURL(s string) string {\n\treturn slug.MakeLang(s, \"en\")\n}", "func (g *GoogleUrlShortener) ExpandedUrl(id string) (string, error) {\n\tif !strings.HasPrefix(id, \"https://goo.gl\") && !strings.HasPrefix(id, \"http://goo.gl\") {\n\t\treturn \"\", errors.New(\"cannot expand non shortened url\")\n\t}\n\t\n\turl, err := url.Parse(g.postUrl() + \"&shortUrl=\" + id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody_reader := httputils.Get(url.String())\n\tdefer body_reader.Close()\n\n\texp_resp := deJsonifyExpendedResponse(body_reader)\n\treturn exp_resp.LongUrl, nil\n}", "func (as *AptxService) ShortenURL(ctx context.Context, request *aptxv1.ShortenURLRequest) (*aptxv1.ShortenURLResponse, error) {\n\tif request == nil {\n\t\treturn nil, entity.ErrEmptyURL()\n\t}\n\n\turl, cerr := as.creator.Create(ctx, request.GetOriginalUrl())\n\tif cerr != nil {\n\t\treturn nil, cerr\n\t}\n\n\treturn createShortenURLResponseFromEntity(url), nil\n}", "func (s *Service) Shorten(w http.ResponseWriter, r *http.Request) {\n\treq, err := parseShortenRequest(r)\n\tif err != nil {\n\t\trenderError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tshortURL := s.URLBuilder.Build()\n\tif err := s.Store.Set(shortURL.Path, req.URL); err != nil {\n\t\trenderError(w, http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tresponse := ShortenResponse{\n\t\tLongURL: req.URL,\n\t\tShortURL: shortURL.String(),\n\t}\n\trenderJSON(w, response, http.StatusOK)\n}", "func CreateShortenedURL(w http.ResponseWriter, r *http.Request) {\n\t// set headers\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\t// set short and long url from r.Body to the reqURL obj\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\treqURL.ClickCount = 0\n\n\tlg.WriteInfo(fmt.Sprintf(\"Creating Short URL: %v to Long URL: %v\", reqURL.ShortenedURLCode, reqURL.OriginalURL))\n\n\t// check if the same short url already exists\n\tvar searchResult bson.M\n\terr := collection.FindOne(context.TODO(), bson.D{{\"shortened_url_code\", reqURL.ShortenedURLCode}}).Decode(&searchResult)\n\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\t// short url is unique -> insert in db\n\t\t\tresult, err := collection.InsertOne(context.TODO(), reqURL)\n\t\t\tif err != nil {\n\t\t\t\tlg.WriteError(err.Error())\n\t\t\t}\n\n\t\t\tjson.NewEncoder(w).Encode(response{\"okay\", result.InsertedID})\n\t\t}\n\t} else {\n\t\tjson.NewEncoder(w).Encode(response{\"error\", \"Same Short URL already exists\"})\n\t}\n}", "func ShortenURL(urlvar string, b *bitly.Client) string {\n\n\tshortURL, err := b.Links.Shorten(urlvar)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn shortURL.URL\n}", "func (r *RedisCli) Shorten(url string, exp int64) (string, error) {\n\n\tfmt.Println(\"收到的网址\", url)\n\n\t// 将网址转换为hash convert url to sha1 hash\n\th := utils.ToSha1(url)\n\tfmt.Println(\"将网址转换为hash\", h)\n\n\t// 根据hash 获取缓存\n\tkey := fmt.Sprintf(URLHashKey, h)\n\td, err := r.Cli.Get(key).Result()\n\tif err == redis.Nil {\n\t\t// 缓存中不存在\n\t} else if err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\t// 缓存存在 直接返回\n\t\treturn d, nil\n\t}\n\n\t// increase the global counter\n\terr = r.Cli.Incr(URLIDKEY).Err() //next.url.id\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\t// encode global counter to base62\n\tid, err := r.Cli.Get(URLIDKEY).Int64() //next.url.id\n\n\tfmt.Println(\"id\", id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\teid := base62.EncodeInt64(id)\n\tfmt.Println(\"eid\", eid)\n\n\t// store the url against this encoded id\n\terr = r.Cli.Set(fmt.Sprintf(ShortlinkKey, eid), url, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// store the url against the hash of it\n\terr = r.Cli.Set(fmt.Sprintf(URLHashKey, h), eid, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdetails, err := json.Marshal(&URLDetail{\n\t\tURL: url,\n\t\tCreatedAt: time.Now().String(),\n\t\tExpirationInMinutes: time.Duration(exp),\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// store the url detail against this encoded id\n\terr = r.Cli.Set(fmt.Sprintf(ShortlinkDetailKey, eid), details, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn eid, nil\n}", "func Encode(u *url.URL) string {\n\treturn base64.URLEncoding.EncodeToString([]byte(u.RequestURI()))\n}", "func (this *Codec) encode(longUrl string) string {\n\tfor {\n\t\tkey := rand.Int()\n\t\tif this.urls[key] == \"\" {\n\t\t\tthis.urls[key] = longUrl\n\t\t\treturn \"http://tinyurl.com/\" + strconv.Itoa(key)\n\t\t}\n\t}\n\n}", "func ShortenURLEnc(content string, spitType string, exp uint64) (string, error) {\n\n\tclient := &http.Client{}\n\n\tparameters := url.Values{}\n\tparameters.Add(\"content\", content)\n\tparameters.Add(\"spit_type\", spitType)\n\tparameters.Add(\"exp\", strconv.FormatUint(exp, 10))\n\n\treq, err := http.NewRequest(\"POST\", SPITO_API_ADD,\n\t\tbytes.NewBufferString(parameters.Encode()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\treturn _handleResponse(resp)\n}", "func URLShortened(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func shortenHandler(res http.ResponseWriter, req *http.Request) {\n\tvar url myURL\n\t// Extract JSON from body\n\terr := json.NewDecoder(req.Body).Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tlog.Println(\"Received request to shorten URL:\", url.LongURL)\n\n\t// Validate if shortURL already exist\n\tvar result []myURL\n\t// Run query\n\terr = db.C(collection).Find(bson.M{\"longURL\": url.LongURL}).All(&result)\n\tif err != nil {\n\t\tlog.Println(\"Error running query\")\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tif len(result) == 0 {\n\t\t// No results\n\t\tlog.Println(\"ShortURL doesn't exist for\", url.LongURL, \"creating\")\n\t\t// Encode a hashID\n\t\tdata := hashids.NewData()\n\t\thash, _ := hashids.NewWithData(data)\n\t\tid, _ := hash.Encode([]int{int(time.Now().Unix())})\n\t\t// Create the short URL\n\t\turl.ID = id\n\t\turl.ShortURL = endpoint + \"/\" + id\n\t\t// Insert to DB\n\t\terr = db.C(\"shorty\").Insert(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\t// Respond with an error\n\t\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\tres.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tjson.NewEncoder(res).Encode(url)\n\t} else {\n\t\tlog.Println(\"ShortURL\", result[0].ID, \"already exists for\", url.LongURL)\n\t\t// Respond with the URL\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(result[0])\n\t}\n}", "func UpdateShortURL(w http.ResponseWriter, r *http.Request) {\n\t// set headers\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\n\tlg.WriteInfo(fmt.Sprintf(\"Update URL: %v with new Long URL %v\", reqURL.ShortenedURLCode, reqURL.OriginalURL))\n\n\tfilter := bson.D{{\"_id\", reqURL.ID}}\n\treplacement := bson.D{{\"$set\", bson.D{{\"original_url\", reqURL.OriginalURL}}}}\n\n\tvar replaced bson.M\n\terr := collection.FindOneAndUpdate(context.TODO(), filter, replacement).Decode(&replaced)\n\tif err != nil {\n\t\tlg.WriteError(err.Error())\n\t}\n\n\tjson.NewEncoder(w).Encode(response{\"okay\", \"Updated successfully\"})\n}", "func urlEncode(s string) string {\n\treturn strings.Replace(url.QueryEscape(s), \"+\", \"%20\", -1)\n}", "func SaveURL(ctx context.Context, db *DB, url string) (context.Context, string, error) {\n\t//create the short url\n\turlShort := GenURLStringRndm(URLShortLength)\n\n\t//save\n\tstmt := fmt.Sprintf(\"INSERT INTO %s(id,url_short,url) VALUES (UUID_TO_BIN(UUID()),?,?)\", dbTableURLShort)\n\tctx, result, err := db.Exec(ctx, stmt, urlShort, url)\n\tif err != nil {\n\t\treturn ctx, urlShort, errors.Wrap(err, \"insert url short\")\n\t}\n\tcount, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn ctx, urlShort, errors.Wrap(err, \"insert url short rows affected\")\n\t}\n\tif count != 1 {\n\t\treturn ctx, urlShort, fmt.Errorf(\"unable to insert url short: %s\", url)\n\t}\n\treturn ctx, urlShort, nil\n}", "func SinaURLShorten(urlStr string) string {\n\t// http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=http://www.cnblogs.com\n\tapiurl := \"http://api.weibo.com/2/short_url/shorten.json?source=2849184197\"\n\tresp, err := http.Get(fmt.Sprintf(\"%s&url_long=%s\", apiurl, url.QueryEscape(urlStr)))\n\tif err != nil {\n\t\tlog.Warn(err)\n\t\t// handle error\n\t}\n\tdefer resp.Body.Close()\n\tvar body respType\n\tjson.NewDecoder(resp.Body).Decode(&body)\n\t// \tlog.Info(body[\"urls\"].([]interface{}))\n\turls := body[\"urls\"].([]interface{})\n\turlShort := urls[0].(map[string]interface{})[\"url_short\"]\n\t//log.Info(url_short)\n\treturn urlShort.(string)\n}", "func serveShortenedURL(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\toriginal := params[\"url\"]\n\n\tif original == \"\" {\n\t\tjson.NewEncoder(w).Encode(\"\")\n\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(shortenedURL(original))\n}", "func ShortenedUrlHandler(w http.ResponseWriter, r *http.Request) {\n\t// 1. Check if a shortid exists\n\tvars := mux.Vars(r)\n\tshortid, ok := vars[\"shortid\"]\n\tif !ok {\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// 2. Check if the shortid exists in the database\n\tvar url string\n\terr := db.QueryRow(\"SELECT `url` FROM `tiny_urls` WHERE `shortid` = ?\", shortid).Scan(&url)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\t// 3. If the shortid (and thus the URL) exist, update the hit counter\n\tstmt, err := db.Prepare(\"UPDATE `tiny_urls` SET `hits` = `hits` + 1 WHERE `shortid` = ?\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = stmt.Exec(shortid)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// 4. Finally, redirect the user to the URL\n\thttp.Redirect(w, r, url, http.StatusMovedPermanently)\n}", "func GetShortURL(longURL string) (string, error) {\n\n res, err := DB.Exec(\"INSERT INTO urls(longURL) VALUES(?)\", longURL)\n if err != nil {\n\t\treturn \"\", err\n\t}\n\n id, err := res.LastInsertId()\n if err != nil {\n\t\treturn \"\", err\n\t}\n\n shortURL := encode.Encode(id)\n\n return shortURL, nil\n}", "func (h *APIHandler) Shorten(c *routing.Context) error {\n\trecord, err := h.shortener.Shorten(c.FormValue(\"url\"))\n\tif err != nil {\n\t\treturn h.respondWithError(c, err)\n\t}\n\n\tr := makeResponse(c, record)\n\treturn h.respond(c, &r)\n}", "func (driver *DBClient) GenerateShortURL(w http.ResponseWriter, r *http.Request) {\n\tvar id int\n\tvar record Record\n\tpostBody, _ := ioutil.ReadAll(r.Body)\n\tjson.Unmarshal(postBody, &record)\n\terr := driver.db.QueryRow(\"INSERT INTO web_url(url) VALUES($1) RETURNING ide, record.URL\").Scan(&id)\n\n\tresponseMap := map[string]interface{}{\"encoded_string\": base62.Encode(id)}\n\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t} else {\n\t\tresponse, _ := json.Marshal(responseMap)\n\t\tw.Write(response)\n\t}\n}", "func EncodeURL(api string, params RequestQueries) (string, error) {\n\turl, err := url.Parse(api)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tquery := url.Query()\n\n\tfor k, v := range params {\n\t\tquery.Set(k, v)\n\t}\n\n\turl.RawQuery = query.Encode()\n\n\treturn url.String(), nil\n}", "func (c *IndexController) ShortURLHandler(ctx *iris.Context) {\n\turl := ctx.FormValue(\"url\")\n\tresp := new(Response)\n\tinputURL := string(url)\n\n\tif !strings.HasPrefix(inputURL, \"http\") {\n\t\tinputURL = \"http://\" + inputURL\n\t}\n\n\tif inputURL == \"\" {\n\t\tresp.Result = false\n\t\tresp.Message = \"Please input URL first...\"\n\n\t\tctx.JSON(iris.StatusOK, resp)\n\t\treturn\n\t}\n\n\tif strings.Contains(inputURL, \"biturl.top\") {\n\t\tresp.Result = false\n\t\tresp.Message = \"Cannot shorten it again...\"\n\n\t\tctx.JSON(iris.StatusOK, resp)\n\t\treturn\n\t}\n\n\turls := utils.ShortenURL(inputURL)\n\terr := client.Set(urls[0], inputURL, 0).Err()\n\tif err != nil {\n\t\tresp.Result = false\n\t\tresp.Message = \"Backend service is unavailable!\"\n\t}\n\n\tresp.Result = true\n\tresp.Short = \"http://biturl.top/\" + urls[0]\n\n\tctx.JSON(iris.StatusOK, resp)\n}", "func (h *handler) CreateURL(response http.ResponseWriter, request *http.Request) {\n\tvar body createURLRequest\n\n\tdecoder := json.NewDecoder(request.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\thttp.Error(response, \"Invalid body: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := getUniquePath(body.URL)\n\n\tlog.Infof(\"Request to shorten URL '%s'. Path assigned: '%s'\", body.URL, path)\n\n\tif err := h.store.Put(path, body.URL); err != nil {\n\t\tlog.Errorf(\"Generated path '%s' cannot be stored due to: %+v\", path, err)\n\t\thttp.Error(response, \"There was a collision with the generated path, please try again\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresponse.Header().Set(\"Location\", \"/\"+path)\n\tresponse.WriteHeader(http.StatusCreated)\n}", "func encode(value string) string {\n\tencode := &url.URL{Path: value}\n\treturn encode.String()\n}", "func ToURL(s string) string {\n\ts = strings.Trim(s, \" \")\n\ts = strings.ReplaceAll(s, \" \", \"%20\")\n\treturn s\n}", "func URLEncode(s string) string {\n\tencoder := base64.URLEncoding\n\tencoded := make([]byte, encoder.EncodedLen(len([]byte(s))))\n\tencoder.Encode(encoded, []byte(s))\n\treturn string(encoded)\n}", "func expandHandler(res http.ResponseWriter, req *http.Request) {\n\tvar url myURL\n\t// Extract JSON from body\n\terr := json.NewDecoder(req.Body).Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tlog.Println(\"Received request to expand URL\", url.ShortURL)\n\t// Find the corresponding long URL\n\tvar result []myURL\n\t// Run query\n\terr = db.C(collection).Find(bson.M{\"shortURL\": url.ShortURL}).All(&result)\n\tif err != nil {\n\t\tlog.Println(\"Error running query\")\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tif len(result) == 0 {\n\t\t// Not a valid short URL\n\t\tlog.Println(\"No longURL found for:\", url.ShortURL)\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(myURL{LongURL: \"Invalid short URL, shorten first.\"})\n\t} else {\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(result[0])\n\t}\n\n}", "func (f *FastURL) Encode(b []byte) []byte {\n\tif len(f.protocol) > 0 {\n\t\tb = append(b, f.protocol...)\n\t\tb = append(b, ':')\n\t}\n\n\tvar appendslash bool\n\tif len(f.user) > 0 || len(f.pass) > 0 {\n\t\tb = append(b, \"//\"...)\n\t\tappendslash = true\n\t\tb = append(b, f.user...)\n\t\tb = append(b, ':')\n\t\tb = append(b, f.pass...)\n\t\tb = append(b, '@')\n\t}\n\n\tif len(f.hostname) > 0 {\n\t\tif !appendslash {\n\t\t\tb = append(b, \"//\"...)\n\t\t\tappendslash = true\n\t\t}\n\t\tb = append(b, f.hostname...)\n\t}\n\n\tif len(f.port) > 0 {\n\t\tif !appendslash {\n\t\t\tb = append(b, \"//\"...)\n\t\t\tappendslash = true\n\t\t}\n\t\tb = append(b, ':')\n\t\tb = append(b, f.port...)\n\t}\n\n\tif len(f.pathname) > 0 {\n\t\tb = append(b, f.pathname...)\n\t}\n\n\tif f.query.Len() > 0 {\n\t\tb = append(b, '?')\n\t\tb = f.query.Encode(b)\n\t}\n\n\tif len(f.hash) > 0 {\n\t\tb = append(b, f.hash...)\n\t}\n\n\treturn b\n}", "func expandUrl(url string) (result string, err error) {\n\tprefixFound := false\n\tfor _, prefixRE := range linkPrefixes {\n\t\tif found := prefixRE.FindString(url); found != \"\" {\n\t\t\tprefixFound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !prefixFound {\n\t\treturn \"\", nil\n\t}\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = \"http://\" + url\n\t}\n\tlog.Println(\"Resolving url\", url)\n\treturn util.ResolveRedirects(url)\n}", "func PutURL(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"PUT URL\")\n\turlKey := mux.Vars(r)[urlKeyPattern]\n\tdao := NewDao(shortURLDbPath)\n\texists, status := dao.DoesExist(urlKey)\n\n\tif status == Error {\n\t\tlog.Println(\"Internal Server Error\")\n\t\tsendJSON(w, http.StatusInternalServerError, genericResponse{\"Internal Server Error\"})\n\t\treturn\n\t}\n\n\tif !exists {\n\t\tsendJSON(w, http.StatusNotFound, genericResponse{\"No URL found for key \" + urlKey})\n\t\treturn\n\t}\n\n\twriteURLInfo(w, r, urlKey, http.StatusOK)\n}", "func urlEncode(str string) (string, error) {\n\tu, err := url.Parse(str)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.String(), nil\n}", "func (o *Aliyun) makeURLEncode(m, str string) string {\n\tStringToSign := m + \"&\" + o.percentEncode(\"/\") + \"&\" + o.percentEncode(str)\n\treturn StringToSign\n}", "func cutShort(h *Handler, c echo.Context) error {\n\tvar u string\n\tvar e error\n\tcustom := c.FormValue(\"custom\")\n\t// TODO: move this in CreateByLongURL\n\tif u, e = algo.NormalizeURL(c.FormValue(\"url\")); e != nil {\n\t\terrorMessage := fmt.Sprintf(\"Error in URL for %s: %s\", c.FormValue(\"url\"), e)\n\t\tlog.Error(errorMessage)\n\t\treturn c.String(http.StatusUnprocessableEntity, errorMessage)\n\t}\n\tresult, e := h.Store.CreateByLongURL(u, custom)\n\tif e != nil {\n\t\terrorMessage := fmt.Sprintf(\"Error in shortening for %s: %s\", c.FormValue(\"url\"), e)\n\t\tlog.Error(errorMessage)\n\t\treturn c.String(http.StatusUnprocessableEntity, errorMessage)\n\t}\n\treturn c.String(http.StatusCreated, result.ShortURL())\n}", "func buildURL(searchTerm string, shorturl string) string {\r\n\t//filler\r\n\tsearchTerm = strings.Replace(searchTerm, \" \", \"-\", -1)\r\n\treturn fmt.Sprintf(\"%s%s\", mURL[shorturl], searchTerm)\r\n}", "func GetShortURLHandler(response http.ResponseWriter, request *http.Request) {\n\ttype URLRequestObject struct {\n\t\tURL string `json:\"url\"`\n\t}\n\ttype URLCollection struct {\n\t\tActualURL string\n\t\tShortURL string\n\t}\n\ttype SuccessResponse struct {\n\t\tCode int\n\t\tMessage string\n\t\tResponse URLCollection\n\t}\n\tvar urlRequest URLRequestObject\n\tvar httpError = ErrorResponse{\n\t\tCode: http.StatusInternalServerError, Message: \"Something went wrong at our end\",\n\t}\n\n\tdecoder := json.NewDecoder(request.Body)\n\terr := decoder.Decode(&urlRequest)\n\n\tif err != nil {\n\t\thttpError.Message = \"URL can't be empty\"\n\t\treturnErrorResponse(response, request, httpError)\n\t} else if !isURL(urlRequest.URL) {\n\t\thttpError.Message = \"An invalid URL found, provide a valid URL\"\n\t\treturnErrorResponse(response, request, httpError)\n\t} else {\n\t\tuniqueID, idError := shortid.Generate()\n\t\tif idError != nil {\n\t\t\treturnErrorResponse(response, request, httpError)\n\t\t} else {\n\t\t\terr := Client.Set(uniqueID, urlRequest.URL, 0).Err()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturnErrorResponse(response, request, httpError)\n\t\t\t}\n\t\t\tvar successResponse = SuccessResponse{\n\t\t\t\tCode: http.StatusOK,\n\t\t\t\tMessage: \"Short URL generated\",\n\t\t\t\tResponse: URLCollection{\n\t\t\t\t\tActualURL: urlRequest.URL,\n\t\t\t\t\tShortURL: request.Host + \"/\" + uniqueID,\n\t\t\t\t},\n\t\t\t}\n\t\t\tjsonResponse, err := json.Marshal(successResponse)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tresponse.WriteHeader(successResponse.Code)\n\t\t\tresponse.Write(jsonResponse)\n\t\t}\n\t}\n}", "func UrlEncode(str string) string {\r\n\ts := url.QueryEscape(str)\r\n\treturn s\r\n}", "func (mg *MongoConn) CreateShortURL(c *fiber.Ctx) error {\n\tfmt.Println(\"entering db (redir)\")\n\treqBody := URLRequest{}\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tif err := c.BodyParser(&reqBody); err != nil {\n\t\tcancel()\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\n\tinsDoc := CreateURL{\n\t\tURLMain: reqBody.URLMain,\n\t\tShortID: reqBody.Event,\n\t}\n\t_, err := mg.Db.Collection(os.Getenv(\"COLLECTION_NAME\")).InsertOne(ctx, insDoc)\n\tif err != nil {\n\t\tcancel()\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\tbaseString := \"http://localhost:3000/\"\n\tcancel()\n\tfmt.Println(\"short url created\")\n\treturn c.Status(201).JSON(fiber.Map{\n\t\t\"short_url\": baseString + insDoc.ShortID,\n\t})\n}", "func uriEncode(value string) string {\n\tinitial := url.QueryEscape(value)\n\treturn strings.Replace(initial, \"+\", \"%20\", -1)\n}", "func StoreUrl(c *gin.Context) {\n\torigin := c.PostForm(\"long_url\")\n\tfmt.Println(origin)\n\tstr := storage.RedisPool.StoreLongUrl2Redis(origin)\n\tif str == \"\" {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"surl\": \"\",\n\t\t\t\"msg\": \"failed\",\n\t\t})\n\t} else {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"surl\": str,\n\t\t\t\"msg\": \"success\",\n\t\t})\n\t}\n}", "func CreateUrl() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar url Url\n\n\t\terr := url.Validate(r)\n\t\tif err != nil {\n\t\t\tutil.SendError(w, http.StatusBadRequest, nil)\n\t\t\treturn\n\t\t}\n\n\t\terr = url.Create()\n\n\t\tswitch err {\n\t\tcase UrlAlreadyExist:\n\t\t\turl.SetPrefix()\n\t\t\tutil.SendSuccess(w, url)\n\t\tcase store.DatabaseQueryError:\n\t\t\tutil.SendError(w, http.StatusInternalServerError, err)\n\t\tcase nil:\n\t\t\t// URL successfully shortened and stored.\n\t\t\turl.SetPrefix()\n\t\t\tw.WriteHeader(201)\n\t\t\tutil.SendSuccess(w, url)\n\t\tdefault:\n\t\t\tutil.SendError(w, http.StatusInternalServerError, nil)\n\t\t}\n\t}\n}", "func (app *App) expand(w http.ResponseWriter, r *http.Request) {\n\tshortened := r.URL.Query().Get(\"url\")\n\tif shortened == \"\" {\n\t\tresp, _ := json.Marshal(responseMessage{Error: \"No url provided. Use 'url' param.\"})\n\t\thttp.Error(w, string(resp), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\texpanded, err := app.Expander.ExpandUrl(shortened)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: (%s) %s [url: %s]\", r.RemoteAddr, err.Error(), shortened)\n\t\tswitch err {\n\t\tcase urlexpander.ErrDisallowedByRobotsTxt, urlexpander.ErrInvalidUrl, urlexpander.ErrLongUrl:\n\t\t\tresp, _ := json.Marshal(responseMessage{Error: err.Error()})\n\t\t\thttp.Error(w, string(resp), http.StatusBadRequest)\n\t\tdefault:\n\t\t\tresp, _ := json.Marshal(responseMessage{Error: \"Uknown error\"})\n\t\t\thttp.Error(w, string(resp), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tresp := responseMessage{Original: shortened, Expanded: expanded}\n\tjson.NewEncoder(w).Encode(resp)\n}", "func GenerateShortenedURL() string {\n\tlength := 6\n\turl := make([]rune, length)\n\trand.Seed(time.Now().UnixNano())\n\tfor i := range url {\n\t\turl[i] = letters[rand.Intn(len(letters))]\n\t}\n\tfmt.Println(string(url))\n\treturn string(url)\n}", "func ExpandEndpoint(w http.ResponseWriter, req *http.Request) {\n\tvar n1q1Params = []interface{}\n\tquery := gocb.NewN1qlQuery(\"SELECT `\" + bucketName + \"`.* FROM `\" + bucketName + \"` WHERE shortUrl = $1\")\n\tparams := req.URL.Query()\n\tn1q1Params = append(n1q1Params, params.Get(\"ShortURL\"))\n\trows, _ := bucket.ExecuteN1qlQuery(query, n1q1Params)\n\tvar row = ShortURL\n\trows.One(&row)\n\tjson.NewEncoder(w).Encode(row)\n}", "func URLify(buffer []byte, originalLen int) {\n\tspaces := 0\n\tfor i := 0; i < originalLen; i++ {\n\t\tif buffer[i] == ' ' {\n\t\t\tspaces++\n\t\t}\n\t}\n\tif originalLen+spaces*2 > len(buffer) {\n\t\treturn\n\t}\n\ti := originalLen - 1\n\tj := originalLen + spaces*2 - 1\n\tfor i >= 0 && j >= 2 {\n\t\tif buffer[i] == ' ' {\n\t\t\tbuffer[j-2] = '%'\n\t\t\tbuffer[j-1] = '2'\n\t\t\tbuffer[j] = '0'\n\t\t\tj -= 3\n\t\t} else {\n\t\t\tbuffer[j] = buffer[i]\n\t\t\tj--\n\t\t}\n\t\ti--\n\t}\n}", "func EscapeURL(s string) string {\n\treturn got.URLQueryEscaper(s)\n}", "func URLify(s []rune, baseLength int) {\n\tnumSpaces := 0\n\tfor i := 0; i < baseLength; i++ {\n\t\tif s[i] == ' ' {\n\t\t\tnumSpaces++\n\t\t}\n\t}\n\n\tindex := baseLength + numSpaces*2\n\tfor i := baseLength - 1; i >= 0; i-- {\n\t\tif s[i] == ' ' {\n\t\t\ts[index-1] = '0'\n\t\t\ts[index-2] = '2'\n\t\t\ts[index-3] = '%'\n\t\t\tindex = index - 3\n\t\t} else {\n\t\t\ts[index-1] = s[i]\n\t\t\tindex--\n\t\t}\n\t}\n}", "func (o BlankOptions) encodeURL(u *url.URL) error {\n\tnoencode := \"\"\n\tval := url.Values{}\n\tfor k, v := range o {\n\t\t//This is the ',noencode' option\n\t\t// the result of url.QueryEncode changing ' ' to '+'\n\t\t// when we need percent encoded spaces we pass a url.PathEncoded value here\n\t\tif strings.Contains(k, \",noencode\") {\n\t\t\tkey := strings.Replace(k, \",noencode\", \"\", -1)\n\t\t\t//unfortunately pathEncode misses the '=' signs so we do that manually\n\t\t\tv = strings.Replace(v, \"=\", \"%3D\",-1)\n\t\t\tnoencode += key + \"=\" + v + \"&\"\n\t\t} else {\n\t\t\tval.Add(k, v)\n\t\t}\n\t}\n\tu.RawQuery = val.Encode()\n\tu.RawQuery += \"&\" + noencode\n\treturn nil\n}", "func (a *App) EncodeUri(uri string) string {\n\teUri, err := url.Parse(uri)\n\tif err != nil {\n\t\tfmt.Printf(\"Error parsing uri: '%s'. Error: %s\\n\", uri, err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tencoded := \"\"\n\n\tscheme := eUri.Scheme\n\tif scheme != \"\" {\n\t\tencoded = scheme + \"://\"\n\t}\n\n\thost := eUri.Host\n\tif host != \"\" {\n\t\tencoded += host\n\t}\n\n\tpaths := strings.Split(eUri.EscapedPath(), \"/\")\n\tfor i, p := range paths {\n\t\tval, _ := url.QueryUnescape(p)\n\t\tpaths[i] = url.PathEscape(val)\n\t}\n\tencoded += strings.Join(paths, \"/\")\n\n\tif eUri.RawQuery != \"\" {\n\t\tencoded += \"?\" + eUri.Query().Encode()\n\t}\n\n\treturn encoded\n}", "func URLify(input string, truelen int) string {\n\tspaces := 0\n\n\tfor idx_in := 0; idx_in < truelen; idx_in++ {\n\n\t\tif input[idx_in] == byte(' ') {\n\t\t\tspaces++\n\t\t}\n\t}\n\t// +2 for each space for the extra \"20\"s.\n\toutput := make([]byte, truelen+(2*spaces))\n\tidx_out := truelen + spaces*2 - 1\n\n\tfor idx_in := truelen - 1; idx_in >= 0; idx_in-- {\n\t\tif input[idx_in] == byte(' ') {\n\t\t\toutput[idx_out] = byte('0')\n\t\t\toutput[idx_out-1] = byte('2')\n\t\t\toutput[idx_out-2] = byte('%')\n\t\t\tidx_out -= 3\n\t\t} else {\n\t\t\toutput[idx_out] = input[idx_in]\n\t\t\tidx_out--\n\t\t}\n\t}\n\treturn string(output)\n}", "func MakeUrl(address string) string {\n\n params := url.Values{}\n params.Add(\"near\", address)\n\n uri := fmt.Sprintf(\"%s?%s\", URL, params.Encode())\n\n return uri\n}", "func RegisterShortLink(w http.ResponseWriter, req *http.Request) {\n\tremoteURL := req.FormValue(\"url\")\n\te, err := models.RegisterShortLink(req.Host, remoteURL)\n\n\tif err, ok := err.(*shared.HTTPError); ok {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(w, http.StatusText(err.Status), err.Status)\n\t\treturn\n\t}\n\n\tconfig.TPL.ExecuteTemplate(w, \"success.gohtml\", e)\n}", "func (b *Builder) URL(s string) *Builder {\n\treturn b.appendMessage(s, func(offset, limit int) tg.MessageEntityClass {\n\t\treturn &tg.MessageEntityUrl{Offset: offset, Length: limit}\n\t})\n}", "func URLShortenedContains(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func URL(route string, opts ...string) (s string) {\n\tsize := len(opts)\n\tif size >= 1 {\n\t\tif strings.Contains(route, \"$1\") {\n\t\t\troute = strings.Replace(route, \"$1\", opts[0], 1)\n\t\t}\n\t\tif size >= 2 && strings.Contains(route, \"$2\") {\n\t\t\troute = strings.Replace(route, \"$2\", opts[1], 1)\n\t\t}\n\t}\n\ts = fmt.Sprintf(\"%s%s\", Host, route)\n\treturn\n}", "func (h *Handlers) NewURL(w http.ResponseWriter, r *http.Request, params map[string]string) {\n\tu := params[\"\"]\n\n\tif !h.ValidateURL(u) {\n\t\th.RespondError(w, ErrInvalidURL, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\treqDB := h.masterDB.Copy()\n\tdefer reqDB.Close()\n\n\tcollection := reqDB.DB(\"\").C(urlCollection)\n\n\tslug := h.slugifier.GenerateUniqueSlug(8, collection, \"slug\")\n\n\tnewUrl := URL{\n\t\tSlug: slug,\n\t\tOriginalURL: u,\n\t\tShortURL: h.Host + \"/\" + slug,\n\t}\n\n\tif err := collection.Insert(&newUrl); err != nil {\n\t\th.RespondError(w, ErrUnableToShortenUrl, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\th.RespondJSON(w, newUrl, 201)\n}", "func (d *DeepLink) Encode() (string, error) {\n\tsrc, err := rlp.EncodeToBytes(d)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.RawURLEncoding.EncodeToString(src), nil\n}", "func URLEncode(s string) string {\n\tif pos := strings.IndexRune(s, '?'); pos > -1 { // escape query data\n\t\treturn s[0:pos+1] + url.QueryEscape(s[pos+1:])\n\t}\n\n\treturn s\n}", "func (s SinkAPI) Sink(ctx context.Context, req *gw.SinkRequest) (*gw.SinkResponse, error) {\n\tshortened, err := s.shortener.Shorten(ctx, req.Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &gw.SinkResponse{Url: shortened}, nil\n}", "func formatUrl(source string) string {\n\tif match, _ := regexp.MatchString(\"https?:\\\\/\\\\/\", source); match {\n\t\treturn source\n\t}\n\n\treturn \"https://\" + source\n}", "func onGetShortLink(w http.ResponseWriter, r *http.Request) {\n\tvalues := r.URL.Query()\n\tlongURL, ok := values[\"longURL\"]\n\tif ok {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif len(longURL) >= 1 {\n\t\t\tfmt.Println(longURL[0])\n\t\t\t_, err := url.ParseRequestURI(longURL[0]) // trying to parse string to proper URL\n\t\t\tif err != nil {\n\t\t\t\tresponseToCLient(w, \"Please enter the correct and complete url, example - http://google.com\")\n\t\t\t} else {\n\t\t\t\tshortUrl, ok := getShortURL(longURL[0])\n\t\t\t\tif ok {\n\t\t\t\t\tresponseToCLient(w, \"Your Short URL is : http://mydomain.com/\"+shortUrl) // responding with short link by attaching demo domain\n\t\t\t\t} else {\n\t\t\t\t\tresponseToCLient(w, \"Please check the request parameters\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tresponseToCLient(w, \"Please check the request parameters\")\n\t\t}\n\t} else {\n\t\tresponseToCLient(w, \"No longURL found, Please check the request parameters\")\n\t}\n}", "func Urlify(entry string, n int) string {\n\tinput := []rune(entry)\n\tspaceCount := 0\n\tfor i := 0; i < n; i++ {\n\t\tif input[i] == ' ' {\n\t\t\tspaceCount++\n\t\t}\n\t}\n\n\toutput := make([]rune, n+(spaceCount*2))\n\toutputi := 0\n\tfor i := 0; i < n; i++ {\n\t\tif input[i] == ' ' {\n\t\t\toutput[outputi] = '%'\n\t\t\toutput[outputi+1] = '2'\n\t\t\toutput[outputi+2] = '0'\n\t\t\toutputi += 3\n\t\t} else {\n\t\t\toutput[outputi] = input[i]\n\t\t\toutputi++\n\t\t}\n\t}\n\treturn string(output)\n}", "func URLEncoded(str string) string {\n\tu, err := url.Parse(str)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding the url: %s , error: %v\", str, err)\n\t\treturn str\n\t}\n\n\tu.RawQuery = u.Query().Encode()\n\treturn u.String()\n}", "func NewURL(original, shortened string) (URL, error) {\n\tif original == \"\" {\n\t\treturn URL{}, NewOriginalURLInvalidError(original)\n\t}\n\tif shortened == \"\" {\n\t\treturn URL{}, ErrShortenedValueIsEmpty\n\t}\n\t_, err := url.ParseRequestURI(original)\n\tif err != nil {\n\t\treturn URL{}, NewOriginalURLInvalidError(original)\n\t}\n\treturn URL{\n\t\tOriginal: original,\n\t\tShortened: shortened,\n\t\tCreatedAt: time.Now().UTC(),\n\t}, nil\n}", "func (h *UrlHandler) Insert(c *gin.Context) {\n\tvar urlSh models.URLShorten\n\n\terr := c.ShouldBindWith(&urlSh, binding.FormPost)\n\tif err != nil {\n\t\te := NewAPIError(400, CodeBadRequest, err.Error(), errors.New(\"Bad Request\"))\n\t\tc.JSON(e.Status, e)\n\t\treturn\n\t}\n\n\tif !utils.IsRequestURL(urlSh.LongURL) {\n\t\te := NewAPIError(422, CodeInvalidParam, \"\", fmt.Errorf(\"Invalid longUrl: %s\", urlSh.LongURL))\n\t\tc.JSON(e.Status, e)\n\t\treturn\n\t}\n\n\tres, err := h.service.Insert(c, &urlSh)\n\tif err != nil {\n\t\tif IsNotFound(err) {\n\t\t\tc.JSON(404, ErrAPINotFound)\n\t\t\treturn\n\t\t}\n\n\t\tlogrus.Error(err)\n\t\tc.JSON(500, ErrAPIInternal)\n\t\treturn\n\t}\n\n\tjsonData(c, http.StatusCreated, res)\n}", "func URLEncoded(str string) string {\n\tu, err := url.Parse(str)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error encoding the url: %s, error: %v\", str, err)\n\t\treturn str\n\t}\n\treturn u.String()\n}", "func urlify(s string) string {\n\tvar r strings.Builder\n\n\tfor i := 0; i < len(s); i++ {\n\t\tif string(s[i]) == \" \" {\n\t\t\tr.WriteString(\"%20\")\n\t\t} else {\n\t\t\tr.WriteString(string(s[i]))\n\t\t}\n\t}\n\treturn r.String()\n}", "func createurl(w http.ResponseWriter, r *http.Request) {\n\tvar url Myurl\n\tjson.NewDecoder(r.Body).Decode(&url)\n\thd := hashids.NewData()\n\th, _ := hashids.NewWithData(hd)\n\tnow := time.Now()\n\turl.ID, _ = h.Encode([]int{int(now.Unix())})\n\turl.ShortURL = \"http://localhost:8080/\" + url.ID\n\tdb.Create(&url)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(url)\n}", "func URLShortenedEQ(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func mutateURL(url string) string {\n\treturn strings.Replace(url, \"/j/\", \"/wc/join/\", 1)\n}", "func (c *Client) URL(path string, a ...interface{}) string {\n\tu, _ := urlx.Parse(c.addr)\n\n\tu.Path = fmt.Sprintf(path, a...)\n\n\treturn u.String()\n}", "func URLify(s string) string {\n\tspaces := 0\n\tfor _, c := range s {\n\t\tif c == ' ' {\n\t\t\tspaces++\n\t\t}\n\t}\n\n\tindex := len(s) + spaces*2\n\trunes := make([]rune, index)\n\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tif s[i] == ' ' {\n\t\t\trunes[index-1] = '0'\n\t\t\trunes[index-2] = '2'\n\t\t\trunes[index-3] = '%'\n\t\t\tindex = index - 3\n\t\t} else {\n\t\t\trunes[index-1] = rune(s[i])\n\t\t\tindex--\n\t\t}\n\t}\n\n\treturn string(runes)\n}", "func URLShortenedHasSuffix(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func URLEncoded(str string) string {\n\tu, err := url.Parse(str)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding the url: %s, error: %v\", str, err)\n\t\treturn str\n\t}\n\treturn u.String()\n}", "func URLize(t string) string {\n\treturn StringConcat(slug.MakeLang(t, \"en\"), \".html\")\n}", "func (s Store) AddURL(url string) (string, error) {\n\turl = strings.TrimSpace(url)\n\tif url == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Empty url is not allowed\")\n\t}\n\tid := s.getID(url)\n\tif id != \"\" {\n\t\treturn id, nil\n\t}\n\n\tid = newID()\n\tif err := s.put(id, url); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn id, nil\n}", "func (fn *formulaFuncs) ENCODEURL(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"ENCODEURL requires 1 argument\")\n\t}\n\ttoken := argsList.Front().Value.(formulaArg).Value()\n\treturn newStringFormulaArg(strings.ReplaceAll(url.QueryEscape(token), \"+\", \"%20\"))\n}", "func (r *urlRepository) Create(u string) (string, error) {\n\tshortURL, err := r.getShortURL(u)\n\tif err == nil {\n\t\treturn shortURL, nil\n\t} else if err != ErrNoRecords {\n\t\treturn \"\", err\n\t}\n\tshortURL = RandomStringGenerator(LengthURL)\n\tisCollision, err := r.isShortURLExist(shortURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif isCollision {\n\t\tfor i := 0; isCollision && i < 20; i++ {\n\t\t\tshortURL = RandomStringGenerator(LengthURL)\n\t\t\tisCollision, err = r.isShortURLExist(shortURL)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\tif isCollision {\n\t\t\treturn \"\", fmt.Errorf(\"could not create short url, because of collisions, try again later\")\n\t\t}\n\t}\n\tvar originalURL string\n\tif err := r.s.db.QueryRow(\"INSERT INTO url VALUES ($1, $2) RETURNING original_url\", shortURL, u).Scan(&originalURL); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn shortURL, nil\n}", "func URLShortenedGTE(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func (this *Codec) decode(shortUrl string) string {\n return this.decodeMap[shortUrl]\n}", "func URLify(str string) string {\n\trunes := []rune(str)\n\tfor i, j := 0, 0; j < len(str); i++ {\n\t\tif j > len(str) {\n\t\t\tbreak\n\t\t}\n\t\tif str[i] != ' ' {\n\t\t\trunes[j] = rune(str[i])\n\t\t\tj++\n\t\t} else {\n\t\t\trunes[j] = '%'\n\t\t\trunes[j+1] = '2'\n\t\t\trunes[j+2] = '0'\n\t\t\tj = j + 3\n\t\t}\n\t}\n\treturn string(runes)\n}", "func URLEncode(str string) string {\n\treturn url.QueryEscape(str)\n}", "func URLShortenedEqualFold(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EqualFold(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func urlify(rawInput string) string {\n\tencoded := strings.TrimSpace(rawInput)\n\treturn strings.ReplaceAll(encoded, \" \", \"%20\")\n}", "func EmbedURL(url string) string {\n\tif e := miscURL(url); e != \"\" {\n\t\treturn e\n\t}\n\treturn oEmbedURL(url)\n}", "func Encode(src []byte) string {\n\treturn base64.RawURLEncoding.EncodeToString(src)\n}", "func NewShortUrl(ctx *pulumi.Context,\n\tname string, args *ShortUrlArgs, opts ...pulumi.ResourceOption) (*ShortUrl, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.EffectiveDays == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EffectiveDays'\")\n\t}\n\tif args.ShortUrlName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ShortUrlName'\")\n\t}\n\tif args.SourceUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SourceUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource ShortUrl\n\terr := ctx.RegisterResource(\"alicloud:sms/shortUrl:ShortUrl\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (p *PathSpec) URLize(uri string) string {\n\treturn p.URLEscape(p.MakePathSanitized(uri))\n}", "func NewUrlShortenerHandler(r *mux.Router, usu domain.UrlShortenerUseCase) {\n\thandler := &UrlShortenerHandler{\n\t\tUrlShortUseCase: usu,\n\t}\n\tr.HandleFunc(\"/shorten\", handler.UrlShorten).Methods(\"POST\")\n\tr.HandleFunc(\"/{shortcode:[a-zA-Z0-9]+}\", handler.GetShortCode).Methods(\"GET\")\n\tr.HandleFunc(\"/{shortcode:[a-zA-Z0-9]+}/stats\", handler.GetShortCodeStats).Methods(\"GET\")\n}", "func URLize(path string) string {\n\n\tpath = strings.Replace(strings.TrimSpace(path), \" \", \"-\", -1)\n\tpath = strings.ToLower(path)\n\tpath = UnicodeSanitize(path)\n\treturn path\n}", "func URLToClient(session *network.Session) {\n\tvar cash_url = g_ServerConfig.CashWeb_URL\n\tvar cash_odc_url = g_ServerConfig.CashWeb_Odc_URL\n\tvar cash_charge_url = g_ServerConfig.CashWeb_Charge_URL\n\tvar guildweb_url = g_ServerConfig.GuildWeb_URL\n\tvar sns_url = g_ServerConfig.Sns_URL\n\n\tvar dataLen = len(cash_url) + 4\n\tdataLen += len(cash_odc_url) + 4\n\tdataLen += len(cash_charge_url) + 4\n\tdataLen += len(guildweb_url) + 4\n\tdataLen += len(sns_url) + 4\n\n\tvar packet = network.NewWriter(URLTOCLIENT)\n\tpacket.WriteInt16(dataLen + 2)\n\tpacket.WriteInt16(dataLen)\n\tpacket.WriteInt32(len(cash_url))\n\tpacket.WriteString(cash_url)\n\tpacket.WriteInt32(len(cash_odc_url))\n\tpacket.WriteString(cash_odc_url)\n\tpacket.WriteInt32(len(cash_charge_url))\n\tpacket.WriteString(cash_charge_url)\n\tpacket.WriteInt32(len(guildweb_url))\n\tpacket.WriteString(guildweb_url)\n\tpacket.WriteInt32(len(sns_url))\n\tpacket.WriteString(sns_url)\n\n\tsession.Send(packet)\n}" ]
[ "0.6746286", "0.67336696", "0.664273", "0.66162133", "0.6591163", "0.65204084", "0.642802", "0.63661915", "0.6342407", "0.63409114", "0.6322413", "0.63224053", "0.6271976", "0.623999", "0.6236754", "0.6203312", "0.6180786", "0.61444587", "0.6082755", "0.60555315", "0.60261446", "0.6022431", "0.59923697", "0.59598225", "0.5957246", "0.5916062", "0.5902349", "0.5882706", "0.58600175", "0.5859732", "0.5783452", "0.5717601", "0.5697901", "0.5670652", "0.5616829", "0.56016093", "0.5576517", "0.5574006", "0.55526465", "0.5515118", "0.5491955", "0.5461809", "0.5461478", "0.5440476", "0.543201", "0.54085267", "0.5405396", "0.53988975", "0.53684115", "0.5361943", "0.53514814", "0.53214073", "0.52330625", "0.5229392", "0.5226627", "0.52128655", "0.5207478", "0.5202887", "0.519771", "0.51791406", "0.5170737", "0.51543766", "0.5144531", "0.5128682", "0.51034427", "0.50996774", "0.5090882", "0.5075515", "0.50687104", "0.506056", "0.50527704", "0.5052673", "0.50446033", "0.5032653", "0.5026507", "0.5005365", "0.49991557", "0.4998127", "0.49927178", "0.49839988", "0.49731237", "0.49658474", "0.49539658", "0.49473405", "0.4942659", "0.4934401", "0.49317467", "0.49310252", "0.49250954", "0.49209976", "0.49169043", "0.49112824", "0.48988926", "0.4892136", "0.48874336", "0.48860803", "0.48851442", "0.48840123", "0.48727205", "0.48718914" ]
0.6672017
2
Decodes a shortened URL to its original URL.
func (this *Codec) decode(shortUrl string) string { return this.decodeMap[shortUrl] }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Codec) decode(shortUrl string) string {\n\tindex := strings.LastIndex(shortUrl, \"/\")\n\tkey, _ := strconv.Atoi(shortUrl[index+1:])\n\treturn this.urls[key]\n\n}", "func (this *Codec) decode(shortUrl string) string {\n\treturn this.m[shortUrl]\n}", "func (s Service) ShortenURL(long string) (short string, err error) {\n\tif short, err = hash.Hash(long); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := s.repo.findByShort(short); err == nil {\n\t\treturn short, nil\n\t}\n\n\ts.repo.Save(&url{\n\t\tLong: long,\n\t\tShort: short,\n\t})\n\n\treturn short, nil\n}", "func (r *RedisCli) Unshorten(eid string) (string, error) {\n\turl, err := r.Cli.Get(fmt.Sprintf(ShortlinkKey, eid)).Result()\n\tif err == redis.Nil {\n\t\treturn \"\", errors.New(\"unknown short URL\")\n\t} else if err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn url, nil\n\t}\n}", "func (g * GoogleUrlShortener) ShortenedUrl(longUrl string) (string, error) {\n\tif strings.HasPrefix(longUrl, \"https://goo.gl\") && strings.HasPrefix(longUrl, \"http://goo.gl\") {\n\t\treturn \"\", errors.New(\"cannot shorten already shortened url\")\n\t}\n\t\n\tbody_reader := httputils.Post(g.postUrl(), strings.NewReader(\"{\\\"longUrl\\\": \\\"\" + longUrl + \"/\\\"}\"), \"application/json\")\n\tdefer body_reader.Close()\n\n\tshort_resp := deJsonifyShortenedResponse(body_reader)\n\treturn short_resp.Id, nil\n}", "func (g *GoogleUrlShortener) ExpandedUrl(id string) (string, error) {\n\tif !strings.HasPrefix(id, \"https://goo.gl\") && !strings.HasPrefix(id, \"http://goo.gl\") {\n\t\treturn \"\", errors.New(\"cannot expand non shortened url\")\n\t}\n\t\n\turl, err := url.Parse(g.postUrl() + \"&shortUrl=\" + id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody_reader := httputils.Get(url.String())\n\tdefer body_reader.Close()\n\n\texp_resp := deJsonifyExpendedResponse(body_reader)\n\treturn exp_resp.LongUrl, nil\n}", "func BitlyURLShorten(urlStr string) string {\n\tapiKey := os.Getenv(\"BITLY_TOKEN\")\n\tb := bitly.New(apiKey)\n\tshortURL, err := b.Links.Shorten(urlStr)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to sign request\", err)\n\t} else {\n\t\tlog.Debug(\"The bitly URL is\", shortURL)\n\t}\n\treturn shortURL.URL\n}", "func (as *AptxService) ShortenURL(ctx context.Context, request *aptxv1.ShortenURLRequest) (*aptxv1.ShortenURLResponse, error) {\n\tif request == nil {\n\t\treturn nil, entity.ErrEmptyURL()\n\t}\n\n\turl, cerr := as.creator.Create(ctx, request.GetOriginalUrl())\n\tif cerr != nil {\n\t\treturn nil, cerr\n\t}\n\n\treturn createShortenURLResponseFromEntity(url), nil\n}", "func SinaURLShorten(urlStr string) string {\n\t// http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=http://www.cnblogs.com\n\tapiurl := \"http://api.weibo.com/2/short_url/shorten.json?source=2849184197\"\n\tresp, err := http.Get(fmt.Sprintf(\"%s&url_long=%s\", apiurl, url.QueryEscape(urlStr)))\n\tif err != nil {\n\t\tlog.Warn(err)\n\t\t// handle error\n\t}\n\tdefer resp.Body.Close()\n\tvar body respType\n\tjson.NewDecoder(resp.Body).Decode(&body)\n\t// \tlog.Info(body[\"urls\"].([]interface{}))\n\turls := body[\"urls\"].([]interface{})\n\turlShort := urls[0].(map[string]interface{})[\"url_short\"]\n\t//log.Info(url_short)\n\treturn urlShort.(string)\n}", "func shorten(url string) string {\n // TODO: what is the good way to get the shortened url? (short & unique)\n return \"localhost/\" + fmt.Sprint(hash(url))\n}", "func ShortenURL(urlvar string, b *bitly.Client) string {\n\n\tshortURL, err := b.Links.Shorten(urlvar)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn shortURL.URL\n}", "func (a *App) Shorten(w http.ResponseWriter, r *http.Request) {\n\tvar id int64\n\tvar body Body\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&body); err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid request payload\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\turl := body.URL\n\n\tif !isValidURL(url) {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid url\")\n\t\treturn\n\t}\n\n\ta.DB.QueryRow(\"SELECT id FROM shortened_urls WHERE long_url = ?\", url).Scan(&id)\n\tif id == 0 {\n\t\tres, err := a.DB.Exec(`INSERT INTO shortened_urls (long_url, created) VALUES(?, now())`, url)\n\t\tif err != nil {\n\t\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\tid, _ = res.LastInsertId()\n\t}\n\thash := encode(id)\n\tbody.URL = r.Host + \"/\" + hash\n\tsendResponse(w, http.StatusOK, body)\n}", "func URLShortened(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func (ush *UrlShortenerHandler) UrlShorten(w http.ResponseWriter, r *http.Request) {\n\tvar shortenReq model.ShortenReq\n\n\terr := json.NewDecoder(r.Body).Decode(&shortenReq)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\thttpStatus := http.StatusCreated\n\n\tresp, errResp := ush.UrlShortUseCase.StoreShorten(ctx, shortenReq.URL, shortenReq.Slug)\n\tif errResp != nil {\n\t\trespErrResp := model.ResponseError{\n\t\t\tMessage: errResp.Error(),\n\t\t}\n\n\t\thttpStatus = utils.GetStatusCode(errResp)\n\n\t\tmarshallingResponse(w, respErrResp, errResp, httpStatus)\n\n\t\treturn\n\t}\n\n\tmarshallingResponse(w, resp, nil, httpStatus)\n}", "func UpdateShortURL(w http.ResponseWriter, r *http.Request) {\n\t// set headers\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\n\tlg.WriteInfo(fmt.Sprintf(\"Update URL: %v with new Long URL %v\", reqURL.ShortenedURLCode, reqURL.OriginalURL))\n\n\tfilter := bson.D{{\"_id\", reqURL.ID}}\n\treplacement := bson.D{{\"$set\", bson.D{{\"original_url\", reqURL.OriginalURL}}}}\n\n\tvar replaced bson.M\n\terr := collection.FindOneAndUpdate(context.TODO(), filter, replacement).Decode(&replaced)\n\tif err != nil {\n\t\tlg.WriteError(err.Error())\n\t}\n\n\tjson.NewEncoder(w).Encode(response{\"okay\", \"Updated successfully\"})\n}", "func GetShortURL(longURL string) (string, error) {\n\n res, err := DB.Exec(\"INSERT INTO urls(longURL) VALUES(?)\", longURL)\n if err != nil {\n\t\treturn \"\", err\n\t}\n\n id, err := res.LastInsertId()\n if err != nil {\n\t\treturn \"\", err\n\t}\n\n shortURL := encode.Encode(id)\n\n return shortURL, nil\n}", "func GetURLByShortenedURL(shortenedURL string) (*URL, error) {\n\turl := &URL{}\n\terr := GetDB().Where(\"short_url=?\", shortenedURL).First(url).Error\n\tif err != nil {\n\t\treturn url, err\n\t}\n\treturn url, nil\n}", "func (h *APIHandler) Shorten(c *routing.Context) error {\n\trecord, err := h.shortener.Shorten(c.FormValue(\"url\"))\n\tif err != nil {\n\t\treturn h.respondWithError(c, err)\n\t}\n\n\tr := makeResponse(c, record)\n\treturn h.respond(c, &r)\n}", "func GetLongURL(shortURL string) (string, error) {\n var longURL string\n\n id := encode.Decode(shortURL)\n\n err := DB.QueryRow(\"SELECT longURL FROM urls WHERE id=?\", id).Scan(&longURL)\n if err != nil {\n\t\treturn \"\", err\n\t}\n\n return longURL, nil\n}", "func ShortenHandler(w http.ResponseWriter, r *http.Request) {\n\tlink := Myurl{}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr := json.NewDecoder(r.Body).Decode(&link)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tlog.Println(link)\n\t// Check if the url parameter has been sent along (and is not empty)\n\n\tif link.URL == \"\" {\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Get the short URL out of the config\n\tif !viper.IsSet(\"short_url\") {\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tshort_url := viper.GetString(\"short_url\")\n\n\t// Check if url already exists in the database\n\terr1 := db.QueryRow(\"SELECT `shortid` FROM `tiny_urls` WHERE `url` = ?\", link.URL).Scan(&link.Shortid)\n\tif err1 == nil {\n\t\t// The URL already exists! Return the shortened URL.\n\t\tw.Write([]byte(short_url + \"/\" + link.Shortid))\n\t\treturn\n\t}\n\n\t// generate a shortid and validate it doesn't\n\t// exist until we find a valid one.\n\tvar exists = true\n\tfor exists == true {\n\t\tlink.Shortid = generateshortid()\n\t\terr, exists = shortidExists(link.Shortid)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Insert it into the database\n\tstmt, err := db.Prepare(\"INSERT INTO `tiny_urls` (`shortid`, `url`, `created_at`, `hits`) VALUES (?, ?, NOW(), ?)\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = stmt.Exec(link.Shortid, link.URL, 0)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\te := db.QueryRow(\"SELECT shortid,url,created_at FROM `tiny_urls` WHERE `shortid` = ?\", link.Shortid).Scan(&link)\n\tif e != nil {\n\t\tlog.Println(err)\n\t}\n\tlog.Println(link)\n\tlink.ShortURL = short_url + \"/\" + link.Shortid\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(link)\n\t//w.Write([]byte(short_url + \"/\" + shortid))\n}", "func (r *urlRepository) getShortURL(OriginalURL string) (string, error) {\n\tvar shortURL string\n\tif err := r.s.db.QueryRow(\"SELECT short_url FROM url WHERE original_url = $1\",\n\t\tOriginalURL).Scan(&shortURL); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", ErrNoRecords\n\t\t}\n\t\treturn \"\", err\n\t}\n\treturn shortURL, nil\n}", "func (u URL) OriginalURL() *string {\n\treturn &u.url.LongLink\n}", "func (s *Service) Shorten(w http.ResponseWriter, r *http.Request) {\n\treq, err := parseShortenRequest(r)\n\tif err != nil {\n\t\trenderError(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tshortURL := s.URLBuilder.Build()\n\tif err := s.Store.Set(shortURL.Path, req.URL); err != nil {\n\t\trenderError(w, http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\n\tresponse := ShortenResponse{\n\t\tLongURL: req.URL,\n\t\tShortURL: shortURL.String(),\n\t}\n\trenderJSON(w, response, http.StatusOK)\n}", "func (r *RedisCli) Shorten(url string, exp int64) (string, error) {\n\n\tfmt.Println(\"收到的网址\", url)\n\n\t// 将网址转换为hash convert url to sha1 hash\n\th := utils.ToSha1(url)\n\tfmt.Println(\"将网址转换为hash\", h)\n\n\t// 根据hash 获取缓存\n\tkey := fmt.Sprintf(URLHashKey, h)\n\td, err := r.Cli.Get(key).Result()\n\tif err == redis.Nil {\n\t\t// 缓存中不存在\n\t} else if err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\t// 缓存存在 直接返回\n\t\treturn d, nil\n\t}\n\n\t// increase the global counter\n\terr = r.Cli.Incr(URLIDKEY).Err() //next.url.id\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\t// encode global counter to base62\n\tid, err := r.Cli.Get(URLIDKEY).Int64() //next.url.id\n\n\tfmt.Println(\"id\", id)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\teid := base62.EncodeInt64(id)\n\tfmt.Println(\"eid\", eid)\n\n\t// store the url against this encoded id\n\terr = r.Cli.Set(fmt.Sprintf(ShortlinkKey, eid), url, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// store the url against the hash of it\n\terr = r.Cli.Set(fmt.Sprintf(URLHashKey, h), eid, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdetails, err := json.Marshal(&URLDetail{\n\t\tURL: url,\n\t\tCreatedAt: time.Now().String(),\n\t\tExpirationInMinutes: time.Duration(exp),\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// store the url detail against this encoded id\n\terr = r.Cli.Set(fmt.Sprintf(ShortlinkDetailKey, eid), details, time.Minute*time.Duration(exp)).Err()\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn eid, nil\n}", "func (s Shortener) Shorten(uri string) string {\n\t// Is this check needed here?\n\t_, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tid, err := s.db.AddURL(uri)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn s.domain + \"/\" + id\n}", "func serveShortenedURL(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\toriginal := params[\"url\"]\n\n\tif original == \"\" {\n\t\tjson.NewEncoder(w).Encode(\"\")\n\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(shortenedURL(original))\n}", "func CreateShortenedURL(w http.ResponseWriter, r *http.Request) {\n\t// set headers\n\t// w.Header().Set(\"Content-Type\", \"application/json\")\n\t// w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t// w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tif !auth.IsValidToken(r.Header.Get(\"x-auth-token\")) {\n\t\tresp := response{Status: \"error\", Message: \"Invalid Token\"}\n\t\tjson.NewEncoder(w).Encode(resp)\n\t\treturn\n\t}\n\n\t// set short and long url from r.Body to the reqURL obj\n\tvar reqURL models.URLShorten\n\t_ = json.NewDecoder(r.Body).Decode(&reqURL)\n\treqURL.ClickCount = 0\n\n\tlg.WriteInfo(fmt.Sprintf(\"Creating Short URL: %v to Long URL: %v\", reqURL.ShortenedURLCode, reqURL.OriginalURL))\n\n\t// check if the same short url already exists\n\tvar searchResult bson.M\n\terr := collection.FindOne(context.TODO(), bson.D{{\"shortened_url_code\", reqURL.ShortenedURLCode}}).Decode(&searchResult)\n\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\t// short url is unique -> insert in db\n\t\t\tresult, err := collection.InsertOne(context.TODO(), reqURL)\n\t\t\tif err != nil {\n\t\t\t\tlg.WriteError(err.Error())\n\t\t\t}\n\n\t\t\tjson.NewEncoder(w).Encode(response{\"okay\", result.InsertedID})\n\t\t}\n\t} else {\n\t\tjson.NewEncoder(w).Encode(response{\"error\", \"Same Short URL already exists\"})\n\t}\n}", "func shortenHandler(res http.ResponseWriter, req *http.Request) {\n\tvar url myURL\n\t// Extract JSON from body\n\terr := json.NewDecoder(req.Body).Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tlog.Println(\"Received request to shorten URL:\", url.LongURL)\n\n\t// Validate if shortURL already exist\n\tvar result []myURL\n\t// Run query\n\terr = db.C(collection).Find(bson.M{\"longURL\": url.LongURL}).All(&result)\n\tif err != nil {\n\t\tlog.Println(\"Error running query\")\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tif len(result) == 0 {\n\t\t// No results\n\t\tlog.Println(\"ShortURL doesn't exist for\", url.LongURL, \"creating\")\n\t\t// Encode a hashID\n\t\tdata := hashids.NewData()\n\t\thash, _ := hashids.NewWithData(data)\n\t\tid, _ := hash.Encode([]int{int(time.Now().Unix())})\n\t\t// Create the short URL\n\t\turl.ID = id\n\t\turl.ShortURL = endpoint + \"/\" + id\n\t\t// Insert to DB\n\t\terr = db.C(\"shorty\").Insert(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\t// Respond with an error\n\t\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\tres.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tjson.NewEncoder(res).Encode(url)\n\t} else {\n\t\tlog.Println(\"ShortURL\", result[0].ID, \"already exists for\", url.LongURL)\n\t\t// Respond with the URL\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(result[0])\n\t}\n}", "func (c *IndexController) ShortURLHandler(ctx *iris.Context) {\n\turl := ctx.FormValue(\"url\")\n\tresp := new(Response)\n\tinputURL := string(url)\n\n\tif !strings.HasPrefix(inputURL, \"http\") {\n\t\tinputURL = \"http://\" + inputURL\n\t}\n\n\tif inputURL == \"\" {\n\t\tresp.Result = false\n\t\tresp.Message = \"Please input URL first...\"\n\n\t\tctx.JSON(iris.StatusOK, resp)\n\t\treturn\n\t}\n\n\tif strings.Contains(inputURL, \"biturl.top\") {\n\t\tresp.Result = false\n\t\tresp.Message = \"Cannot shorten it again...\"\n\n\t\tctx.JSON(iris.StatusOK, resp)\n\t\treturn\n\t}\n\n\turls := utils.ShortenURL(inputURL)\n\terr := client.Set(urls[0], inputURL, 0).Err()\n\tif err != nil {\n\t\tresp.Result = false\n\t\tresp.Message = \"Backend service is unavailable!\"\n\t}\n\n\tresp.Result = true\n\tresp.Short = \"http://biturl.top/\" + urls[0]\n\n\tctx.JSON(iris.StatusOK, resp)\n}", "func expandHandler(res http.ResponseWriter, req *http.Request) {\n\tvar url myURL\n\t// Extract JSON from body\n\terr := json.NewDecoder(req.Body).Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusBadRequest)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tlog.Println(\"Received request to expand URL\", url.ShortURL)\n\t// Find the corresponding long URL\n\tvar result []myURL\n\t// Run query\n\terr = db.C(collection).Find(bson.M{\"shortURL\": url.ShortURL}).All(&result)\n\tif err != nil {\n\t\tlog.Println(\"Error running query\")\n\t\tlog.Fatal(err)\n\t\t// Respond with an error\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\tres.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tif len(result) == 0 {\n\t\t// Not a valid short URL\n\t\tlog.Println(\"No longURL found for:\", url.ShortURL)\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(myURL{LongURL: \"Invalid short URL, shorten first.\"})\n\t} else {\n\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\tres.WriteHeader(http.StatusOK)\n\t\tjson.NewEncoder(res).Encode(result[0])\n\t}\n\n}", "func getLongURL(h *Handler, c echo.Context) error {\n\tshortURL := c.Param(\"shortURL\")\n\tvar u *url.URL\n\tvar e error\n\tif u, e = h.Store.FindByShortURL(shortURL); e != nil {\n\t\tlog.Error(fmt.Sprintf(\"Error in getSlug for %s: %s\", shortURL, e))\n\t\treturn c.String(http.StatusNotFound, \"Invalid Link\")\n\t}\n\treturn c.Redirect(http.StatusMovedPermanently, u.Original)\n}", "func URLDecode(s string) string {\n\tencoder := base64.URLEncoding\n\tdecoded := make([]byte, encoder.EncodedLen(len([]byte(s))))\n\t_, err := encoder.Decode(decoded, []byte(s))\n\tif err != nil {\n\t\treturn fmt.Sprintln(err)\n\t}\n\treturn string(decoded)\n}", "func (c *PgClient) GetURL(ctx context.Context, shorten string) (string, *errors.Error) {\n\tsqlGetURL := `SELECT original FROM urls WHERE shorten = $1 AND expired_at >= current_timestamp;`\n\trow := c.QueryRow(ctx, sqlGetURL, shorten)\n\tvar original string\n\tif err := row.Scan(&original); err != nil {\n\t\tif err == pgx.ErrNoRows {\n\t\t\treturn \"\", errors.New(errors.URLNotFoundError, err.Error())\n\t\t}\n\t\treturn \"\", errors.New(errors.ScanError, err.Error())\n\t}\n\treturn original, nil\n}", "func NewURL(original, shortened string) (URL, error) {\n\tif original == \"\" {\n\t\treturn URL{}, NewOriginalURLInvalidError(original)\n\t}\n\tif shortened == \"\" {\n\t\treturn URL{}, ErrShortenedValueIsEmpty\n\t}\n\t_, err := url.ParseRequestURI(original)\n\tif err != nil {\n\t\treturn URL{}, NewOriginalURLInvalidError(original)\n\t}\n\treturn URL{\n\t\tOriginal: original,\n\t\tShortened: shortened,\n\t\tCreatedAt: time.Now().UTC(),\n\t}, nil\n}", "func DeleteShortURL(res http.ResponseWriter, req *http.Request) {\n\tif err := url.DeleteURLFromRequest(req); err != nil {\n\t\tresponse.JSON(res, http.StatusNotFound, response.Body{\"message\": err.Error()})\n\t\treturn\n\t}\n\n\tresponse.JSON(res, http.StatusOK, response.Body{\"deleted\": true})\n}", "func (this *Codec) encode(longUrl string) string {\n if _, ok := this.encodeMap[longUrl]; !ok {\n shortUrl := base + strconv.Itoa(len(this.encodeMap) + 1)\n this.encodeMap[longUrl] = shortUrl\n this.decodeMap[shortUrl] = longUrl\n }\n return this.encodeMap[longUrl]\n}", "func GetShortURLHandler(response http.ResponseWriter, request *http.Request) {\n\ttype URLRequestObject struct {\n\t\tURL string `json:\"url\"`\n\t}\n\ttype URLCollection struct {\n\t\tActualURL string\n\t\tShortURL string\n\t}\n\ttype SuccessResponse struct {\n\t\tCode int\n\t\tMessage string\n\t\tResponse URLCollection\n\t}\n\tvar urlRequest URLRequestObject\n\tvar httpError = ErrorResponse{\n\t\tCode: http.StatusInternalServerError, Message: \"Something went wrong at our end\",\n\t}\n\n\tdecoder := json.NewDecoder(request.Body)\n\terr := decoder.Decode(&urlRequest)\n\n\tif err != nil {\n\t\thttpError.Message = \"URL can't be empty\"\n\t\treturnErrorResponse(response, request, httpError)\n\t} else if !isURL(urlRequest.URL) {\n\t\thttpError.Message = \"An invalid URL found, provide a valid URL\"\n\t\treturnErrorResponse(response, request, httpError)\n\t} else {\n\t\tuniqueID, idError := shortid.Generate()\n\t\tif idError != nil {\n\t\t\treturnErrorResponse(response, request, httpError)\n\t\t} else {\n\t\t\terr := Client.Set(uniqueID, urlRequest.URL, 0).Err()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturnErrorResponse(response, request, httpError)\n\t\t\t}\n\t\t\tvar successResponse = SuccessResponse{\n\t\t\t\tCode: http.StatusOK,\n\t\t\t\tMessage: \"Short URL generated\",\n\t\t\t\tResponse: URLCollection{\n\t\t\t\t\tActualURL: urlRequest.URL,\n\t\t\t\t\tShortURL: request.Host + \"/\" + uniqueID,\n\t\t\t\t},\n\t\t\t}\n\t\t\tjsonResponse, err := json.Marshal(successResponse)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tresponse.WriteHeader(successResponse.Code)\n\t\t\tresponse.Write(jsonResponse)\n\t\t}\n\t}\n}", "func onGetShortLink(w http.ResponseWriter, r *http.Request) {\n\tvalues := r.URL.Query()\n\tlongURL, ok := values[\"longURL\"]\n\tif ok {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif len(longURL) >= 1 {\n\t\t\tfmt.Println(longURL[0])\n\t\t\t_, err := url.ParseRequestURI(longURL[0]) // trying to parse string to proper URL\n\t\t\tif err != nil {\n\t\t\t\tresponseToCLient(w, \"Please enter the correct and complete url, example - http://google.com\")\n\t\t\t} else {\n\t\t\t\tshortUrl, ok := getShortURL(longURL[0])\n\t\t\t\tif ok {\n\t\t\t\t\tresponseToCLient(w, \"Your Short URL is : http://mydomain.com/\"+shortUrl) // responding with short link by attaching demo domain\n\t\t\t\t} else {\n\t\t\t\t\tresponseToCLient(w, \"Please check the request parameters\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tresponseToCLient(w, \"Please check the request parameters\")\n\t\t}\n\t} else {\n\t\tresponseToCLient(w, \"No longURL found, Please check the request parameters\")\n\t}\n}", "func (p FnacParser) GetShortURL() string {\n\treturn p.shortURL\n}", "func (s shortURLImpl) Parse(w http.ResponseWriter, req *http.Request) {\n\t_ = req.ParseForm()\n\tshort := req.FormValue(\"s\")\n\tif len(short) == 0 {\n\t\t_ = s.responseJSON(w, errors.New(\"empty shorted URL (as s)\"))\n\t\treturn\n\t}\n\n\tid := base62.Decode(short)\n\tout := orm.ShortURLDO{\n\t\tID: id,\n\t}\n\n\tif err := s.orm.Query(&out); err != nil {\n\t\t_ = s.responseJSON(w, err)\n\t\treturn\n\t}\n\n\t_ = s.responseJSON(w, out.Source)\n}", "func ShortenURLEnc(content string, spitType string, exp uint64) (string, error) {\n\n\tclient := &http.Client{}\n\n\tparameters := url.Values{}\n\tparameters.Add(\"content\", content)\n\tparameters.Add(\"spit_type\", spitType)\n\tparameters.Add(\"exp\", strconv.FormatUint(exp, 10))\n\n\treq, err := http.NewRequest(\"POST\", SPITO_API_ADD,\n\t\tbytes.NewBufferString(parameters.Encode()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\treturn _handleResponse(resp)\n}", "func (r *urlRepository) Get(shortUrl string) (string, error) {\n\tvar url string\n\tif err := r.s.db.QueryRow(\n\t\t\"SELECT original_url FROM url WHERE short_url = $1\",\n\t\tshortUrl).Scan(&url); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", ErrNoRecords\n\t\t}\n\t\treturn \"\", err\n\t}\n\treturn url, nil\n}", "func (p LeclercParser) GetShortURL() string {\n\treturn p.shortURL\n}", "func (handler ShortURLForwardingHandler) handleGettingShortURL(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the hash from the URL\n\turlPath := strings.Split(r.URL.Path[1:len(r.URL.Path)], \"/\")\n\tkey := urlPath[0]\n\tlog.Printf(\"Fetching URL for key: %v\", key)\n\n\t// Look up the URL and redirect to the stored URL\n\tnewURL := handler.Storage.GetURLByShortHash(key)\n\thttp.Redirect(w, r, newURL, http.StatusTemporaryRedirect)\n}", "func cutShort(h *Handler, c echo.Context) error {\n\tvar u string\n\tvar e error\n\tcustom := c.FormValue(\"custom\")\n\t// TODO: move this in CreateByLongURL\n\tif u, e = algo.NormalizeURL(c.FormValue(\"url\")); e != nil {\n\t\terrorMessage := fmt.Sprintf(\"Error in URL for %s: %s\", c.FormValue(\"url\"), e)\n\t\tlog.Error(errorMessage)\n\t\treturn c.String(http.StatusUnprocessableEntity, errorMessage)\n\t}\n\tresult, e := h.Store.CreateByLongURL(u, custom)\n\tif e != nil {\n\t\terrorMessage := fmt.Sprintf(\"Error in shortening for %s: %s\", c.FormValue(\"url\"), e)\n\t\tlog.Error(errorMessage)\n\t\treturn c.String(http.StatusUnprocessableEntity, errorMessage)\n\t}\n\treturn c.String(http.StatusCreated, result.ShortURL())\n}", "func ShortenedUrlHandler(w http.ResponseWriter, r *http.Request) {\n\t// 1. Check if a shortid exists\n\tvars := mux.Vars(r)\n\tshortid, ok := vars[\"shortid\"]\n\tif !ok {\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// 2. Check if the shortid exists in the database\n\tvar url string\n\terr := db.QueryRow(\"SELECT `url` FROM `tiny_urls` WHERE `shortid` = ?\", shortid).Scan(&url)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\t// 3. If the shortid (and thus the URL) exist, update the hit counter\n\tstmt, err := db.Prepare(\"UPDATE `tiny_urls` SET `hits` = `hits` + 1 WHERE `shortid` = ?\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = stmt.Exec(shortid)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// 4. Finally, redirect the user to the URL\n\thttp.Redirect(w, r, url, http.StatusMovedPermanently)\n}", "func URLDecode(s string) string {\n\tif pos := strings.IndexRune(s, '?'); pos > -1 { // un-escape query data\n\t\tqy, err := url.QueryUnescape(s[pos+1:])\n\t\tif err == nil {\n\t\t\treturn s[0:pos+1] + qy\n\t\t}\n\t}\n\n\treturn s\n}", "func (driver *DBClient) GenerateShortURL(w http.ResponseWriter, r *http.Request) {\n\tvar id int\n\tvar record Record\n\tpostBody, _ := ioutil.ReadAll(r.Body)\n\tjson.Unmarshal(postBody, &record)\n\terr := driver.db.QueryRow(\"INSERT INTO web_url(url) VALUES($1) RETURNING ide, record.URL\").Scan(&id)\n\n\tresponseMap := map[string]interface{}{\"encoded_string\": base62.Encode(id)}\n\n\tif err != nil {\n\t\tw.Write([]byte(err.Error()))\n\t} else {\n\t\tresponse, _ := json.Marshal(responseMap)\n\t\tw.Write(response)\n\t}\n}", "func GetShortUrl(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *ShortUrlState, opts ...pulumi.ResourceOption) (*ShortUrl, error) {\n\tvar resource ShortUrl\n\terr := ctx.ReadResource(\"alicloud:sms/shortUrl:ShortUrl\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func GetUrl(c *gin.Context) {\n\tsurl := c.Param(\"surl\")\n\tfmt.Println(surl)\n\tkey, err := strconv.ParseUint(surl, 36, 0)\n\tif err != nil {\n\t\tfmt.Println(\"\\033[;31murl not validated\\033[;0m\")\n\t}\n\tstr := storage.RedisPool.GetShortUrlFromRedis(key)\n\tfmt.Println(str)\n\tif str == \"\" {\n\t\tc.JSON(500, gin.H{\n\t\t\t\"surl\": \"\",\n\t\t\t\"msg\": \"failed\",\n\t\t})\n\t}\n\tc.Redirect(302, str)\n}", "func (c *Cache) GetLongUrl(shortUrl string) (*string, error) {\n\tcachedUrl, err := c.cache.GetLongUrlCached(shortUrl)\n\tif err != nil {\n\t\tserializedUrl, err := c.serialized.GetLongUrl(shortUrl)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif serializedUrl != nil {\n\t\t\t_ = c.cache.PutLongUrlCached(serializedUrl.ID, serializedUrl.LongUrl)\n\t\t\treturn &serializedUrl.LongUrl, nil\n\t\t} else {\n\t\t\treturn nil, nil\n\t\t}\n\t}\n\treturn cachedUrl, nil\n}", "func DownloadableURL(original string) (string, error) {\n\tif runtime.GOOS == \"windows\" {\n\t\t// If the distance to the first \":\" is just one character, assume\n\t\t// we're dealing with a drive letter and thus a file path.\n\t\tidx := strings.Index(original, \":\")\n\t\tif idx == 1 {\n\t\t\toriginal = \"file:///\" + original\n\t\t}\n\t}\n\n\turl, err := url.Parse(original)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif url.Scheme == \"\" {\n\t\turl.Scheme = \"file\"\n\t}\n\n\tif url.Scheme == \"file\" {\n\t\t// Windows file handling is all sorts of tricky...\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\t// If the path is using Windows-style slashes, URL parses\n\t\t\t// it into the host field.\n\t\t\tif url.Path == \"\" && strings.Contains(url.Host, `\\`) {\n\t\t\t\turl.Path = url.Host\n\t\t\t\turl.Host = \"\"\n\t\t\t}\n\n\t\t\t// For Windows absolute file paths, remove leading / prior to processing\n\t\t\t// since net/url turns \"C:/\" into \"/C:/\"\n\t\t\tif len(url.Path) > 0 && url.Path[0] == '/' {\n\t\t\t\turl.Path = url.Path[1:len(url.Path)]\n\t\t\t}\n\t\t}\n\n\t\t// Only do the filepath transformations if the file appears\n\t\t// to actually exist.\n\t\tif _, err := os.Stat(url.Path); err == nil {\n\t\t\turl.Path, err = filepath.Abs(url.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\turl.Path, err = filepath.EvalSymlinks(url.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\turl.Path = filepath.Clean(url.Path)\n\t\t}\n\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\t// Also replace all backslashes with forwardslashes since Windows\n\t\t\t// users are likely to do this but the URL should actually only\n\t\t\t// contain forward slashes.\n\t\t\turl.Path = strings.Replace(url.Path, `\\`, `/`, -1)\n\t\t}\n\t}\n\n\t// Make sure it is lowercased\n\turl.Scheme = strings.ToLower(url.Scheme)\n\n\t// This is to work around issue #5927. This can safely be removed once\n\t// we distribute with a version of Go that fixes that bug.\n\t//\n\t// See: https://code.google.com/p/go/issues/detail?id=5927\n\tif url.Path != \"\" && url.Path[0] != '/' {\n\t\turl.Path = \"/\" + url.Path\n\t}\n\n\t// Verify that the scheme is something we support in our common downloader.\n\tsupported := []string{\"file\", \"http\", \"https\"}\n\tfound := false\n\tfor _, s := range supported {\n\t\tif url.Scheme == s {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn \"\", fmt.Errorf(\"Unsupported URL scheme: %s\", url.Scheme)\n\t}\n\n\treturn url.String(), nil\n}", "func getURL(rawurl string) (u *url.URL, err error) {\n\tif !strings.HasPrefix(rawurl, \"https://\") {\n\t\trawurl = \"https://\" + rawurl\n\t}\n\n\tu, err = url.Parse(rawurl)\n\treturn\n}", "func NewUrlShortenerHandler(r *mux.Router, usu domain.UrlShortenerUseCase) {\n\thandler := &UrlShortenerHandler{\n\t\tUrlShortUseCase: usu,\n\t}\n\tr.HandleFunc(\"/shorten\", handler.UrlShorten).Methods(\"POST\")\n\tr.HandleFunc(\"/{shortcode:[a-zA-Z0-9]+}\", handler.GetShortCode).Methods(\"GET\")\n\tr.HandleFunc(\"/{shortcode:[a-zA-Z0-9]+}/stats\", handler.GetShortCodeStats).Methods(\"GET\")\n}", "func (this *Codec) encode(longUrl string) string {\n\tshortUrl := \"\"\n\tfor {\n\t\tstr := genShort()\n\t\tif _, ok := this.used[str]; ok {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tthis.used[str] = struct{}{}\n\t\t\tshortUrl = str\n\t\t\tbreak\n\t\t}\n\t}\n\tthis.m[shortUrl] = longUrl\n\treturn shortUrl\n}", "func expandUrl(url string) (result string, err error) {\n\tprefixFound := false\n\tfor _, prefixRE := range linkPrefixes {\n\t\tif found := prefixRE.FindString(url); found != \"\" {\n\t\t\tprefixFound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !prefixFound {\n\t\treturn \"\", nil\n\t}\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = \"http://\" + url\n\t}\n\tlog.Println(\"Resolving url\", url)\n\treturn util.ResolveRedirects(url)\n}", "func CanonicalizeURL(u *url.URL) (*url.URL, error) {\n\tret := url.URL{}\n\tret.Scheme = \"https\"\n\tret.Host = u.Host\n\tret.Path = u.Path\n\n\tif strings.HasSuffix(ret.Host, \".googlesource.com\") {\n\t\tif strings.HasPrefix(ret.Path, \"/a/\") {\n\t\t\t// Force authorization prefix.\n\t\t\tret.Path = strings.TrimPrefix(ret.Path, \"/a\")\n\t\t}\n\t} else if ret.Host == \"source.developers.google.com\" {\n\t\t// Do nothing.\n\t} else {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"unsupported host: %s\", u.Host)\n\t}\n\t// Git endpoint suffixes.\n\tif strings.HasSuffix(ret.Path, \"/info/refs\") {\n\t\tret.Path = strings.TrimSuffix(ret.Path, \"/info/refs\")\n\t} else if strings.HasSuffix(ret.Path, \"/git-upload-pack\") {\n\t\tret.Path = strings.TrimSuffix(ret.Path, \"/git-upload-pack\")\n\t} else if strings.HasSuffix(ret.Path, \"/git-receive-pack\") {\n\t\tret.Path = strings.TrimSuffix(ret.Path, \"/git-receive-pack\")\n\t}\n\tret.Path = strings.TrimSuffix(ret.Path, \".git\")\n\treturn &ret, nil\n}", "func (s *MapURLStorage) GetURLByShortHash(shortHash string) string {\n\treturn s.Storage[shortHash]\n}", "func ParseURL(operand string) (url *url.URL, err error) { return url.Parse(operand) }", "func (d *BoltDB) GetFullURL(short string) string {\n\n\tvar fullURL []byte\n\terr := d.Conn.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucket))\n\t\tfullURL = b.Get([]byte(short))\n\t\treturn nil\n\t})\n\tif err != nil {\n\n\t}\n\n\treturn string(fullURL)\n}", "func getURL(u *UseCase, ctx context.Context, shortCode string) (*database.URL, error) {\n\n\tgetPopularURL, err := u.RedisRepo.Get(ctx, shortCode)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrorGeneric)\n\t}\n\n\tif getPopularURL != nil {\n\t\tresponse := new(database.URL)\n\t\terr = json.Unmarshal([]byte(*getPopularURL), response)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(ErrorGeneric)\n\t\t}\n\t\treturn response, nil\n\t}\n\n\tresponse, err := u.DatabaseRepo.GetURL(shortCode)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrorGeneric)\n\t}\n\n\tif response == nil {\n\t\treturn nil, errors.New(ErrorRecordNotFound)\n\t}\n\n\treturn response, nil\n\n}", "func UrlFromPost(r *http.Request, usr *User) *Url {\n\t// TODO: Validate Source url format (http[s]://), trim values\n\tsrc := strings.TrimSpace(r.PostFormValue(\"source\"))\n\n\treturn &Url{\n\t\tPath: RandomPath(),\n\t\tSource: formatUrl(src),\n\t\tDateCreated: time.Now(),\n\t\tOwner: usr,\n\t\tCreatorIP: ipAddr(r),\n\t}\n}", "func URLDecode(str string) (string, error) {\n\treturn url.QueryUnescape(str)\n}", "func NewShortUrl(ctx *pulumi.Context,\n\tname string, args *ShortUrlArgs, opts ...pulumi.ResourceOption) (*ShortUrl, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.EffectiveDays == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EffectiveDays'\")\n\t}\n\tif args.ShortUrlName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ShortUrlName'\")\n\t}\n\tif args.SourceUrl == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SourceUrl'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource ShortUrl\n\terr := ctx.RegisterResource(\"alicloud:sms/shortUrl:ShortUrl\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func URLShortenedEqualFold(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EqualFold(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func URLShortenedHasSuffix(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func stripPort(rawurl string) string {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\treturn rawurl\n\t}\n\tu.Host = u.Hostname()\n\treturn u.String()\n}", "func (r *Response) URL() string {\n\treturn r.host + \"/convert/p3r68-cdx67/\" + r.Filename\n}", "func convertURL(url string, pat string) (s string, err error) {\n\tif url[:8] != \"https://\" {\n\t\treturn \"\", errors.New(ErrURLNotHTTPS)\n\t}\n\n\tif url[len(url)-4:] != \".git\" {\n\t\turl = fmt.Sprintf(\"%v.git\", url)\n\t\tfmt.Println(errors.New(ErrURLEndNotDotGit))\n\t}\n\n\treturn fmt.Sprintf(\"https://%v@%v\", pat, url[8:]), err\n}", "func Decode(URL string, target interface{}) (err error) {\n\n\tctx := context.Background()\n\tfs := afs.New()\n\tdata, err := fs.DownloadWithURL(ctx, URL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taMap := map[string]interface{}{}\n\tif strings.HasSuffix(URL, \"yaml\") {\n\t\taMap = map[string]interface{}{}\n\t\tif err := yaml.Unmarshal(data, &aMap); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\taMap = map[string]interface{}{}\n\t\tif err := json.Unmarshal(data, &aMap); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn toolbox.DefaultConverter.AssignConverted(target, aMap)\n}", "func (t TypeURI) Short() string {\n\treturn XDSShortURINames[t]\n}", "func fromProtocolURI(uri string) (source.URI, error) {\n\tunescaped, err := url.PathUnescape(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn source.URI(unescaped), nil\n}", "func (o ShortUrlOutput) SourceUrl() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ShortUrl) pulumi.StringOutput { return v.SourceUrl }).(pulumi.StringOutput)\n}", "func ConvertToDirectLink(auditURL string) string {\n\t// eg. we have https://drive.google.com/open?id=1q4ubKjRBCPS1eViYyiLcivp4cA7iG41d\n\t// we want to convert it to : https://drive.google.com/uc?export=download&id=1q4ubKjRBCPS1eViYyiLcivp4cA7iG41d\n\t// SOMETHING\n\tu, err := url.Parse(auditURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// SOMETHING\n\tid := u.Query()[\"id\"][0]\n\tlog.Print(id)\n\ts := \"https://drive.google.com/uc?export=download\" + \"&\" + \"id=\" + id\n\treturn s\n}", "func (client *Client) IdFromURL(urlString string) (string, os.Error) {\n\tvar url *http.URL\n\tvar err os.Error\n\tif url, err = http.ParseURL(urlString); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(url.Path[len(client.resource.Path):]), nil\n}", "func processUrl(new_url, domain string) string {\n\tu, err := url.Parse(new_url)\n\tif err != nil {\n\t\tlog.Println(\"URL from page so damaged even url.Parse won't handle it -\", err)\n\t\treturn \"\"\n\t}\n\tbase, err := url.Parse(domain)\n\tif err != nil {\n\t\tlog.Fatal(\"Should never happen, domain validated earlier -\", err)\n\t}\n\tprocessed := base.ResolveReference(u)\n\tprocessed.Fragment = \"\"\n\tprocessed.RawQuery = \"\"\n\treturn processed.String()\n}", "func URLify(buffer []byte, originalLen int) {\n\tspaces := 0\n\tfor i := 0; i < originalLen; i++ {\n\t\tif buffer[i] == ' ' {\n\t\t\tspaces++\n\t\t}\n\t}\n\tif originalLen+spaces*2 > len(buffer) {\n\t\treturn\n\t}\n\ti := originalLen - 1\n\tj := originalLen + spaces*2 - 1\n\tfor i >= 0 && j >= 2 {\n\t\tif buffer[i] == ' ' {\n\t\t\tbuffer[j-2] = '%'\n\t\t\tbuffer[j-1] = '2'\n\t\t\tbuffer[j] = '0'\n\t\t\tj -= 3\n\t\t} else {\n\t\t\tbuffer[j] = buffer[i]\n\t\t\tj--\n\t\t}\n\t\ti--\n\t}\n}", "func CanonicalizeURL(base *url.URL, rawurl string) (string, error) {\n\tparsed, err := base.Parse(rawurl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tparsed.Fragment = \"\"\n\treturn parsed.String(), nil\n}", "func NormalizeURL(u string) (*url.URL, error) {\n\tif !isHTTPPrepended(u) {\n\t\tu = prependHTTP(u)\n\t}\n\n\t// We do it like browsers, just remove the trailing slash.\n\t// This will save us from a lot of problems later.\n\tu = strings.TrimSuffix(u, \"/\")\n\n\tparsedURL, err := url.Parse(u)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to parse URL/hostname: %s. %s\", u, err)\n\t}\n\n\treturn parsedURL, nil\n}", "func (*XMLDocument) URLUnencoded() (URLUnencoded string) {\n\tmacro.Rewrite(\"$_.URLUnencoded\")\n\treturn URLUnencoded\n}", "func onGetRedirectLink(w http.ResponseWriter, r *http.Request) {\n\tvalues := r.URL.Query()\n\tshortURL, ok := values[\"shortURL\"]\n\tif ok {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif len(shortURL) >= 1 {\n\t\t\tcorrectURL, err := url.ParseRequestURI(shortURL[0]) // parsing the string to correct URL\n\t\t\tif err != nil {\n\t\t\t\tresponseToCLient(w, \"Please enter the correct and complete url, example - http://google.com\")\n\t\t\t} else {\n\t\t\t\tif correctURL.Host != \"mydomain.com\" { // Checking whether this url is from our domain only\n\t\t\t\t\tresponseToCLient(w, \"Not the correct short link provided by mydomain.com\")\n\t\t\t\t} else {\n\t\t\t\t\ta := correctURL.Path[1:]\n\t\t\t\t\tstr, ok := getLongURL(a)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tresponseToCLient(w, \"Redirect Link is : \"+str)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tresponseToCLient(w, str)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tresponseToCLient(w, \"Please check the request parameters\")\n\t\t}\n\t} else {\n\t\tresponseToCLient(w, \"No shortURL found, Please check the request parameters\")\n\n\t}\n\n}", "func fixImgurLink(link string) string {\n\toriginalurl, err := url.Parse(link)\n\n\tif err != nil || originalurl.Host != \"imgur.com\" {\n\t\treturn link\n\t}\n\n\treturn fmt.Sprintf(\"http://i.imgur.com%s.gif\", originalurl.Path)\n}", "func StandardizeFinalShortLinkSlash(url string) string {\n\turlLen := len(url)\n\tif urlLen <= 0 {\n\t\treturn \"\"\n\t}\n\tif url[urlLen-1] == '/' {\n\t\treturn url[:urlLen-1]\n\t}\n\treturn url\n}", "func String2Int(shortURL string) (seq uint64) {\n\tshortURL = reverse(shortURL)\n\tfor index, char := range shortURL {\n\t\tbase := uint64(math.Pow(float64(BaseStringLength), float64(index)))\n\t\tseq += uint64(strings.Index(BaseString, string(char))) * base\n\t}\n\treturn\n}", "func URLShortenedEQ(v string) predicate.Token {\n\treturn predicate.Token(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldURLShortened), v))\n\t},\n\t)\n}", "func GenerateShortenedURL() string {\n\tlength := 6\n\turl := make([]rune, length)\n\trand.Seed(time.Now().UnixNano())\n\tfor i := range url {\n\t\turl[i] = letters[rand.Intn(len(letters))]\n\t}\n\tfmt.Println(string(url))\n\treturn string(url)\n}", "func (v *Libravatar) FromURL(openid string) (string, error) {\n\tourl, err := url.Parse(openid)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !ourl.IsAbs() {\n\t\treturn \"\", fmt.Errorf(\"Is not an absolute URL\")\n\t} else if ourl.Scheme != \"http\" && ourl.Scheme != \"https\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid protocol: %s\", ourl.Scheme)\n\t}\n\n\tlink, err := v.process(nil, ourl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn link, nil\n}", "func (_m *DBAdapter) ExpandURL(short string) (string, error) {\n\tret := _m.Called(short)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(short)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(short)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mg *MongoConn) CreateShortURL(c *fiber.Ctx) error {\n\tfmt.Println(\"entering db (redir)\")\n\treqBody := URLRequest{}\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tif err := c.BodyParser(&reqBody); err != nil {\n\t\tcancel()\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\n\tinsDoc := CreateURL{\n\t\tURLMain: reqBody.URLMain,\n\t\tShortID: reqBody.Event,\n\t}\n\t_, err := mg.Db.Collection(os.Getenv(\"COLLECTION_NAME\")).InsertOne(ctx, insDoc)\n\tif err != nil {\n\t\tcancel()\n\t\treturn c.Status(400).JSON(fiber.Map{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\tbaseString := \"http://localhost:3000/\"\n\tcancel()\n\tfmt.Println(\"short url created\")\n\treturn c.Status(201).JSON(fiber.Map{\n\t\t\"short_url\": baseString + insDoc.ShortID,\n\t})\n}", "func ToURL(s string) string {\n\ts = strings.Trim(s, \" \")\n\ts = strings.ReplaceAll(s, \" \", \"%20\")\n\treturn s\n}", "func parseUrl(rawurl string) (string, error) {\n\t_, err := url.Parse(rawurl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn rawurl, nil\n}", "func ExpandEndpoint(w http.ResponseWriter, req *http.Request) {\n\tvar n1q1Params = []interface{}\n\tquery := gocb.NewN1qlQuery(\"SELECT `\" + bucketName + \"`.* FROM `\" + bucketName + \"` WHERE shortUrl = $1\")\n\tparams := req.URL.Query()\n\tn1q1Params = append(n1q1Params, params.Get(\"ShortURL\"))\n\trows, _ := bucket.ExecuteN1qlQuery(query, n1q1Params)\n\tvar row = ShortURL\n\trows.One(&row)\n\tjson.NewEncoder(w).Encode(row)\n}", "func (app *App) expand(w http.ResponseWriter, r *http.Request) {\n\tshortened := r.URL.Query().Get(\"url\")\n\tif shortened == \"\" {\n\t\tresp, _ := json.Marshal(responseMessage{Error: \"No url provided. Use 'url' param.\"})\n\t\thttp.Error(w, string(resp), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\texpanded, err := app.Expander.ExpandUrl(shortened)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: (%s) %s [url: %s]\", r.RemoteAddr, err.Error(), shortened)\n\t\tswitch err {\n\t\tcase urlexpander.ErrDisallowedByRobotsTxt, urlexpander.ErrInvalidUrl, urlexpander.ErrLongUrl:\n\t\t\tresp, _ := json.Marshal(responseMessage{Error: err.Error()})\n\t\t\thttp.Error(w, string(resp), http.StatusBadRequest)\n\t\tdefault:\n\t\t\tresp, _ := json.Marshal(responseMessage{Error: \"Uknown error\"})\n\t\t\thttp.Error(w, string(resp), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tresp := responseMessage{Original: shortened, Expanded: expanded}\n\tjson.NewEncoder(w).Encode(resp)\n}", "func mustPU(rawurl string) *url.URL {\n\tif u, err := url.Parse(rawurl); err != nil {\n\t\tpanic(err)\n\t} else {\n\t\treturn u\n\t}\n}", "func getProcessedURL(rawURL string) string {\n\turl, _ := url.Parse(rawURL)\n\treturn url.String()\n}", "func (psql *Postgres) GetShortByLong(longURL string) (string, error) {\n\tquery := \"SELECT short FROM shortener WHERE long = $1;\"\n\trows, err := psql.db.Query(query, longURL)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"query %s: %v\", query, err)\n\t}\n\n\tif !rows.Next() {\n\t\treturn \"\", nil\n\t}\n\n\tvar short string\n\tif err = rows.Scan(&short); err != nil {\n\t\treturn \"\", fmt.Errorf(\"scan sql.Row: %v\", err)\n\t}\n\n\treturn short, nil\n}", "func StandardizeURL(url string) string {\n\tlink := url\n\tvar schema, domain, path string\n\n\t// Try to get the schema\n\tslice := strings.SplitN(url, \"://\", 2)\n\tif len(slice) == 2 && len(slice[0]) < 10 { // schema exists\n\t\tschema = slice[0] + \"://\"\n\t\tlink = slice[1]\n\t} else {\n\t\tschema = \"http://\"\n\t}\n\n\t// Get the domain\n\tslice = strings.SplitN(link, \"/\", 2)\n\tif len(slice) == 2 {\n\t\tdomain = slice[0]\n\t\tpath = \"/\" + slice[1]\n\t} else {\n\t\tdomain = slice[0]\n\t\tpath = \"/\"\n\t}\n\n\tdomain, _ = idna.ToASCII(domain)\n\tlink = schema + domain + path\n\n\treturn link\n}", "func (s Shortener) Resolve(uri string) string {\n\tu, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tid := strings.TrimLeft(u.Path, \"/\")\n\treturn s.db.GetURL(id)\n}", "func rawUrl(htmlUrl string) string {\n\tdomain := strings.Replace(htmlUrl, \"https://github.com/\", \"https://raw.githubusercontent.com/\", -1)\n\treturn strings.Replace(domain, \"/blob/\", \"/\", -1)\n}", "func unmarshalUpdateShortenerPayload(ctx context.Context, service *goa.Service, req *http.Request) error {\n\tpayload := &updateLinkPayload{}\n\tif err := service.DecodeRequest(req, payload); err != nil {\n\t\treturn err\n\t}\n\tif err := payload.Validate(); err != nil {\n\t\t// Initialize payload with private data structure so it can be logged\n\t\tgoa.ContextRequest(ctx).Payload = payload\n\t\treturn err\n\t}\n\tgoa.ContextRequest(ctx).Payload = payload.Publicize()\n\treturn nil\n}" ]
[ "0.71876717", "0.65989834", "0.6503071", "0.64743614", "0.6404518", "0.6319766", "0.6202989", "0.6136067", "0.61311615", "0.6115092", "0.60274875", "0.6020472", "0.600632", "0.59897506", "0.5982226", "0.5975748", "0.5902325", "0.5834771", "0.5825918", "0.5757999", "0.57320887", "0.56705", "0.56489563", "0.56415886", "0.5590369", "0.5565439", "0.55065143", "0.5504418", "0.5422832", "0.5414742", "0.5385716", "0.53705657", "0.5349816", "0.53413427", "0.5337946", "0.5315452", "0.5304553", "0.5294583", "0.528088", "0.52393824", "0.52159864", "0.51881063", "0.51825017", "0.5179679", "0.5173797", "0.51374316", "0.50722134", "0.50473166", "0.50285494", "0.50167763", "0.50093126", "0.49970832", "0.49967903", "0.49954554", "0.49776936", "0.4974463", "0.49398416", "0.49222377", "0.49151394", "0.48836043", "0.48812363", "0.48785308", "0.48676383", "0.4850375", "0.48495078", "0.4849324", "0.48399442", "0.4837248", "0.48291114", "0.48267722", "0.48217523", "0.4806398", "0.47801325", "0.47782362", "0.4770329", "0.47663972", "0.47523913", "0.47360587", "0.47316873", "0.4726657", "0.47156006", "0.4705892", "0.4702423", "0.4693508", "0.46928677", "0.46905643", "0.46868333", "0.46822813", "0.46813348", "0.46750754", "0.46565706", "0.46479505", "0.4630405", "0.46300644", "0.4629617", "0.4626053", "0.46251974", "0.46227202", "0.46220705", "0.46201262" ]
0.7159166
1
lspTests runs all test suites for LSP functionality.
func lspTests(t testing.TB, ctx context.Context, c *jsonrpc2.Conn, root *gituri.URI, wantHover, wantDefinition, wantXDefinition map[string]string, wantReferences, wantSymbols map[string][]string, wantXDependencies string, wantXReferences map[*lsext.WorkspaceReferencesParams][]string, wantXPackages []string) { for pos, want := range wantHover { tbRun(t, fmt.Sprintf("hover-%s", strings.Replace(pos, "/", "-", -1)), func(t testing.TB) { hoverTest(t, ctx, c, root, pos, want) }) } for pos, want := range wantDefinition { tbRun(t, fmt.Sprintf("definition-%s", strings.Replace(pos, "/", "-", -1)), func(t testing.TB) { definitionTest(t, ctx, c, root, pos, want) }) } for pos, want := range wantXDefinition { tbRun(t, fmt.Sprintf("xdefinition-%s", strings.Replace(pos, "/", "-", -1)), func(t testing.TB) { xdefinitionTest(t, ctx, c, root, pos, want) }) } for pos, want := range wantReferences { tbRun(t, fmt.Sprintf("references-%s", pos), func(t testing.TB) { referencesTest(t, ctx, c, root, pos, want) }) } for query, want := range wantSymbols { tbRun(t, fmt.Sprintf("symbols(q=%q)", query), func(t testing.TB) { symbolsTest(t, ctx, c, root, query, want) }) } if wantXDependencies != "" { tbRun(t, fmt.Sprintf("xdependencies-"+wantXDependencies), func(t testing.TB) { var deps []lspext.DependencyReference err := c.Call(ctx, "workspace/xdependencies", struct{}{}, &deps) if err != nil { t.Fatal(err) } jsonTest(t, deps, "xdependencies-"+wantXDependencies) }) } for params, want := range wantXReferences { tbRun(t, fmt.Sprintf("xreferences"), func(t testing.TB) { workspaceReferencesTest(t, ctx, c, root, *params, want) }) } if wantXPackages != nil { tbRun(t, "xpackages", func(t testing.TB) { workspacePackagesTest(t, ctx, c, root, wantXPackages) }) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestLSP(t *testing.T) {\n\ttests.RunTests(t, \"testdata\", true, testLSP)\n}", "func ListTests() {\n\tfmt.Printf(\"Available test suites:\\n\\tauto\\n\")\n\tfor _, suite := range AllSuites {\n\t\tfmt.Printf(\"\\t%s\\n\", suite)\n\t}\n}", "func runTestSuite(t *testing.T, ts TestSuite) {\n\t// Load only the rule for this test suite\n\truleConfigPath := strings.Split(ts.RootPath, \"config-lint/cli/assets/\")[1] + \"/rule.yml\"\n\truleSet, err := loadBuiltInRuleSet(ruleConfigPath)\n\tif err != nil {\n\t\tassert.Nil(t, err, \"Cannot load built-in Terraform rule\")\n\t}\n\n\tfor _, tc := range ts.Tests {\n\t\toptions := linter.Options{\n\t\t\tRuleIDs: []string{tc.RuleId},\n\t\t}\n\t\tvs := assertion.StandardValueSource{}\n\n\t\t// validate the rule set\n\t\tif contains(tc.Tags, \"terraform11\") {\n\t\t\t// Load the test resources for this test suite\n\t\t\ttestResourceDirectory := strings.Split(ts.RootPath, \"config-lint/cli/\")[1] + \"/tests/terraform11/\"\n\t\t\ttestResources, err := getTestResources(testResourceDirectory)\n\t\t\tif err != nil {\n\t\t\t\tassert.Nil(t, err, \"Cannot load built-in Terraform 11 test resources\")\n\n\t\t\t}\n\t\t\t// Defining 'tf11' for the Parser type\n\t\t\tl, err := linter.NewLinter(ruleSet, vs, testResources, \"tf11\")\n\n\t\t\treport, err := l.Validate(ruleSet, options)\n\t\t\tassert.Nil(t, err, \"Validate failed for file\")\n\n\t\t\twarningViolationsReported := getViolationsString(\"WARNING\", report.Violations)\n\t\t\twarningMessage := fmt.Sprintf(\"Expecting %d warnings for rule %s:\\n %s\", tc.Warnings, tc.RuleId, warningViolationsReported)\n\t\t\tassert.Equal(t, tc.Warnings, numberOfWarnings(report.Violations), warningMessage)\n\n\t\t\tfailureViolationsReported := getViolationsString(\"FAILURE\", report.Violations)\n\t\t\tfailureMessage := fmt.Sprintf(\"Expecting %d failures for rule %s:\\n %s\", tc.Failures, tc.RuleId, failureViolationsReported)\n\t\t\tassert.Equal(t, tc.Failures, numberOfFailures(report.Violations), failureMessage)\n\t\t}\n\n\t\tif contains(tc.Tags, \"terraform12\") {\n\t\t\t// Load the test resources for this test suite\n\t\t\ttestResourceDirectory := strings.Split(ts.RootPath, \"config-lint/cli/\")[1] + \"/tests/terraform12/\"\n\t\t\ttestResources, err := getTestResources(testResourceDirectory)\n\t\t\tif err != nil {\n\t\t\t\tassert.Nil(t, err, \"Cannot load built-in Terraform 12 test resources\")\n\n\t\t\t}\n\t\t\t// Defining 'tf11' for the Parser type\n\t\t\tl, err := linter.NewLinter(ruleSet, vs, testResources, \"tf12\")\n\n\t\t\treport, err := l.Validate(ruleSet, options)\n\t\t\tassert.Nil(t, err, \"Validate failed for file\")\n\n\t\t\twarningViolationsReported := getViolationsString(\"WARNING\", report.Violations)\n\t\t\twarningMessage := fmt.Sprintf(\"Expecting %d warnings for rule %s:\\n %s\", tc.Warnings, tc.RuleId, warningViolationsReported)\n\t\t\tassert.Equal(t, tc.Warnings, numberOfWarnings(report.Violations), warningMessage)\n\n\t\t\tfailureViolationsReported := getViolationsString(\"FAILURE\", report.Violations)\n\t\t\tfailureMessage := fmt.Sprintf(\"Expecting %d failures for rule %s:\\n %s\", tc.Failures, tc.RuleId, failureViolationsReported)\n\t\t\tassert.Equal(t, tc.Failures, numberOfFailures(report.Violations), failureMessage)\n\t\t}\n\t}\n}", "func main() {\n Lns_InitModOnce(LnsRuntimeOpt{ Int2strModeDepend })\n //TEST:Lns_Testing_init()\n Lns_RunMain( Main___main )\n //TEST:Testing_run( \"\" )\n //TEST:Testing_outputAllResult(Lns_io_stdout)\n}", "func (m *LoadManager) RunSuite() {\n\tm.HandleShutdownSignal()\n\n\tt := timeNow()\n\tstartTime := epochNowMillis(t)\n\thrStartTime := timeHumanReadable(t)\n\n\tfor _, step := range m.Steps {\n\t\tlog.Infof(\"running step: %s, execution mode: %s\", step.Name, step.ExecutionMode)\n\t\tswitch step.ExecutionMode {\n\t\tcase ParallelMode:\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(len(step.Runners))\n\n\t\t\tfor _, r := range step.Runners {\n\t\t\t\tr.SetupHandleStore(m)\n\t\t\t\tgo r.Run(&wg, m)\n\t\t\t}\n\t\t\twg.Wait()\n\t\tcase SequenceMode:\n\t\t\tfor _, r := range step.Runners {\n\t\t\t\tr.SetupHandleStore(m)\n\t\t\t\tr.Run(nil, m)\n\t\t\t}\n\t\tcase SequenceValidateMode:\n\t\t\tfor _, r := range step.Runners {\n\t\t\t\tr.SetupHandleStore(m)\n\t\t\t\tr.Run(nil, m)\n\t\t\t\tr.SetValidationParams()\n\t\t\t\tr.Run(nil, m)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Fatal(\"please set execution_mode, parallel, sequence or sequence_validate\")\n\t\t}\n\t}\n\tif m.GeneratorConfig.Grafana.URL != \"\" {\n\t\tt = timeNow()\n\t\tfinishTime := epochNowMillis(t)\n\t\thrFinishTime := timeHumanReadable(t)\n\n\t\tTimerangeUrl(startTime, finishTime)\n\t\tHumanReadableTestInterval(hrStartTime, hrFinishTime)\n\t}\n\tm.Shutdown()\n}", "func TestAll() error {\n\tout, err := sh.Output(\"go\", \"test\", \"./...\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Print(out)\n\treturn nil\n}", "func TestAll(t *testing.T) {\n\tcfg := initializeTests(t)\n\ttestUser(t, cfg)\n\ttestHomeMessage(t, cfg)\n\ttestDepartment(t, cfg)\n\ttestCommunity(t, cfg)\n\ttestCity(t, cfg)\n\ttestCopro(t, cfg)\n\ttestBudgetAction(t, cfg)\n\ttestRenewProject(t, cfg)\n\ttestHousingType(t, cfg)\n\ttestHousing(t, cfg)\n\ttestCommitment(t, cfg)\n\ttestBeneficiary(t, cfg)\n\ttestPayment(t, cfg)\n\ttestBudgetSector(t, cfg)\n\ttestCommitmentLink(t, cfg)\n\ttestCommission(t, cfg)\n\ttestRenewProjectForecast(t, cfg)\n\ttestHousingForecast(t, cfg)\n\ttestCoproForecast(t, cfg)\n\ttestSettings(t, cfg)\n\ttestHome(t, cfg)\n\ttestBeneficiaryDatas(t, cfg)\n\ttestBeneficiaryPayments(t, cfg)\n\ttestPmtRatio(t, cfg)\n\ttestPmtForecasts(t, cfg)\n\ttestCmtForecasts(t, cfg)\n\ttestLinkCommitmentsHousings(t, cfg)\n\ttestCoproCommitmentLink(t, cfg)\n\ttestRPEventType(t, cfg)\n\ttestRPEvent(t, cfg)\n\ttestRenewProjectReport(t, cfg)\n\ttestRPPerCommunityReport(t, cfg)\n\ttestRPCmtCityJoin(t, cfg)\n\ttestDepartmentReport(t, cfg)\n\ttestCityReport(t, cfg)\n\ttestPreProg(t, cfg)\n\ttestProg(t, cfg)\n\ttestRPLS(t, cfg)\n\ttestSummaries(t, cfg)\n\ttestHousingSummary(t, cfg)\n\ttestCoproEventType(t, cfg)\n\ttestCoproEvent(t, cfg)\n\ttestCoproDoc(t, cfg)\n\ttestCoproReport(t, cfg)\n\ttestRPMultiAnnualReport(t, cfg)\n\ttestPaymentCredits(t, cfg)\n\ttestPaymentCreditJournals(t, cfg)\n\ttestPlacement(t, cfg)\n\ttestBeneficiaryGroup(t, cfg)\n\ttestBeneficiaryGroupDatas(t, cfg)\n\ttestHousingTypology(t, cfg)\n\ttestHousingConvention(t, cfg)\n\ttestHousingComment(t, cfg)\n\ttestHousingTransfer(t, cfg)\n\ttestConventionType(t, cfg)\n\ttestReservationFee(t, cfg)\n\ttestGetDifActionPaymentPrevisions(t, cfg)\n\ttestReservationReport(t, cfg)\n\ttestSoldCommitment(t, cfg)\n\ttestAvgPmtTime(t, cfg)\n\ttestPaymentDemands(t, cfg)\n\ttestPaymentDelays(t, cfg)\n}", "func TestPCall(t *testing.T){\n\tfilename := \"main.lua\"\n\tls := golua.NewLuaState()\n\tls.LoadFile(filename)\n\tif err := ls.PCall(0, 0, 0); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (i *InspecRunner) RunAllTests(path string) (verifiers.TestSuite, error) {\n\tv := inspec.InspecVerifier{}\n\terr := v.Setup(path)\n\n\tif err != nil {\n\t\tfmt.Println(\"error during inspec verifier setup\")\n\t\treturn verifiers.TestSuite{}, err\n\t}\n\n\tresult, err := v.Check(path)\n\n\tif err != nil {\n\t\tfmt.Println(\"error during inspec test execution\")\n\t\treturn result, err\n\t}\n\treturn result, nil\n\n}", "func main() {\n\tpp.Println(\"=========================================\")\n\tpp.Println(\"No local tests available.\")\n\tpp.Println(\"=========================================\")\n}", "func TestSolution(t *testing.T) {\n\tfor test, f := range tests {\n\t\tRunTest(t, test, f, SampleTestCases)\n\t}\n}", "func (st *buildStatus) runTests(helpers <-chan buildlet.Client) (remoteErr, err error) {\n\ttestNames, remoteErr, err := st.distTestList()\n\tif remoteErr != nil {\n\t\treturn fmt.Errorf(\"distTestList remote: %v\", remoteErr), nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"distTestList exec: %v\", err)\n\t}\n\ttestStats := getTestStats(st)\n\n\tset, err := st.newTestSet(testStats, testNames)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tst.LogEventTime(\"starting_tests\", fmt.Sprintf(\"%d tests\", len(set.items)))\n\tstartTime := time.Now()\n\n\tworkDir, err := st.bc.WorkDir(st.ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error discovering workdir for main buildlet, %s: %v\", st.bc.Name(), err)\n\t}\n\n\tmainBuildletGoroot := st.conf.FilePathJoin(workDir, \"go\")\n\tmainBuildletGopath := st.conf.FilePathJoin(workDir, \"gopath\")\n\n\t// We use our original buildlet to run the tests in order, to\n\t// make the streaming somewhat smooth and not incredibly\n\t// lumpy. The rest of the buildlets run the largest tests\n\t// first (critical path scheduling).\n\t// The buildletActivity WaitGroup is used to track when all\n\t// the buildlets are dead or done.\n\tvar buildletActivity sync.WaitGroup\n\tbuildletActivity.Add(2) // one per goroutine below (main + helper launcher goroutine)\n\tgo func() {\n\t\tdefer buildletActivity.Done() // for the per-goroutine Add(2) above\n\t\tfor !st.bc.IsBroken() {\n\t\t\ttis, ok := set.testsToRunInOrder()\n\t\t\tif !ok {\n\t\t\t\tselect {\n\t\t\t\tcase <-st.ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tst.runTestsOnBuildlet(st.bc, tis, mainBuildletGoroot, mainBuildletGopath)\n\t\t}\n\t\tst.LogEventTime(\"main_buildlet_broken\", st.bc.Name())\n\t}()\n\tgo func() {\n\t\tdefer buildletActivity.Done() // for the per-goroutine Add(2) above\n\t\tfor helper := range helpers {\n\t\t\tbuildletActivity.Add(1)\n\t\t\tgo func(bc buildlet.Client) {\n\t\t\t\tdefer buildletActivity.Done() // for the per-helper Add(1) above\n\t\t\t\tdefer st.LogEventTime(\"closed_helper\", bc.Name())\n\t\t\t\tdefer bc.Close()\n\t\t\t\tif devPause {\n\t\t\t\t\tdefer time.Sleep(5 * time.Minute)\n\t\t\t\t\tdefer st.LogEventTime(\"DEV_HELPER_SLEEP\", bc.Name())\n\t\t\t\t}\n\t\t\t\tst.LogEventTime(\"got_empty_test_helper\", bc.String())\n\t\t\t\tif err := bc.PutTarFromURL(st.ctx, st.SnapshotURL(pool.NewGCEConfiguration().BuildEnv()), \"go\"); err != nil {\n\t\t\t\t\tlog.Printf(\"failed to extract snapshot for helper %s: %v\", bc.Name(), err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tworkDir, err := bc.WorkDir(st.ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error discovering workdir for helper %s: %v\", bc.Name(), err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tst.LogEventTime(\"test_helper_set_up\", bc.Name())\n\t\t\t\tgoroot := st.conf.FilePathJoin(workDir, \"go\")\n\t\t\t\tgopath := st.conf.FilePathJoin(workDir, \"gopath\")\n\t\t\t\tfor !bc.IsBroken() {\n\t\t\t\t\ttis, ok := set.testsToRunBiggestFirst()\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tst.LogEventTime(\"no_new_tests_remain\", bc.Name())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tst.runTestsOnBuildlet(bc, tis, goroot, gopath)\n\t\t\t\t}\n\t\t\t\tst.LogEventTime(\"test_helper_is_broken\", bc.Name())\n\t\t\t}(helper)\n\t\t}\n\t}()\n\n\t// Convert a sync.WaitGroup into a channel.\n\t// Aside: https://groups.google.com/forum/#!topic/golang-dev/7fjGWuImu5k\n\tbuildletsGone := make(chan struct{})\n\tgo func() {\n\t\tbuildletActivity.Wait()\n\t\tclose(buildletsGone)\n\t}()\n\n\tvar lastMetadata string\n\tvar lastHeader string\n\tvar serialDuration time.Duration\n\tfor _, ti := range set.items {\n\tAwaitDone:\n\t\tfor {\n\t\t\ttimer := time.NewTimer(30 * time.Second)\n\t\t\tselect {\n\t\t\tcase <-ti.done: // wait for success\n\t\t\t\ttimer.Stop()\n\t\t\t\tbreak AwaitDone\n\t\t\tcase <-timer.C:\n\t\t\t\tst.LogEventTime(\"still_waiting_on_test\", ti.name.Old)\n\t\t\tcase <-buildletsGone:\n\t\t\t\tset.cancelAll()\n\t\t\t\treturn nil, errBuildletsGone\n\t\t\t}\n\t\t}\n\n\t\tserialDuration += ti.execDuration\n\t\tif len(ti.output) > 0 {\n\t\t\tmetadata, header, out := parseOutputAndHeader(ti.output)\n\t\t\tprintHeader := false\n\t\t\tif metadata != lastMetadata {\n\t\t\t\tlastMetadata = metadata\n\t\t\t\tfmt.Fprintf(st, \"\\n%s\\n\", metadata)\n\t\t\t\t// Always include the test header after\n\t\t\t\t// metadata changes. This is a readability\n\t\t\t\t// optimization that ensures that tests are\n\t\t\t\t// always immediately preceded by their test\n\t\t\t\t// banner, even if it is duplicate banner\n\t\t\t\t// because the test metadata changed.\n\t\t\t\tprintHeader = true\n\t\t\t}\n\t\t\tif header != lastHeader {\n\t\t\t\tlastHeader = header\n\t\t\t\tprintHeader = true\n\t\t\t}\n\t\t\tif printHeader {\n\t\t\t\tfmt.Fprintf(st, \"\\n%s\\n\", header)\n\t\t\t}\n\t\t\tif pool.NewGCEConfiguration().InStaging() {\n\t\t\t\tout = bytes.TrimSuffix(out, nl)\n\t\t\t\tst.Write(out)\n\t\t\t\tfmt.Fprintf(st, \" (shard %s; par=%d)\\n\", ti.shardIPPort, ti.groupSize)\n\t\t\t} else {\n\t\t\t\tst.Write(out)\n\t\t\t}\n\t\t}\n\n\t\tif ti.remoteErr != nil {\n\t\t\tset.cancelAll()\n\t\t\treturn fmt.Errorf(\"dist test failed: %s: %v\", ti.name, ti.remoteErr), nil\n\t\t}\n\t}\n\telapsed := time.Since(startTime)\n\tvar msg string\n\tif st.conf.NumTestHelpers(st.isTry()) > 0 {\n\t\tmsg = fmt.Sprintf(\"took %v; aggregate %v; saved %v\", elapsed, serialDuration, serialDuration-elapsed)\n\t} else {\n\t\tmsg = fmt.Sprintf(\"took %v\", elapsed)\n\t}\n\tst.LogEventTime(\"tests_complete\", msg)\n\tfmt.Fprintf(st, \"\\nAll tests passed.\\n\")\n\treturn nil, nil\n}", "func (suite *AddCommandTestSuite) TestExecuteWhenMultipleTracksFound() {\n\n}", "func (sfs *SuiteFS) TestAll(t *testing.T) {\n\tsfs.RunTests(t, UsrTest,\n\t\t// VFS tests\n\t\tsfs.TestClone,\n\t\tsfs.TestChdir,\n\t\tsfs.TestChtimes,\n\t\tsfs.TestCreate,\n\t\tsfs.TestEvalSymlink,\n\t\tsfs.TestGetTempDir,\n\t\tsfs.TestLink,\n\t\tsfs.TestLstat,\n\t\tsfs.TestMkdir,\n\t\tsfs.TestMkdirAll,\n\t\tsfs.TestOpen,\n\t\tsfs.TestOpenFileWrite,\n\t\tsfs.TestReadDir,\n\t\tsfs.TestReadFile,\n\t\tsfs.TestReadlink,\n\t\tsfs.TestRemove,\n\t\tsfs.TestRemoveAll,\n\t\tsfs.TestRename,\n\t\tsfs.TestSameFile,\n\t\tsfs.TestStat,\n\t\tsfs.TestSymlink,\n\t\tsfs.TestTempDir,\n\t\tsfs.TestTempFile,\n\t\tsfs.TestTruncate,\n\t\tsfs.TestWriteFile,\n\t\tsfs.TestWriteString,\n\t\tsfs.TestToSysStat,\n\t\tsfs.TestUmask,\n\n\t\t// File tests\n\t\tsfs.TestFileChdir,\n\t\tsfs.TestFileCloseWrite,\n\t\tsfs.TestFileCloseRead,\n\t\tsfs.TestFileFd,\n\t\tsfs.TestFileName,\n\t\tsfs.TestFileRead,\n\t\tsfs.TestFileReadDir,\n\t\tsfs.TestFileReaddirnames,\n\t\tsfs.TestFileSeek,\n\t\tsfs.TestFileStat,\n\t\tsfs.TestFileSync,\n\t\tsfs.TestFileTruncate,\n\t\tsfs.TestFileWrite,\n\t\tsfs.TestFileWriteString,\n\t\tsfs.TestFileWriteTime,\n\n\t\t// Path tests\n\t\tsfs.TestAbs,\n\t\tsfs.TestBase,\n\t\tsfs.TestClean,\n\t\tsfs.TestDir,\n\t\tsfs.TestFromToSlash,\n\t\tsfs.TestGlob,\n\t\tsfs.TestIsAbs,\n\t\tsfs.TestJoin,\n\t\tsfs.TestRel,\n\t\tsfs.TestSplit,\n\t\tsfs.TestWalk)\n\n\t// Tests to be run as root\n\tsfs.RunTests(t, avfs.UsrRoot,\n\t\tsfs.TestChmod,\n\t\tsfs.TestChown,\n\t\tsfs.TestChroot,\n\t\tsfs.TestLchown,\n\t\tsfs.TestFileChmod,\n\t\tsfs.TestFileChown)\n}", "func (ts *TestSuite) RunTests() {\n\n\tif len(ts.Tests) == 0 {\n\t\tout.Printf(\"No tests to run\\n\")\n\t\treturn\n\t}\n\n\tstartTime := time.Now()\n\n\t// setup search\n\ts := search.NewSearch()\n\tsl := search.NewSearchLimits()\n\tsl.MoveTime = ts.Time\n\tsl.Depth = ts.Depth\n\tif sl.MoveTime > 0 {\n\t\tsl.TimeControl = true\n\t}\n\n\tout.Printf(\"Running Test Suite\\n\")\n\tout.Printf(\"==================================================================\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"No of tests: %d\\n\", len(ts.Tests))\n\tout.Println()\n\n\t// execute all tests and store results in the\n\t// test instance\n\tfor i, t := range ts.Tests {\n\t\tout.Printf(\"Test %d of %d\\nTest: %s -- Target Result %s\\n\", i+1, len(ts.Tests), t.line, t.targetMoves.StringUci())\n\t\tstartTime2 := time.Now()\n\t\trunSingleTest(s, sl, t)\n\t\telapsedTime := time.Since(startTime2)\n\t\tt.nodes = s.NodesVisited()\n\t\tt.time = s.LastSearchResult().SearchTime\n\t\tt.nps = util.Nps(s.NodesVisited(), s.LastSearchResult().SearchTime)\n\t\tout.Printf(\"Test finished in %d ms with result %s (%s) - nps: %d\\n\\n\",\n\t\t\telapsedTime.Milliseconds(), t.rType.String(), t.actual.StringUci(), t.nps)\n\t}\n\n\t// sum up result for report\n\ttr := &SuiteResult{}\n\tfor _, t := range ts.Tests {\n\t\ttr.Counter++\n\t\tswitch t.rType {\n\t\tcase NotTested:\n\t\t\ttr.NotTestedCounter++\n\t\tcase Skipped:\n\t\t\ttr.SkippedCounter++\n\t\tcase Failed:\n\t\t\ttr.FailedCounter++\n\t\tcase Success:\n\t\t\ttr.SuccessCounter++\n\t\t}\n\t\ttr.Nodes += t.nodes\n\t\ttr.Time += t.time\n\t}\n\tts.LastResult = tr\n\n\telapsed := time.Since(startTime)\n\n\t// print report\n\tout.Printf(\"Results for Test Suite\\n\", ts.FilePath)\n\tout.Printf(\"------------------------------------------------------------------------------------------------------------------------------------\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\" %-4s | %-10s | %-8s | %-8s | %-15s | %s | %s\\n\", \" Nr.\", \"Result\", \"Move\", \"Value\", \"Expected Result\", \"Fen\", \"Id\")\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tfor i, t := range ts.Tests {\n\t\tif t.tType == DM {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s%-15d | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), \"dm \", t.mateDepth, t.fen, t.id)\n\t\t} else {\n\t\t\tout.Printf(\" %-4d | %-10s | %-8s | %-8s | %s %-15s | %s | %s\\n\",\n\t\t\t\ti+1, t.rType.String(), t.actual.StringUci(), t.value.String(), t.tType.String(), t.targetMoves.StringUci(), t.fen, t.id)\n\t\t}\n\t}\n\tout.Printf(\"====================================================================================================================================\\n\")\n\tout.Printf(\"Summary:\\n\")\n\tout.Printf(\"EPD File: %s\\n\", ts.FilePath)\n\tout.Printf(\"SearchTime: %d ms\\n\", ts.Time.Milliseconds())\n\tout.Printf(\"MaxDepth: %d\\n\", ts.Depth)\n\tout.Printf(\"Date: %s\\n\", time.Now().Local())\n\tout.Printf(\"Successful: %-3d (%d %%)\\n\", tr.SuccessCounter, 100*tr.SuccessCounter/tr.Counter)\n\tout.Printf(\"Failed: %-3d (%d %%)\\n\", tr.FailedCounter, 100*tr.FailedCounter/tr.Counter)\n\tout.Printf(\"Skipped: %-3d (%d %%)\\n\", tr.SkippedCounter, 100*tr.SkippedCounter/tr.Counter)\n\tout.Printf(\"Not tested: %-3d (%d %%)\\n\", tr.NotTestedCounter, 100*tr.NotTestedCounter/tr.Counter)\n\tout.Printf(\"Test time: %s\\n\", elapsed)\n\tout.Printf(\"Configuration: %s\\n\", config.Settings.String())\n}", "func TestAllSpecs(t *testing.T) {\n\tr := gospec.NewRunner()\n\n\tr.Parallel = false\n\n\tr.BeforeEach = func() {\n\t\tConfigure(map[string]string{\n\t\t\t\"server\": \"localhost:7000\",\n\t\t\t\"process\": \"1\",\n\t\t\t\"database\": \"15\",\n\t\t\t\"pool\": \"1\",\n\t\t})\n\n\t\tfor port := 7000; port <= 7002; port++ {\n\t\t\tc, _ := redis.Dial(\"tcp\", \"localhost:\"+strconv.Itoa(port))\n\t\t\tc.Cmd(\"flushdb\")\n\t\t\tc.Close()\n }\n\t}\n\n\t// List all specs here\n\tr.AddSpec(WorkersSpec)\n\tr.AddSpec(ConfigSpec)\n\tr.AddSpec(MsgSpec)\n\tr.AddSpec(FetchSpec)\n\tr.AddSpec(WorkerSpec)\n\tr.AddSpec(ManagerSpec)\n\tr.AddSpec(ScheduledSpec)\n\tr.AddSpec(EnqueueSpec)\n\tr.AddSpec(MiddlewareSpec)\n\tr.AddSpec(MiddlewareRetrySpec)\n\tr.AddSpec(MiddlewareStatsSpec)\n\n\t// Run GoSpec and report any errors to gotest's `testing.T` instance\n\tgospec.MainGoTest(r, t)\n}", "func TestPanguTestSuite(t *testing.T) {\n\tsuite.Run(t, new(PanguTestSuite))\n}", "func TestRunTestAllReal(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping test in short mode.\")\n\t}\n\n\ttaskData := agent.TaskData{\n\t\tStringValues: map[string]string{\n\t\t\tCFG_TEST_TYPE: CFG_TYPE_ALL,\n\t\t\tCFG_SERVER_HOST: \"speedtest.nyc.rr.com:8080\",\n\t\t\tCFG_SERVER_ID: \"16976\",\n\t\t},\n\t\tIntValues: map[string]int{\n\t\t\tCFG_SERVER_ID: 16976,\n\t\t\tCFG_TIME_OUT: 5,\n\t\t},\n\t\tFloatValues: map[string]float64{CFG_MAX_SECONDS: 6},\n\t\tIntSlices: map[string][]int{\n\t\t\tCFG_DOWNLOAD_SIZES: {245388, 505544},\n\t\t\tCFG_UPLOAD_SIZES: {32768, 65536},\n\t\t},\n\t}\n\n\tspdTestRunner := SpeedTestRunner{}\n\n\tspTestResults, err := spdTestRunner.Run(taskData)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected Error: \\n%s\", err.Error())\n\t}\n\n\tresults := spTestResults.Latency.Seconds()\n\n\tif results <= 0 {\n\t\tt.Errorf(\"Error: Expected a positive Latency result, but got: %f\", results)\n\t} else {\n\t\tfmt.Printf(\"\\nLatency test results for server %d ... %f\\n\", taskData.IntValues[CFG_SERVER_ID], results)\n\t}\n\n\tresults = spTestResults.Download\n\tif results <= 0 {\n\t\tt.Errorf(\"Error: Expected a positive Download result, but got: %f\", results)\n\t} else {\n\t\tfmt.Printf(\"\\nDownload test results for server %d ... %f\\n\", taskData.IntValues[CFG_SERVER_ID], results)\n\t}\n\n\tresults = spTestResults.Upload\n\tif results <= 0 {\n\t\tt.Errorf(\"Error: Expected a positive Upload result, but got: %f\", results)\n\t} else {\n\t\tfmt.Printf(\"\\nUpload test results for server %d ... %f\\n\", taskData.IntValues[CFG_SERVER_ID], results)\n\t}\n}", "func TESTL(ir, emr operand.Op) { ctx.TESTL(ir, emr) }", "func TestLocalFSRepoTestSuite(t *testing.T) {\n\tsuite.Run(t, new(LocalFSRepoTestSuite))\n}", "func (st *buildStatus) runTests(helpers <-chan *buildlet.Client) (remoteErr, err error) {\n\ttestNames, err := st.distTestList()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"distTestList: %v\", err)\n\t}\n\tset := st.newTestSet(testNames)\n\tst.logEventTime(\"starting_tests\", fmt.Sprintf(\"%d tests\", len(set.items)))\n\tstartTime := time.Now()\n\n\tworkDir, err := st.bc.WorkDir()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error discovering workdir for main buildlet, %s: %v\", st.bc.Name(), err)\n\t}\n\tmainBuildletGoroot := st.conf.FilePathJoin(workDir, \"go\")\n\n\t// We use our original buildlet to run the tests in order, to\n\t// make the streaming somewhat smooth and not incredibly\n\t// lumpy. The rest of the buildlets run the largest tests\n\t// first (critical path scheduling).\n\t// The buildletActivity WaitGroup is used to track when all\n\t// the buildlets are dead or done.\n\tvar buildletActivity sync.WaitGroup\n\tbuildletActivity.Add(2) // one per goroutine below (main + helper launcher goroutine)\n\tgo func() {\n\t\tdefer buildletActivity.Done() // for the per-goroutine Add(2) above\n\t\tfor !st.bc.IsBroken() {\n\t\t\ttis, ok := set.testsToRunInOrder()\n\t\t\tif !ok {\n\t\t\t\tselect {\n\t\t\t\tcase <-st.ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tst.runTestsOnBuildlet(st.bc, tis, mainBuildletGoroot)\n\t\t}\n\t\tst.logEventTime(\"main_buildlet_broken\", st.bc.Name())\n\t}()\n\tgo func() {\n\t\tdefer buildletActivity.Done() // for the per-goroutine Add(2) above\n\t\tfor helper := range helpers {\n\t\t\tbuildletActivity.Add(1)\n\t\t\tgo func(bc *buildlet.Client) {\n\t\t\t\tdefer buildletActivity.Done() // for the per-helper Add(1) above\n\t\t\t\tdefer st.logEventTime(\"closed_helper\", bc.Name())\n\t\t\t\tdefer bc.Close()\n\t\t\t\tif devPause {\n\t\t\t\t\tdefer time.Sleep(5 * time.Minute)\n\t\t\t\t\tdefer st.logEventTime(\"DEV_HELPER_SLEEP\", bc.Name())\n\t\t\t\t}\n\t\t\t\tst.logEventTime(\"got_empty_test_helper\", bc.String())\n\t\t\t\tif err := bc.PutTarFromURL(st.snapshotURL(), \"go\"); err != nil {\n\t\t\t\t\tlog.Printf(\"failed to extract snapshot for helper %s: %v\", bc.Name(), err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tworkDir, err := bc.WorkDir()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error discovering workdir for helper %s: %v\", bc.Name(), err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tst.logEventTime(\"test_helper_set_up\", bc.Name())\n\t\t\t\tgoroot := st.conf.FilePathJoin(workDir, \"go\")\n\t\t\t\tfor !bc.IsBroken() {\n\t\t\t\t\ttis, ok := set.testsToRunBiggestFirst()\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tst.logEventTime(\"no_new_tests_remain\", bc.Name())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tst.runTestsOnBuildlet(bc, tis, goroot)\n\t\t\t\t}\n\t\t\t\tst.logEventTime(\"test_helper_is_broken\", bc.Name())\n\t\t\t}(helper)\n\t\t}\n\t}()\n\n\t// Convert a sync.WaitGroup into a channel.\n\t// Aside: https://groups.google.com/forum/#!topic/golang-dev/7fjGWuImu5k\n\tbuildletsGone := make(chan struct{})\n\tgo func() {\n\t\tbuildletActivity.Wait()\n\t\tclose(buildletsGone)\n\t}()\n\n\tvar lastBanner string\n\tvar serialDuration time.Duration\n\tfor _, ti := range set.items {\n\tAwaitDone:\n\t\tfor {\n\t\t\ttimer := time.NewTimer(30 * time.Second)\n\t\t\tselect {\n\t\t\tcase <-ti.done: // wait for success\n\t\t\t\ttimer.Stop()\n\t\t\t\tbreak AwaitDone\n\t\t\tcase <-timer.C:\n\t\t\t\tst.logEventTime(\"still_waiting_on_test\", ti.name)\n\t\t\tcase <-buildletsGone:\n\t\t\t\tset.cancelAll()\n\t\t\t\treturn nil, fmt.Errorf(\"dist test failed: all buildlets had network errors or timeouts, yet tests remain\")\n\t\t\t}\n\t\t}\n\n\t\tserialDuration += ti.execDuration\n\t\tif len(ti.output) > 0 {\n\t\t\tbanner, out := parseOutputAndBanner(ti.output)\n\t\t\tif banner != lastBanner {\n\t\t\t\tlastBanner = banner\n\t\t\t\tfmt.Fprintf(st, \"\\n##### %s\\n\", banner)\n\t\t\t}\n\t\t\tif inStaging {\n\t\t\t\tout = bytes.TrimSuffix(out, nl)\n\t\t\t\tst.Write(out)\n\t\t\t\tfmt.Fprintf(st, \" (shard %s; par=%d)\\n\", ti.shardIPPort, ti.groupSize)\n\t\t\t} else {\n\t\t\t\tst.Write(out)\n\t\t\t}\n\t\t}\n\n\t\tif ti.remoteErr != nil {\n\t\t\tset.cancelAll()\n\t\t\treturn fmt.Errorf(\"dist test failed: %s: %v\", ti.name, ti.remoteErr), nil\n\t\t}\n\t}\n\telapsed := time.Since(startTime)\n\tvar msg string\n\tif st.conf.NumTestHelpers > 0 {\n\t\tmsg = fmt.Sprintf(\"took %v; aggregate %v; saved %v\", elapsed, serialDuration, serialDuration-elapsed)\n\t} else {\n\t\tmsg = fmt.Sprintf(\"took %v\", elapsed)\n\t}\n\tst.logEventTime(\"tests_complete\", msg)\n\tfmt.Fprintf(st, \"\\nAll tests passed.\\n\")\n\treturn nil, nil\n}", "func SubtestAll(t *testing.T, tr mux.Multiplexer) {\n\ttmux.SubtestAll(t, tr)\n\n}", "func (f Factory) RunStoreTests(t *testing.T) {\n\tt.Run(\"Test store events\", f.TestStoreEvents)\n\tt.Run(\"Test store info\", f.TestGetInfo)\n\tt.Run(\"Test finding segments\", f.TestFindSegments)\n\tt.Run(\"Test getting map IDs\", f.TestGetMapIDs)\n\tt.Run(\"Test getting segments\", f.TestGetSegment)\n\tt.Run(\"Test creating links\", f.TestCreateLink)\n\tt.Run(\"Test batch implementation\", f.TestBatch)\n\tt.Run(\"Test evidence store\", f.TestEvidenceStore)\n}", "func (tg *testGroup) test(evalInterval time.Duration, groupOrderMap map[string]int, queryOpts promql.LazyLoaderOpts, ruleFiles ...string) []error {\n\t// Setup testing suite.\n\tsuite, err := promql.NewLazyLoader(nil, tg.seriesLoadingString(), queryOpts)\n\tif err != nil {\n\t\treturn []error{err}\n\t}\n\tdefer suite.Close()\n\tsuite.SubqueryInterval = evalInterval\n\n\t// Load the rule files.\n\topts := &rules.ManagerOptions{\n\t\tQueryFunc: rules.EngineQueryFunc(suite.QueryEngine(), suite.Storage()),\n\t\tAppendable: suite.Storage(),\n\t\tContext: context.Background(),\n\t\tNotifyFunc: func(ctx context.Context, expr string, alerts ...*rules.Alert) {},\n\t\tLogger: log.NewNopLogger(),\n\t}\n\tm := rules.NewManager(opts)\n\tgroupsMap, ers := m.LoadGroups(time.Duration(tg.Interval), tg.ExternalLabels, tg.ExternalURL, nil, ruleFiles...)\n\tif ers != nil {\n\t\treturn ers\n\t}\n\tgroups := orderedGroups(groupsMap, groupOrderMap)\n\n\t// Bounds for evaluating the rules.\n\tmint := time.Unix(0, 0).UTC()\n\tmaxt := mint.Add(tg.maxEvalTime())\n\n\t// Pre-processing some data for testing alerts.\n\t// All this preparation is so that we can test alerts as we evaluate the rules.\n\t// This avoids storing them in memory, as the number of evals might be high.\n\n\t// All the `eval_time` for which we have unit tests for alerts.\n\talertEvalTimesMap := map[model.Duration]struct{}{}\n\t// Map of all the eval_time+alertname combination present in the unit tests.\n\talertsInTest := make(map[model.Duration]map[string]struct{})\n\t// Map of all the unit tests for given eval_time.\n\talertTests := make(map[model.Duration][]alertTestCase)\n\tfor _, alert := range tg.AlertRuleTests {\n\t\tif alert.Alertname == \"\" {\n\t\t\tvar testGroupLog string\n\t\t\tif tg.TestGroupName != \"\" {\n\t\t\t\ttestGroupLog = fmt.Sprintf(\" (in TestGroup %s)\", tg.TestGroupName)\n\t\t\t}\n\t\t\treturn []error{fmt.Errorf(\"an item under alert_rule_test misses required attribute alertname at eval_time %v%s\", alert.EvalTime, testGroupLog)}\n\t\t}\n\t\talertEvalTimesMap[alert.EvalTime] = struct{}{}\n\n\t\tif _, ok := alertsInTest[alert.EvalTime]; !ok {\n\t\t\talertsInTest[alert.EvalTime] = make(map[string]struct{})\n\t\t}\n\t\talertsInTest[alert.EvalTime][alert.Alertname] = struct{}{}\n\n\t\talertTests[alert.EvalTime] = append(alertTests[alert.EvalTime], alert)\n\t}\n\talertEvalTimes := make([]model.Duration, 0, len(alertEvalTimesMap))\n\tfor k := range alertEvalTimesMap {\n\t\talertEvalTimes = append(alertEvalTimes, k)\n\t}\n\tsort.Slice(alertEvalTimes, func(i, j int) bool {\n\t\treturn alertEvalTimes[i] < alertEvalTimes[j]\n\t})\n\n\t// Current index in alertEvalTimes what we are looking at.\n\tcurr := 0\n\n\tfor _, g := range groups {\n\t\tfor _, r := range g.Rules() {\n\t\t\tif alertRule, ok := r.(*rules.AlertingRule); ok {\n\t\t\t\t// Mark alerting rules as restored, to ensure the ALERTS timeseries is\n\t\t\t\t// created when they run.\n\t\t\t\talertRule.SetRestored(true)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar errs []error\n\tfor ts := mint; ts.Before(maxt) || ts.Equal(maxt); ts = ts.Add(evalInterval) {\n\t\t// Collects the alerts asked for unit testing.\n\t\tvar evalErrs []error\n\t\tsuite.WithSamplesTill(ts, func(err error) {\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, g := range groups {\n\t\t\t\tg.Eval(suite.Context(), ts)\n\t\t\t\tfor _, r := range g.Rules() {\n\t\t\t\t\tif r.LastError() != nil {\n\t\t\t\t\t\tevalErrs = append(evalErrs, fmt.Errorf(\" rule: %s, time: %s, err: %v\",\n\t\t\t\t\t\t\tr.Name(), ts.Sub(time.Unix(0, 0).UTC()), r.LastError()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\terrs = append(errs, evalErrs...)\n\t\t// Only end testing at this point if errors occurred evaluating above,\n\t\t// rather than any test failures already collected in errs.\n\t\tif len(evalErrs) > 0 {\n\t\t\treturn errs\n\t\t}\n\n\t\tfor {\n\t\t\tif !(curr < len(alertEvalTimes) && ts.Sub(mint) <= time.Duration(alertEvalTimes[curr]) &&\n\t\t\t\ttime.Duration(alertEvalTimes[curr]) < ts.Add(evalInterval).Sub(mint)) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// We need to check alerts for this time.\n\t\t\t// If 'ts <= `eval_time=alertEvalTimes[curr]` < ts+evalInterval'\n\t\t\t// then we compare alerts with the Eval at `ts`.\n\t\t\tt := alertEvalTimes[curr]\n\n\t\t\tpresentAlerts := alertsInTest[t]\n\t\t\tgot := make(map[string]labelsAndAnnotations)\n\n\t\t\t// Same Alert name can be present in multiple groups.\n\t\t\t// Hence we collect them all to check against expected alerts.\n\t\t\tfor _, g := range groups {\n\t\t\t\tgrules := g.Rules()\n\t\t\t\tfor _, r := range grules {\n\t\t\t\t\tar, ok := r.(*rules.AlertingRule)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := presentAlerts[ar.Name()]; !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tvar alerts labelsAndAnnotations\n\t\t\t\t\tfor _, a := range ar.ActiveAlerts() {\n\t\t\t\t\t\tif a.State == rules.StateFiring {\n\t\t\t\t\t\t\talerts = append(alerts, labelAndAnnotation{\n\t\t\t\t\t\t\t\tLabels: a.Labels.Copy(),\n\t\t\t\t\t\t\t\tAnnotations: a.Annotations.Copy(),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tgot[ar.Name()] = append(got[ar.Name()], alerts...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, testcase := range alertTests[t] {\n\t\t\t\t// Checking alerts.\n\t\t\t\tgotAlerts := got[testcase.Alertname]\n\n\t\t\t\tvar expAlerts labelsAndAnnotations\n\t\t\t\tfor _, a := range testcase.ExpAlerts {\n\t\t\t\t\t// User gives only the labels from alerting rule, which doesn't\n\t\t\t\t\t// include this label (added by Prometheus during Eval).\n\t\t\t\t\tif a.ExpLabels == nil {\n\t\t\t\t\t\ta.ExpLabels = make(map[string]string)\n\t\t\t\t\t}\n\t\t\t\t\ta.ExpLabels[labels.AlertName] = testcase.Alertname\n\n\t\t\t\t\texpAlerts = append(expAlerts, labelAndAnnotation{\n\t\t\t\t\t\tLabels: labels.FromMap(a.ExpLabels),\n\t\t\t\t\t\tAnnotations: labels.FromMap(a.ExpAnnotations),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\tsort.Sort(gotAlerts)\n\t\t\t\tsort.Sort(expAlerts)\n\n\t\t\t\tif !reflect.DeepEqual(expAlerts, gotAlerts) {\n\t\t\t\t\tvar testName string\n\t\t\t\t\tif tg.TestGroupName != \"\" {\n\t\t\t\t\t\ttestName = fmt.Sprintf(\" name: %s,\\n\", tg.TestGroupName)\n\t\t\t\t\t}\n\t\t\t\t\texpString := indentLines(expAlerts.String(), \" \")\n\t\t\t\t\tgotString := indentLines(gotAlerts.String(), \" \")\n\t\t\t\t\terrs = append(errs, fmt.Errorf(\"%s alertname: %s, time: %s, \\n exp:%v, \\n got:%v\",\n\t\t\t\t\t\ttestName, testcase.Alertname, testcase.EvalTime.String(), expString, gotString))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurr++\n\t\t}\n\t}\n\n\t// Checking promql expressions.\nOuter:\n\tfor _, testCase := range tg.PromqlExprTests {\n\t\tgot, err := query(suite.Context(), testCase.Expr, mint.Add(time.Duration(testCase.EvalTime)),\n\t\t\tsuite.QueryEngine(), suite.Queryable())\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\" expr: %q, time: %s, err: %s\", testCase.Expr,\n\t\t\t\ttestCase.EvalTime.String(), err.Error()))\n\t\t\tcontinue\n\t\t}\n\n\t\tvar gotSamples []parsedSample\n\t\tfor _, s := range got {\n\t\t\tgotSamples = append(gotSamples, parsedSample{\n\t\t\t\tLabels: s.Metric.Copy(),\n\t\t\t\tValue: s.F,\n\t\t\t\tHistogram: promql.HistogramTestExpression(s.H),\n\t\t\t})\n\t\t}\n\n\t\tvar expSamples []parsedSample\n\t\tfor _, s := range testCase.ExpSamples {\n\t\t\tlb, err := parser.ParseMetric(s.Labels)\n\t\t\tvar hist *histogram.FloatHistogram\n\t\t\tif err == nil && s.Histogram != \"\" {\n\t\t\t\t_, values, parseErr := parser.ParseSeriesDesc(\"{} \" + s.Histogram)\n\t\t\t\tswitch {\n\t\t\t\tcase parseErr != nil:\n\t\t\t\t\terr = parseErr\n\t\t\t\tcase len(values) != 1:\n\t\t\t\t\terr = fmt.Errorf(\"expected 1 value, got %d\", len(values))\n\t\t\t\tcase values[0].Histogram == nil:\n\t\t\t\t\terr = fmt.Errorf(\"expected histogram, got %v\", values[0])\n\t\t\t\tdefault:\n\t\t\t\t\thist = values[0].Histogram\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"labels %q: %w\", s.Labels, err)\n\t\t\t\terrs = append(errs, fmt.Errorf(\" expr: %q, time: %s, err: %w\", testCase.Expr,\n\t\t\t\t\ttestCase.EvalTime.String(), err))\n\t\t\t\tcontinue Outer\n\t\t\t}\n\t\t\texpSamples = append(expSamples, parsedSample{\n\t\t\t\tLabels: lb,\n\t\t\t\tValue: s.Value,\n\t\t\t\tHistogram: promql.HistogramTestExpression(hist),\n\t\t\t})\n\t\t}\n\n\t\tsort.Slice(expSamples, func(i, j int) bool {\n\t\t\treturn labels.Compare(expSamples[i].Labels, expSamples[j].Labels) <= 0\n\t\t})\n\t\tsort.Slice(gotSamples, func(i, j int) bool {\n\t\t\treturn labels.Compare(gotSamples[i].Labels, gotSamples[j].Labels) <= 0\n\t\t})\n\t\tif !reflect.DeepEqual(expSamples, gotSamples) {\n\t\t\terrs = append(errs, fmt.Errorf(\" expr: %q, time: %s,\\n exp: %v\\n got: %v\", testCase.Expr,\n\t\t\t\ttestCase.EvalTime.String(), parsedSamplesString(expSamples), parsedSamplesString(gotSamples)))\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func RunTests(t *testing.T, svctest ServiceTest) {\n\tt.Run(\"NewSite\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestNewSite) })\n\tt.Run(\"DeleteSite\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestDeleteSite) })\n\tt.Run(\"WritePost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestWritePost) })\n\tt.Run(\"RemovePost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestRemovePost) })\n\tt.Run(\"ReadPost\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadPost) })\n\tt.Run(\"WriteConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestWriteConfig) })\n\tt.Run(\"ReadConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadConfig) })\n\tt.Run(\"UpdateAbout\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestUpdateAbout) })\n\tt.Run(\"ReadAbout\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestReadAbout) })\n\tt.Run(\"ChangeDefaultConfig\", func(t *testing.T) { clearEnvWrapper(t, svctest.TestChangeDefaultConfig) })\n}", "func initTestingEnv() {\n\t// Always update env variables for new test\n\tos.Setenv(\"SCUTTLE_LOGGING\", \"true\")\n\tconfig = getConfig()\n\n\t// Do not restart http servers for each test\n\tif testsInit {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Initiating test HTTP servers\")\n\n\t// Always 200 and live envoy state\n\tgoodServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"{\\\"state\\\": \\\"LIVE\\\"}\")) // Envoy live response\n\t}))\n\n\t// 503 for 5 requests, then 200 + live envoy state\n\tgoodEventuallyServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttimeSinceStarted := time.Now().Unix() - envoyDelayTimestamp\n\t\tif timeSinceStarted < envoyDelayMax {\n\t\t\tfmt.Println(\"Status Unavailable\")\n\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t\tw.Write([]byte(\"{\\\"state\\\": \\\"LIVE\\\"}\")) // Envoy live response\n\t}))\n\n\t// Always 503\n\tbadServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Println(\"Status Unavailable\")\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t}))\n\n\tgenericQuitServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Println(\"Status Ok\")\n\t\tw.WriteHeader(http.StatusOK)\n\t}))\n\n\ttestsInit = true\n}", "func TestTrackerSuite(t *testing.T) {\n\tsuite.Run(t, &TrackerSuite{})\n}", "func TestAllTask() {\n\tif noTestsFlag {\n\t\tlog.Println(\"*** Skipping: notests\")\n\t\treturn\n\t}\n\trunCmd(\"./pkg/pac/make.sh\")\n\trunCmd(\"go\", \"test\", \"-tags=\\\"net databases\\\"\",\n\t\t\"./cmd/...\", \"./pkg/...\")\n}", "func goplsMain() {\n\t// Panic on bugs (unlike the production gopls command),\n\t// except in tests that inject calls to bug.Report.\n\tif os.Getenv(\"TEST_GOPLS_BUG\") == \"\" {\n\t\tbug.PanicOnBugs = true\n\t}\n\n\ttool.Main(context.Background(), cmd.New(\"gopls\", \"\", nil, hooks.Options), os.Args[1:])\n}", "func TestLDS(t *testing.T) {\n\t_, tearDown := initLocalPilotTestEnv(t)\n\tdefer tearDown()\n\n\tt.Run(\"sidecar\", func(t *testing.T) {\n\t\tldsr, cancel, err := connectADS(util.MockPilotGrpcAddr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer cancel()\n\t\terr = sendLDSReq(sidecarID(app3Ip, \"app3\"), ldsr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tres, err := ldsr.Recv()\n\t\tif err != nil {\n\t\t\tt.Fatal(\"Failed to receive LDS\", err)\n\t\t\treturn\n\t\t}\n\n\t\tstrResponse, _ := model.ToJSONWithIndent(res, \" \")\n\t\t_ = ioutil.WriteFile(env.IstioOut+\"/ldsv2_sidecar.json\", []byte(strResponse), 0644)\n\n\t\tif len(res.Resources) == 0 {\n\t\t\tt.Fatal(\"No response\")\n\t\t}\n\t})\n\n\t// 'router' or 'gateway' type of listener\n\tt.Run(\"gateway\", func(t *testing.T) {\n\t\tldsr, cancel, err := connectADS(util.MockPilotGrpcAddr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer cancel()\n\t\terr = sendLDSReq(gatewayID(gatewayIP), ldsr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tres, err := ldsr.Recv()\n\t\tif err != nil {\n\t\t\tt.Fatal(\"Failed to receive LDS\", err)\n\t\t}\n\n\t\tstrResponse, _ := model.ToJSONWithIndent(res, \" \")\n\n\t\t_ = ioutil.WriteFile(env.IstioOut+\"/ldsv2_gateway.json\", []byte(strResponse), 0644)\n\n\t\tif len(res.Resources) == 0 {\n\t\t\tt.Fatal(\"No response\")\n\t\t}\n\t})\n\n\tt.Run(\"ingress\", func(t *testing.T) {\n\t\tldsr, cancel, err := connectADS(util.MockPilotGrpcAddr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer cancel()\n\n\t\terr = sendLDSReq(ingressID(ingressIP), ldsr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tres, err := ldsr.Recv()\n\t\tif err != nil {\n\t\t\tt.Fatal(\"Failed to receive LDS\", err)\n\t\t\treturn\n\t\t}\n\n\t\tstrResponse, _ := model.ToJSONWithIndent(res, \" \")\n\n\t\t_ = ioutil.WriteFile(env.IstioOut+\"/ads_lds_ingress.json\", []byte(strResponse), 0644)\n\n\t\tif len(res.Resources) == 0 {\n\t\t\tt.Fatal(\"No response\")\n\t\t}\n\t})\n\t// TODO: compare with some golden once it's stable\n\t// check that each mocked service and destination rule has a corresponding resource\n\n\t// TODO: dynamic checks ( see EDS )\n}", "func (svrs Servers) StartTest() {\n\tfor i, s := range svrs {\n\t\ts.Show()\n\t\tlatency := pingTest(s.URL)\n\t\tdlSpeed := downloadTest(s.URL, latency)\n\t\tulSpeed := uploadTest(s.URL, latency)\n\t\tsvrs[i].DLSpeed = dlSpeed\n\t\tsvrs[i].ULSpeed = ulSpeed\n\t\tsvrs[i].Ping = latency\n\t}\n}", "func (suite *SmsTests) SetUpSuite(c *C) {\n}", "func (sfs *SuiteFS) RunTests(t *testing.T, userName string, stFuncs ...SuiteTestFunc) {\n\tvfs := sfs.vfsSetup\n\n\t_, _ = sfs.User(t, userName)\n\tdefer sfs.User(t, sfs.initUser.Name())\n\n\tfor _, stFunc := range stFuncs {\n\t\tfuncName := runtime.FuncForPC(reflect.ValueOf(stFunc).Pointer()).Name()\n\t\tfuncName = funcName[strings.LastIndex(funcName, \".\")+1 : strings.LastIndex(funcName, \"-\")]\n\t\ttestDir := vfs.Join(sfs.rootDir, funcName)\n\n\t\tsfs.CreateTestDir(t, testDir)\n\n\t\tt.Run(funcName, func(t *testing.T) {\n\t\t\tstFunc(t, testDir)\n\t\t})\n\n\t\tsfs.RemoveTestDir(t, testDir)\n\t}\n}", "func TestSuite(t *testing.T) {\n\tsuite.Run(t, new(ClientTestSuite))\n\tsuite.Run(t, new(ParserTestSuite))\n}", "func TestServiceLookupSuite(t *testing.T) {\n\tsuite.Run(t, new(ServiceLookupTestSuite))\n}", "func RunSuite(s *test.Suite, context Context) ([]*Result, error) {\n results := make([]*Result, 0)\n c := context.Subcontext(make(map[string]interface{}))\n \n for _, e := range context.Gendoc {\n err := e.Prefix()\n if err != nil {\n return nil, err\n }\n }\n \n for _, e := range s.Cases {\n r, err := RunTest(e, c)\n if err != nil {\n return nil, err\n }\n results = append(results, r)\n }\n \n for _, e := range context.Gendoc {\n err := e.Suffix()\n if err != nil {\n return nil, err\n }\n }\n \n return results, nil\n}", "func TestHealthCheckTestSuite(t *testing.T) {\n\tsuite.Run(t, new(HealthCheckTestSuite))\n}", "func TestMain(m *testing.M) {\n\tprintln(\"do stuff before all tests\")\n\tm.Run()\n\tprintln(\"do stuff after all tests\")\n}", "func TestLegacyTestSuite(t *testing.T) {\n\tsuite.Run(t, new(LegacyTestSuite))\n}", "func RunSubtests(ctx *Context) {\n\tfor name, fn := range tests {\n\t\tctx.Run(name, fn)\n\t}\n}", "func main() {\n\ttest_plain_background()\n\ttest_cloud()\n\ttest_enemy()\n\ttest_move_background()\n\ttest_display_score()\n}", "func (pg *PortalIntegrationTestSuite) SetupSuite() {\n\tfmt.Println(\"Setting up the suite...\")\n\t// Kovan env\n\tpg.IncKBNTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000082\"\n\tpg.IncSALTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000081\"\n\tpg.IncOMGTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000072\"\n\tpg.IncSNTTokenIDStr = \"0000000000000000000000000000000000000000000000000000000000000071\"\n\tpg.OMGAddressStr = \"0xdB7ec4E4784118D9733710e46F7C83fE7889596a\" // kovan\n\tpg.SNTAddressStr = \"0x4c99B04682fbF9020Fcb31677F8D8d66832d3322\" // kovan\n\tpg.DepositingEther = float64(5)\n\tpg.ETHPrivKeyStr = \"1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61\"\n\tpg.PortalAdminKey = \"B8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31\"\n\tpg.ETHHost = \"http://localhost:8545\"\n\n\tvar err error\n\tfmt.Println(\"Pulling image if not exist, please wait...\")\n\t// remove container if already running\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f portalv3\").Output()\n\texec.Command(\"/bin/sh\", \"-c\", \"docker rm -f incognito\").Output()\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", \"docker run -d -p 8545:8545 --name portalv3 trufflesuite/ganache-cli --account=\\\"0x1ABA488300A9D7297A315D127837BE4219107C62C61966ECDF7A75431D75CC61,10000000000000000000000000000000000,0xB8DB29A7A43FB88AD520F762C5FDF6F1B0155637FA1E5CB2C796AFE9E5C04E31,10000000000000000000000000000000000\\\"\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\ttime.Sleep(10 * time.Second)\n\n\tETHPrivKey, ETHClient, err := ethInstance(pg.ETHPrivKeyStr, pg.ETHHost)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.ETHClient = ETHClient\n\tpg.ETHPrivKey = ETHPrivKey\n\tpg.auth = bind.NewKeyedTransactor(ETHPrivKey)\n\n\t// admin key\n\tprivKey, err := crypto.HexToECDSA(pg.PortalAdminKey)\n\trequire.Equal(pg.T(), nil, err)\n\tadmin := bind.NewKeyedTransactor(privKey)\n\n\t//pg.Portalv3 = common.HexToAddress(\"0x8c13AFB7815f10A8333955854E6ec7503eD841B7\")\n\t//pg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\t//incAddr := common.HexToAddress(\"0x2fe0423B148739CD9D0E49e07b5ca00d388A15ac\")\n\t//pg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\t//require.Equal(pg.T(), nil, err)\n\n\tc := getFixedCommittee()\n\tincAddr, _, _, err := incognitoproxy.DeployIncognitoproxy(pg.auth, pg.ETHClient, admin.From, c.beacons)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"Proxy address: %s\\n\", incAddr.Hex())\n\tportalv3Logic, _, _, err := portalv3.DeployPortalv3(pg.auth, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"portalv3 address: %s\\n\", portalv3Logic.Hex())\n\n\tportalv3ABI, _ := abi.JSON(strings.NewReader(portalv3.Portalv3ABI))\n\tinput, _ := portalv3ABI.Pack(\"initialize\")\n\n\t//PortalV3\n\tpg.Portalv3, _, _, err = delegator.DeployDelegator(pg.auth, pg.ETHClient, portalv3Logic, admin.From, incAddr, input)\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"delegator address: %s\\n\", pg.Portalv3.Hex())\n\tpg.portalV3Inst, err = portalv3.NewPortalv3(pg.Portalv3, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\tpg.incProxy, err = incognitoproxy.NewIncognitoproxy(incAddr, pg.ETHClient)\n\trequire.Equal(pg.T(), nil, err)\n\n\t// 0x54d28562271De782B261807a01d1D2fb97417912\n\tpg.USDTAddress, _, _, err = usdt.DeployUsdt(pg.auth, pg.ETHClient, big.NewInt(100000000000), \"Tether\", \"USDT\", big.NewInt(6))\n\trequire.Equal(pg.T(), nil, err)\n\tfmt.Printf(\"usdt address: %s\\n\", pg.USDTAddress.Hex())\n\n\t//get portalv3 ip\n\tipAddress, err := exec.Command(\"/bin/sh\", \"-c\", \"docker inspect -f \\\"{{ .NetworkSettings.IPAddress }}\\\" portalv3\").Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\t// run incognito chaind\n\tincogitoWithArgument := fmt.Sprintf(\"docker run -d -p 9334:9334 -p 9338:9338 --name incognito -e GETH_NAME=%v -e PORTAL_CONTRACT=%v incognito\", string(ipAddress), pg.Portalv3.Hex())\n\tincogitoWithArgument = strings.Replace(incogitoWithArgument, \"\\n\", \"\", -1)\n\t_, err = exec.Command(\"/bin/sh\", \"-c\", incogitoWithArgument).Output()\n\trequire.Equal(pg.T(), nil, err)\n\n\tfor {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif checkRepsonse(pg.IncBridgeHost) {\n\t\t\tbreak\n\t\t}\n\t}\n\ttime.Sleep(40 * time.Second)\n}", "func TestRun(t *testing.T) {\n\tsuite.Run(t, new(CategoryTestSuite))\n\tsuite.Run(t, new(ProductTestSuite))\n}", "func TestMain(m *testing.M) {\n\tframework.Run(\"pilot_test\", m)\n}", "func (Test) All() error {\n\tprintHeader(\"PKG TESTS (ALL)\")\n\terr := sh.RunV(\"gotestsum\", \"./pkg/...\")\n\treturn err\n}", "func (sIdm *SuiteIdm) TestAll(t *testing.T) {\n\tsIdm.TestCurrentUser(t)\n\tsIdm.TestGroupAddDel(t)\n\tsIdm.TestUserAddDel(t)\n\tsIdm.TestLookup(t)\n\tsIdm.TestUser(t)\n\tsIdm.TestUserDenied(t)\n\tsIdm.TestPermDenied(t)\n}", "func TestQslSearch(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping TestQSLSearch in short mode\")\n\t}\n\ttestURL1 := TestBaseURL + \"/v1/qsl/node[@name=\\\"node01\\\"]{*}\"\n\ttestURL2 := TestBaseURL + \"/v1/qsl/node[@name=\\\"node01\\\"]{@labels}\"\n\n\ttests := []TestStruct{\n\t\t{\"TestSearchNode01All\", testURL1, \"\", 200, \"\", 0},\n\t\t{\"TestSearchNode01@labels\", testURL2, \"\", 200, \"\", 0},\n\t}\n\n\tfor i, testCase := range tests {\n\t\tt.Run(testCase.testCaseName, func(t *testing.T) {\n\t\t\tresCode, resBody, _ := QslSearch(t, testCase.testURL)\n\t\t\ttests[i].observedStatusCode = resCode\n\t\t\ttests[i].responseBody = string(resBody)\n\t\t})\n\t}\n\tDisplayTestCaseResults(\"TestQslSearch\", tests, t, \"uid\")\n}", "func NewTestSuite(fpath string, payloads []TestPayload) TestSuite {\n\tts := TestSuite{\n\t\tDir: strings.Title(filepath.Base(filepath.Dir(fpath))),\n\t\tFilepath: fpath,\n\t}\n\n\tif strings.Contains(fpath, \"x-pack\") {\n\t\tts.Type = \"xpack\"\n\t}\n\tif ts.Type == \"\" {\n\t\tts.Type = \"core\"\n\t}\n\n\tfor _, payload := range payloads {\n\t\tsec_keys := utils.MapKeys(payload.Payload)\n\t\tswitch {\n\t\tcase len(sec_keys) > 0 && strings.Contains(strings.Join(sec_keys, \",\"), \"setup\") || strings.Contains(strings.Join(sec_keys, \",\"), \"teardown\"):\n\t\t\tfor k, v := range payload.Payload.(map[interface{}]interface{}) {\n\t\t\t\tswitch k {\n\t\t\t\tcase \"setup\":\n\t\t\t\t\tfor _, vv := range v.([]interface{}) {\n\t\t\t\t\t\tfor k, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tif k == \"do\" {\n\t\t\t\t\t\t\t\tts.Setup = append(ts.Setup, NewAction(vvv))\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\tcase \"teardown\":\n\t\t\t\t\tfor _, vv := range v.([]interface{}) {\n\t\t\t\t\t\tfor k, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tif k == \"do\" {\n\t\t\t\t\t\t\t\tts.Teardown = append(ts.Teardown, NewAction(vvv))\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\tdefault:\n\t\t\tfor k, v := range payload.Payload.(map[interface{}]interface{}) {\n\t\t\t\tvar t Test\n\t\t\t\tvar steps []Step\n\n\t\t\t\tfor _, vv := range v.([]interface{}) {\n\t\t\t\t\tswitch utils.MapKeys(vv)[0] {\n\t\t\t\t\tcase \"skip\":\n\t\t\t\t\t\tvar (\n\t\t\t\t\t\t\tok bool\n\t\t\t\t\t\t\tskip_v string\n\t\t\t\t\t\t\tskip_r string\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tskip := vv.(map[interface{}]interface{})[\"skip\"]\n\n\t\t\t\t\t\tif skip_v, ok = skip.(map[interface{}]interface{})[\"version\"].(string); ok {\n\t\t\t\t\t\t\tif skip_rr, ok := skip.(map[interface{}]interface{})[\"reason\"].(string); ok {\n\t\t\t\t\t\t\t\tskip_r = skip_rr\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif skip_v == \"all\" {\n\t\t\t\t\t\t\t\tt.Skip = true\n\t\t\t\t\t\t\t\tt.SkipInfo = \"Skipping all versions\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ts.SkipEsVersion(skip_v) {\n\t\t\t\t\t\t\t\t// fmt.Printf(\"Skip: %q, EsVersion: %s, Skip: %v, Reason: %s\\n\", skip_v, EsVersion, ts.SkipEsVersion(skip_v), skip_r)\n\t\t\t\t\t\t\t\tt.Skip = true\n\t\t\t\t\t\t\t\tt.SkipInfo = skip_r\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"setup\":\n\t\t\t\t\t\tfor _, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tfor _, vvvv := range vvv.([]interface{}) {\n\t\t\t\t\t\t\t\tt.Setup = append(t.Setup, NewAction(vvvv.(map[interface{}]interface{})[\"do\"]))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"teardown\":\n\t\t\t\t\t\tfor _, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tfor _, vvvv := range vvv.([]interface{}) {\n\t\t\t\t\t\t\t\tt.Teardown = append(t.Teardown, NewAction(vvvv.(map[interface{}]interface{})[\"do\"]))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"set\":\n\t\t\t\t\t\tfor _, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tsteps = append(steps, NewStash(vvv))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"transform_and_set\":\n\t\t\t\t\t\tfor _, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\t// NOTE: `set_and_transform` has flipped ordering of key and value, compared to `set`\n\t\t\t\t\t\t\tkey := utils.MapValues(vvv)[0]\n\t\t\t\t\t\t\tval := utils.MapKeys(vvv)[0]\n\t\t\t\t\t\t\tpayload := make(map[interface{}]interface{})\n\t\t\t\t\t\t\tpayload[key] = val\n\t\t\t\t\t\t\t// fmt.Println(payload)\n\t\t\t\t\t\t\tsteps = append(steps, NewStash(payload))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"do\":\n\t\t\t\t\t\tfor _, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tsteps = append(steps, NewAction(vvv))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"is_true\", \"is_false\", \"match\", \"lt\", \"gt\", \"lte\", \"gte\":\n\t\t\t\t\t\tfor kkk, vvv := range vv.(map[interface{}]interface{}) {\n\t\t\t\t\t\t\tsteps = append(steps, NewAssertion(kkk.(string), vvv))\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// TODO: \"length\" operator\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !ts.Skip {\n\t\t\t\t\tt.Name = strings.ReplaceAll(k.(string), `\"`, `'`)\n\t\t\t\t\tt.Filepath = payload.Filepath\n\t\t\t\t\tt.OrigName = k.(string)\n\t\t\t\t\tt.Steps = steps\n\n\t\t\t\t\tts.Tests = append(ts.Tests, t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ts\n}", "func TestServiceSuite(t *testing.T) {\n\tsuite.Run(t, new(TestSuite))\n}", "func main() {\n\tfmt.Println(\"\\nTests from within scratch container:\")\n\terrors := testTZ()\n\terrors += testTLS()\n\tos.Exit(errors)\n}", "func TestCLI(t *testing.T) {\n\t// parse configuration file 'solar-conf.yaml' in local directory\n\t_, err := util.ReadConfiguration()\n\tif err != nil {\n\t\tfmt.Println(\"unable to read the configuration file\")\n\t\tfmt.Println(err)\n\t}\n\n\t// initialise command line options\n\tutil.ParseCommandLineOptions()\n\n\t// create model\n\tm := model.GetModel()\n \n\t// start the main event loop\n\tengine.StartDispatcher(m)\n\n\t// get the command line interface\n\tshell := cli.Shell(m)\n\n\t// load commands from a file\n\tcmds, err := LoadCommands()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tfmt.Println(\"Executing tests:\")\n\tfmt.Println(\"Nr. Command\")\n\tfmt.Println(\"------------------------------------------------------------\")\n\tfor index, cmd := range cmds {\n\t\t// skip empty command lines\n\t\tif cmd[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// construct command line string\n\t\tcmdline := strings.Join(cmd, \" \")\n\n\t\t// log the command line\n\t\tfmt.Printf(\"%03d %s\\n\", index, cmdline)\n\n\t\t// process\n\t\terr = shell.Process(cmd...)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Command failed: %s\\n%s\", cmdline, err)\n\t\t}\n\t}\n}", "func CleanupSuite() {\n\t// Run on all Ginkgo nodes\n}", "func TestTools(t *testing.T) { TestingT(t) }", "func runTest(waf *engine.Waf, profile testProfile) (bool, int, error){\n\tpassed := 0\n\tfor _, test := range profile.Tests{\n\t\ttn := time.Now().UnixNano()\n\t\tpass := true\n\t\tfor _, stage := range test.Stages{\n\t\t\ttx := waf.NewTransaction()\n\t\t\tif stage.Stage.Input.EncodedRequest != \"\"{\n\t\t\t\tsDec, _ := b64.StdEncoding.DecodeString(stage.Stage.Input.EncodedRequest)\n\t\t\t\tstage.Stage.Input.RawRequest = string(sDec)\n\t\t\t}\n\t\t\tif stage.Stage.Input.RawRequest != \"\"{\n\t\t\t\treq, err := requestFromString(stage.Stage.Input.RawRequest)\n\t\t\t\tif err != nil{\n\t\t\t\t\tfmt.Println(\"Error parsing HTTP request:\")\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn false, 0, err\n\t\t\t\t}\n\t\t\t\trequestToTx(req, tx)\n\t\t\t}\n\t\t\t//Apply tx data\n\t\t\tif len(stage.Stage.Input.Headers) > 0{\n\t\t\t\tfor k, v := range stage.Stage.Input.Headers{\n\t\t\t\t\ttx.AddRequestHeader(k, v)\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\tmethod := \"GET\"\n\t\t\tif stage.Stage.Input.Method != \"\"{\n\t\t\t\tmethod = stage.Stage.Input.Method\n\t\t\t\ttx.SetRequestMethod(method)\n\t\t\t}\n\n\t\t\t//Request Line\n\t\t\thttpv := \"HTTP/1.1\"\n\t\t\tif stage.Stage.Input.Version != \"\"{\n\t\t\t\thttpv = stage.Stage.Input.Version\n\t\t\t}\n\n\t\t\tpath := \"/\"\n\t\t\tif stage.Stage.Input.Uri != \"\"{\n\t\t\t\tu, err := url.Parse(stage.Stage.Input.Uri)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif debug{\n\t\t\t\t\t\tfmt.Println(\"Invalid URL: \" + stage.Stage.Input.Uri)\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\ttx.SetUrl(u)\n\t\t\t\t\ttx.AddGetArgsFromUrl(u)\n\t\t\t\t\tpath = stage.Stage.Input.Uri//or unescaped?\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\ttx.SetRequestLine(method, httpv, path)\n\n\t\t\t//PHASE 1\n\t\t\ttx.ExecutePhase(1)\n\n\t\t\t// POST DATA\n\t\t\tif stage.Stage.Input.Data != \"\"{\n\t\t\t\tdata := \"\"\n\t\t\t\tv := reflect.ValueOf(stage.Stage.Input.Data)\n\t\t\t\tswitch v.Kind() {\n\t\t\t\tcase reflect.Slice:\n\t\t\t for i := 0; i < v.Len(); i++ {\n\t\t\t data += fmt.Sprintf(\"%s\\r\\n\", v.Index(i))\n\t\t\t }\n\t\t\t data += \"\\r\\n\"\n\t\t\t\tcase reflect.String:\n\t\t\t\t\tdata = stage.Stage.Input.Data.(string)\n\t\t\t\t}\n\t\t\t\trh := tx.GetCollection(\"request_headers\")\n\t\t\t\tct := rh.GetSimple(\"content-type\")\n\t\t\t\tctt := \"\"\n\t\t\t\tif len(ct) == 1{\n\t\t\t\t\tctt = ct[0]\n\t\t\t\t}\n\t\t\t\tmediaType, params, _ := mime.ParseMediaType(ctt)\n\t\t\t\tif method == \"GET\" || method == \"HEAD\" || method == \"OPTIONS\" {\n\t\t\t\t\tlength := strconv.Itoa(len(data))\n\t\t\t\t\tif len(rh.GetSimple(\"content-length\")) == 0{\n\t\t\t\t\t\trh.Set(\"content-length\", []string{length})\n\t\t\t\t\t}\n\t\t\t\t\t// Just for testing\n\t\t\t\t\ttx.GetCollection(\"request_body\").Set(\"\", []string{data})\n\t\t\t\t}else if strings.HasPrefix(mediaType, \"multipart/\") {\n\t\t\t\t\tparseMultipart(data, params[\"boundary\"], tx)\n\t\t\t\t}else {\n\t\t\t\t\ttx.SetRequestBody(data, int64(len(data)), mediaType)\n\t\t\t\t\tu, err := url.ParseQuery(data)\n\t\t\t\t\tif err == nil{\n\t\t\t\t\t\ttx.SetArgsPost(u)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor i := 2; i <= 5; i++{\n\t\t\t\ttx.ExecutePhase(i)\n\t\t\t}\n\t\t\tlog := \"\"\n\t\t\tfor _, mr := range tx.MatchedRules{\n\t\t\t\tlog += fmt.Sprintf(\" [id \\\"%d\\\"]\", mr.Id)\n\t\t\t}\n\t\t\t//now we evaluate tests\n\t\t\tif stage.Stage.Output.LogContains != \"\"{\n\t\t\t\tif !strings.Contains(log, stage.Stage.Output.LogContains){\n\t\t\t\t\tpass = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif stage.Stage.Output.NoLogContains != \"\"{\n\t\t\t\tif strings.Contains(log, stage.Stage.Output.NoLogContains){\n\t\t\t\t\tpass = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresult := \"\\033[31mFailed\"\n\t\tif pass{\n\t\t\tresult = \"\\033[32mPassed\"\n\t\t\tpassed++\n\t\t\tif failonly{\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"%s: %s\\033[0m (%dus)\\n\", test.Title, result, time.Now().UnixNano()-tn)\n\t}\n\treturn len(profile.Tests) == passed, 0, nil\n}", "func listTests(ctx context.Context, cfg *config.Config,\n\tdrv *driver.Driver,\n\tdutInfos map[string]*protocol.DUTInfo) ([]*resultsjson.Result, error) {\n\tCompanionFeatures := make(map[string]*frameworkprotocol.DUTFeatures)\n\tfor role, dutInfo := range dutInfos {\n\t\tif role != \"\" {\n\t\t\tCompanionFeatures[role] = dutInfo.GetFeatures()\n\t\t}\n\t}\n\n\tvar dutFeature *frameworkprotocol.DUTFeatures\n\tif _, ok := dutInfos[\"\"]; ok {\n\t\tdutFeature = dutInfos[\"\"].GetFeatures()\n\t}\n\n\ttests, err := drv.ListMatchedTests(ctx, cfg.Features(dutFeature, CompanionFeatures))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar shard *sharding.Shard\n\tif cfg.ShardMethod() == \"hash\" {\n\t\tshard = sharding.ComputeHash(tests, cfg.ShardIndex(), cfg.TotalShards())\n\t} else {\n\t\tshard = sharding.ComputeAlpha(tests, cfg.ShardIndex(), cfg.TotalShards())\n\t}\n\n\tvar testsToPrint []*driver.BundleEntity\n\tif cfg.ExcludeSkipped() {\n\t\ttestsToPrint, _ = removeSkippedTestsFromBundle(shard.Included)\n\t} else {\n\t\ttestsToPrint = shard.Included\n\t}\n\n\t// Convert driver.BundleEntity to resultsjson.Result.\n\tresults := make([]*resultsjson.Result, len(testsToPrint))\n\tfor i, re := range testsToPrint {\n\t\ttest, err := resultsjson.NewTest(re.Resolved.GetEntity())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults[i] = &resultsjson.Result{\n\t\t\tTest: *test,\n\t\t\tSkipReason: strings.Join(re.Resolved.GetSkip().GetReasons(), \", \"),\n\t\t}\n\t}\n\treturn results, nil\n}", "func TestAll(t *testing.T) {\n\n\t// remove anything that might have been leftover from failed tests\n\tDeleteApi(TEST_API_AXLE_SERVER, TEST_API_NAME)\n\tDeleteKey(TEST_API_AXLE_SERVER, TEST_KEY_NAME)\n\tDeleteKeyRing(TEST_API_AXLE_SERVER, TEST_KEYRING_NAME)\n\n\ttestPing(t)\n\ttestInfo(t)\n\ttestGetNonExistentApi(t)\n\ttestCreateApi(t)\n\tapi := testGetApi(t)\n\ttestUpdateApi(t, api)\n\ttestApiStats(t, api)\n\tk := testNewKey(t)\n\ttestGetKey(t)\n\ttestUpdateKey(t, k)\n\ttestLinkKey(t, api)\n\ttestApiKeyCharts(t, api)\n\ttestApiKeys(t)\n\ttestApis(t)\n\ttestApisCharts(t)\n\ttestKeyApiCharts(t)\n\ttestKeyApis(t, k)\n\ttestKeyStats(t, k)\n\ttestKeysCharts(t)\n\ttestKeys(t)\n\tkr := testNewKeyRing(t)\n\ttestGetKeyRing(t)\n\ttestUpdateKeyRing(t, kr)\n\ttestKeyRingLinkKey(t)\n\ttestKeyRingKeys(t, kr)\n\ttestKeyRingStats(t, kr)\n\ttestKeyRings(t)\n\ttestKeyRingUnlinkKey(t)\n\ttestKeyRingsEmpty(t)\n\ttestUnlinkKey(t)\n\ttestDeleteKey(t)\n\ttestDeleteKeyRing(t)\n\ttestDeleteApi(t, api)\n}", "func (c *Context) TESTL(ir, emr operand.Op) {\n\tc.addinstruction(x86.TESTL(ir, emr))\n}", "func (o Scorecard) RunTests(ctx context.Context) (testOutput v1alpha3.Test, err error) {\n\n\terr = o.TestRunner.Initialize(ctx)\n\tif err != nil {\n\t\treturn testOutput, err\n\t}\n\n\ttests := o.selectTests()\n\tif len(tests) == 0 {\n\t\treturn testOutput, nil\n\t}\n\n\tfor _, test := range tests {\n\t\tresult, err := o.TestRunner.RunTest(ctx, test)\n\t\tif err != nil {\n\t\t\tresult = convertErrorToStatus(test.Name, err)\n\t\t}\n\t\ttestOutput.Status.Results = append(testOutput.Status.Results, result.Results...)\n\t}\n\n\tif !o.SkipCleanup {\n\t\terr = o.TestRunner.Cleanup(ctx)\n\t\tif err != nil {\n\t\t\treturn testOutput, err\n\t\t}\n\t}\n\treturn testOutput, nil\n}", "func TestMain(t *testing.T) { TestingT(t) }", "func main() {\n\tfmt.Println(\"Tests from within scratch container:\")\n\terrors := testTZ()\n\terrors += testTLS()\n\tos.Exit(errors)\n}", "func TestMain(t *testing.T) {\n}", "func (st *buildStatus) runTestsOnBuildlet(bc buildlet.Client, tis []*testItem, goroot, gopath string) {\n\tnames, rawNames := make([]string, len(tis)), make([]string, len(tis))\n\tfor i, ti := range tis {\n\t\tnames[i], rawNames[i] = ti.name.Old, ti.name.Raw\n\t\tif i > 0 && (!strings.HasPrefix(ti.name.Old, \"go_test:\") || !strings.HasPrefix(names[0], \"go_test:\")) {\n\t\t\tpanic(\"only go_test:* tests may be merged\")\n\t\t}\n\t}\n\tvar spanName string\n\tvar detail string\n\tif len(names) == 1 {\n\t\tspanName = \"run_test:\" + names[0]\n\t\tdetail = bc.Name()\n\t} else {\n\t\tspanName = \"run_tests_multi\"\n\t\tdetail = fmt.Sprintf(\"%s: %v\", bc.Name(), names)\n\t}\n\tsp := st.CreateSpan(spanName, detail)\n\n\targs := []string{\"tool\", \"dist\", \"test\", \"--no-rebuild\", \"--banner=\" + banner}\n\tif st.conf.IsRace() {\n\t\targs = append(args, \"--race\")\n\t}\n\tif st.conf.CompileOnly {\n\t\targs = append(args, \"--compile-only\")\n\t}\n\tif st.useKeepGoingFlag() {\n\t\targs = append(args, \"-k\")\n\t}\n\targs = append(args, rawNames...)\n\tvar buf bytes.Buffer\n\tt0 := time.Now()\n\ttimeout := st.conf.DistTestsExecTimeout(names)\n\n\tctx, cancel := context.WithTimeout(st.ctx, timeout)\n\tdefer cancel()\n\n\tenv := append(st.conf.Env(),\n\t\t\"GOROOT=\"+goroot,\n\t\t\"GOPATH=\"+gopath,\n\t)\n\tenv = append(env, st.modulesEnv()...)\n\n\tremoteErr, err := bc.Exec(ctx, \"./go/bin/go\", buildlet.ExecOpts{\n\t\t// We set Dir to \".\" instead of the default (\"go/bin\") so when the dist tests\n\t\t// try to run os/exec.Command(\"go\", \"test\", ...), the LookPath of \"go\" doesn't\n\t\t// return \"./go.exe\" (which exists in the current directory: \"go/bin\") and then\n\t\t// fail when dist tries to run the binary in dir \"$GOROOT/src\", since\n\t\t// \"$GOROOT/src\" + \"./go.exe\" doesn't exist. Perhaps LookPath should return\n\t\t// an absolute path.\n\t\tDir: \".\",\n\t\tOutput: &buf, // see \"maybe stream lines\" TODO below\n\t\tExtraEnv: env,\n\t\tPath: []string{st.conf.FilePathJoin(\"$WORKDIR\", \"go\", \"bin\"), \"$PATH\"},\n\t\tArgs: args,\n\t})\n\texecDuration := time.Since(t0)\n\tsp.Done(err)\n\tif err != nil {\n\t\tbc.MarkBroken() // prevents reuse\n\t\tfor _, ti := range tis {\n\t\t\tti.numFail++\n\t\t\tst.logf(\"Execution error running %s on %s: %v (numFails = %d)\", ti.name, bc, err, ti.numFail)\n\t\t\tif err == buildlet.ErrTimeout {\n\t\t\t\tti.failf(\"Test %q ran over %v limit (%v); saw output:\\n%s\", ti.name, timeout, execDuration, buf.Bytes())\n\t\t\t} else if ti.numFail >= maxTestExecErrors {\n\t\t\t\tti.failf(\"Failed to schedule %q test after %d tries.\\n\", ti.name, maxTestExecErrors)\n\t\t\t} else {\n\t\t\t\tti.retry()\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tout := buf.Bytes()\n\tout = bytes.Replace(out, []byte(\"\\nALL TESTS PASSED (some were excluded)\\n\"), nil, 1)\n\tout = bytes.Replace(out, []byte(\"\\nALL TESTS PASSED\\n\"), nil, 1)\n\n\tfor _, ti := range tis {\n\t\tti.output = out\n\t\tti.remoteErr = remoteErr\n\t\tti.execDuration = execDuration\n\t\tti.groupSize = len(tis)\n\t\tti.shardIPPort = bc.IPPort()\n\t\tclose(ti.done)\n\n\t\t// After the first one, make the rest succeed with no output.\n\t\t// TODO: maybe stream lines (set Output to a line-reading\n\t\t// Writer instead of &buf). for now we just wait for them in\n\t\t// ~10 second batches. Doesn't look as smooth on the output,\n\t\t// though.\n\t\tout = nil\n\t\tremoteErr = nil\n\t\texecDuration = 0\n\t}\n}", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func Test(t *testing.T) { check.TestingT(t) }", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestMain(m *testing.M) {\n\tfstest.TestMain(m)\n}", "func TestPackages() error {\n\treturn devtools.TestPackages()\n}", "func TestServices(t *testing.T) { check.TestingT(t) }", "func TestMainTestSuite(t *testing.T) {\n\tsuite.Run(t, new(MainTestSuite))\n}", "func (suite *AddCommandTestSuite) TestExecuteWithMultipleURLs() {\n\n}", "func RunTests(t *testing.T, tests map[string]SubTest) {\n\tfor name, test := range tests {\n\t\tdomainKeeper, ctx, mocks := NewTestKeeper(t, true)\n\t\t// set default mock.Supply not to fail\n\t\tmocks.Supply.SetSendCoinsFromAccountToModule(func(ctx types.Context, addr types.AccAddress, moduleName string, coins types.Coins) error {\n\t\t\treturn nil\n\t\t})\n\t\t// set default fees\n\t\tsetFees := domainKeeper.ConfigurationKeeper.(ConfigurationSetter).SetFees\n\t\tfees := configuration.NewFees()\n\t\tfees.SetDefaults(\"testcoin\")\n\t\tsetFees(ctx, fees)\n\t\t// run sub SubTest\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// run before SubTest\n\t\t\tif test.BeforeTest != nil {\n\t\t\t\tif test.BeforeTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.BeforeTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.BeforeTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\n\t\t\tif test.TestBlockTime != 0 {\n\t\t\t\tt := time.Unix(test.TestBlockTime, 0)\n\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t}\n\t\t\t// run actual SubTest\n\t\t\ttest.Test(t, domainKeeper, ctx, mocks)\n\n\t\t\t// run after SubTest\n\t\t\tif test.AfterTest != nil {\n\t\t\t\tif test.AfterTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.AfterTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.AfterTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\t\t})\n\t}\n}", "func Test(t *testing.T, driver, dsn string, testSuites []string, rw bool) {\n\tclients, err := ConnectClients(t, driver, dsn, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to connect to %s (%s driver): %s\\n\", dsn, driver, err)\n\t}\n\tclients.RW = rw\n\ttests := make(map[string]struct{})\n\tfor _, test := range testSuites {\n\t\ttests[test] = struct{}{}\n\t}\n\tif _, ok := tests[SuiteAuto]; ok {\n\t\tt.Log(\"Detecting target service compatibility...\")\n\t\tsuites, err := detectCompatibility(clients.Admin)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unable to determine server suite compatibility: %s\\n\", err)\n\t\t}\n\t\ttests = make(map[string]struct{})\n\t\tfor _, suite := range suites {\n\t\t\ttests[suite] = struct{}{}\n\t\t}\n\t}\n\ttestSuites = make([]string, 0, len(tests))\n\tfor test := range tests {\n\t\ttestSuites = append(testSuites, test)\n\t}\n\tt.Logf(\"Running the following test suites: %s\\n\", strings.Join(testSuites, \", \"))\n\tfor _, suite := range testSuites {\n\t\tRunTestsInternal(clients, suite)\n\t}\n}", "func TestRun(t *testing.T) {\n\tRun()\n}", "func RunTests(opts Options) {\n\tif opts.Cleanup {\n\t\terr := CleanupTests(opts.Driver, opts.DSN, opts.Verbose)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Cleanup failed: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\t_ = flag.Set(\"test.run\", opts.Match)\n\tif opts.Verbose {\n\t\t_ = flag.Set(\"test.v\", \"true\")\n\t}\n\ttests := []testing.InternalTest{\n\t\t{\n\t\t\tName: \"MainTest\",\n\t\t\tF: func(t *testing.T) {\n\t\t\t\tTest(t, opts.Driver, opts.DSN, opts.Suites, opts.RW)\n\t\t\t},\n\t\t},\n\t}\n\n\tmainStart(tests)\n}", "func main() {\n\n mainTests{}.mainTests117SortFileMgrsCaseSensitive()\n\n}", "func Test(t *testing.T) {\n}", "func RunTest(flags *Flags) error {\n\tswitch flags.Mode {\n\tcase constants.ManagerMode:\n\t\treturn workermanager.New().RunTest()\n\tcase constants.WorkerMode:\n\t\tslackURL := flags.SlackURL\n\t\tvar slacks []string\n\t\tif len(slackURL) > 0 {\n\t\t\tslacks = append(slacks, slackURL)\n\t\t}\n\t\treturn worker.NewWorker().RunTest(flags.Type, slacks)\n\t}\n\n\treturn nil\n}", "func TestManager(t *testing.T) {\n\tsuite.Run(t, &TestManagerSuite{})\n}", "func TestHealthSuite(t *testing.T) {\n\tsuite.Run(t, new(HealthSuite))\n}", "func TestMain(m *testing.M) {\n\tvar err error\n\tvar status int\n\t// remove timestamp\n\tlog.SetFlags(0)\n\n\tlog.Println(\"Testing using TestStore\")\n\tstore, err = rangestore.ConnectTestStore(\"Test Store\") // this can never return error\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// run the test with store == TestStore\n\tstatus = m.Run()\n\tif status != 0 {\n\t\tos.Exit(status)\n\t}\n\t// do something more\n\tvar dir = \"../rangestore/filestore/t\"\n\tvar depth = 3\n\tvar fast = false\n\tlog.Println(\"Testing using FileStore\")\n\tstore, err = filestore.ConnectFileStore(dir, depth, fast)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// run all the test with store == FileStore\n\tstatus = m.Run()\n\n\tif status != 0 {\n\t\tos.Exit(status)\n\t}\n\n\t// etcdstore\n\tvar hosts = []string{\"http://127.0.0.1:13824\"}\n\tvar roptimize = false\n\tvar efast = false\n\tvar node = \"\"\n\tstore, err = etcdstore.ConnectEtcdStore(hosts, roptimize, efast, node)\n\tif err != nil {\n\t\t// lets die more gracefully!\n\t\tlog.Println(\"NOT Testing using EtcdStore\")\n\t\tos.Exit(0)\n\t}\n\tlog.Println(\"Testing using EtcdStore\")\n\n\t// run all the test with store == EtcdStore\n\tstatus = m.Run()\n\n\tif status != 0 {\n\t\tos.Exit(status)\n\t}\n}", "func (suite *TrackvisitedTestSuite) SetupTest() {}", "func TestTestSuite(t *testing.T) {\n\tRunSuite(t, new(SuiteSuite))\n}", "func doTests(t *testing.T, tests []string) {\n\tdoTestsParam(t, tests, TestParams{\n\t\textensions: parser.CommonExtensions,\n\t})\n}", "func runSuite(t *testing.T, db *H, suite interface{}) {\n\trv := reflect.ValueOf(suite)\n\t//if not pointer quit\n\tif rv.Kind() != reflect.Ptr {\n\t\treturn\n\t}\n\n\trt := rv.Type()\n\tfor i := 0; i < rt.NumMethod(); i++ {\n\t\tm := rt.Method(i)\n\t\tif strings.HasPrefix(m.Name, \"Test\") {\n\t\t\tt.Run(m.Name, func(t *testing.T) {\n\n\t\t\t\tdb, err := localizeLogger(db, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tvar args = []reflect.Value{\n\t\t\t\t\trv,\n\t\t\t\t\treflect.ValueOf(t),\n\t\t\t\t\treflect.ValueOf(db),\n\t\t\t\t}\n\t\t\t\tm.Func.Call(args)\n\t\t\t})\n\t\t}\n\n\t}\n}", "func runTest(m *testing.M) int {\n\t// In order to get a Mongo session we need the name of the database we\n\t// are using. The web framework middleware is using this by convention.\n\tdbName, err := cfg.String(\"MONGO_DB\")\n\tif err != nil {\n\t\tfmt.Println(\"MongoDB is not configured\")\n\t\treturn 1\n\t}\n\n\tdb, err := db.NewMGO(\"context\", dbName)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to get Mongo session\")\n\t\treturn 1\n\t}\n\n\tdefer db.CloseMGO(\"context\")\n\n\ttstdata.Generate(db)\n\tdefer tstdata.Drop(db)\n\n\tloadQuery(db, \"basic.json\")\n\tloadQuery(db, \"basic_var.json\")\n\tdefer qfix.Remove(db, \"QTEST_O\")\n\n\tloadScript(db, \"basic_script_pre.json\")\n\tloadScript(db, \"basic_script_pst.json\")\n\tdefer sfix.Remove(db, \"STEST_O\")\n\n\tloadMasks(db, \"basic.json\")\n\tdefer mfix.Remove(db, \"test_xenia_data\")\n\n\treturn m.Run()\n}", "func TestRunServer(t *testing.T) {\n\trand.Seed(time.Now().Unix())\n\tdir1, err := NewDirectory(\"./TestDir1\", \"127.0.0.1:9331\", 1*time.Second, 500, 10*time.Second, 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo dir1.ListenAndServe()\n\tdir2, err := NewDirectory(\"./TestDir2\", \"127.0.0.1:9332\", 1*time.Second, 500, 10*time.Second, 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo dir2.ListenAndServe()\n\tdir3, err := NewDirectory(\"./TestDir3\", \"127.0.0.1:9333\", 1*time.Second, 500, 10*time.Second, 0, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo dir3.ListenAndServe()\n\ttime.Sleep(1 * time.Second)\n\tss1, err := NewStoreServer(\"./TestStore1\", \"./TestStore1\", 0.4, \"127.0.0.1:8787\", 10*time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo ss1.ListenAndServe()\n\tss2, err := NewStoreServer(\"./TestStore2\", \"./TestStore2\", 0.4, \"127.0.0.1:8788\", 10*time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo ss2.ListenAndServe()\n\tss3, err := NewStoreServer(\"./TestStore3\", \"./TestStore3\", 0.4, \"127.0.0.1:8789\", 10*time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo ss3.ListenAndServe()\n}", "func TestMain(m *testing.M) {\n\ttestsuite.RevelTestHelper(m, \"dev\", run.Run)\n}", "func InitMultiVolumeTestSuite() storageframework.TestSuite {\n\tpatterns := []storageframework.TestPattern{\n\t\tstorageframework.FsVolModePreprovisionedPV,\n\t\tstorageframework.FsVolModeDynamicPV,\n\t\tstorageframework.BlockVolModePreprovisionedPV,\n\t\tstorageframework.BlockVolModeDynamicPV,\n\t\tstorageframework.Ext4DynamicPV,\n\t\tstorageframework.XfsDynamicPV,\n\t\tstorageframework.NtfsDynamicPV,\n\t}\n\treturn InitCustomMultiVolumeTestSuite(patterns)\n}", "func runTests(t *testing.T, tests []test) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresp := executeRequest(tt.method, tt.url, serialize(tt.req), tt.asAdmin)\n\t\t\tif resp.StatusCode != tt.want {\n\t\t\t\tt.Errorf(\"Unexpected status code %d\", resp.StatusCode)\n\t\t\t}\n\n\t\t\tif tt.body != \"\" {\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tdefer resp.Body.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Error loading body\")\n\t\t\t\t}\n\t\t\t\tif tt.body != string(bodyBytes) {\n\t\t\t\t\tt.Errorf(\"Unexpected body '%s', expected '%s'\", bodyBytes, tt.body)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func Testflow(t *testing.T, test TestCase) {\n\tdefer afterTestCase(t, test)\n\tbeforeTestCase(t, test)\n\texecuteTestMethods(t, test)\n\tfmt.Println(\"\")\n}", "func Test(t *testing.T) { TestingT(t) }" ]
[ "0.74199057", "0.6239286", "0.5898885", "0.5763875", "0.55768025", "0.5535625", "0.5483049", "0.5438944", "0.5409459", "0.54024374", "0.536691", "0.53133875", "0.52840734", "0.5260231", "0.52529013", "0.5223269", "0.52011824", "0.5199903", "0.5185914", "0.517336", "0.51660126", "0.5162174", "0.5147487", "0.5146034", "0.51293784", "0.5087189", "0.50809956", "0.50802964", "0.5061168", "0.50510556", "0.5047286", "0.5035536", "0.5034962", "0.5012022", "0.5010247", "0.5005258", "0.4999064", "0.49984252", "0.4969046", "0.49658293", "0.49575478", "0.494832", "0.49464223", "0.4945885", "0.4945814", "0.49415627", "0.49413288", "0.4934963", "0.49339083", "0.4931398", "0.4931188", "0.4919422", "0.4912871", "0.49095422", "0.49035358", "0.4901389", "0.4898545", "0.48966333", "0.48929325", "0.48875123", "0.48858044", "0.48753506", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48644823", "0.48635706", "0.48635706", "0.48635706", "0.48596248", "0.4852091", "0.4850229", "0.48452958", "0.48443487", "0.48349804", "0.483279", "0.48284784", "0.48185757", "0.48163757", "0.48148555", "0.48102173", "0.48088294", "0.4803984", "0.48036152", "0.48035687", "0.48026773", "0.47992754", "0.47989947", "0.47949263", "0.47869626", "0.47850466", "0.47842154", "0.4763276", "0.4761517" ]
0.67247283
1
tbRun calls (testing.T).Run or (testing.B).Run.
func tbRun(t testing.TB, name string, f func(testing.TB)) bool { switch tb := t.(type) { case *testing.B: return tb.Run(name, func(b *testing.B) { f(b) }) case *testing.T: return tb.Run(name, func(t *testing.T) { f(t) }) default: panic(fmt.Sprintf("unexpected %T, want *testing.B or *testing.T", tb)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tbRun(t testing.TB, name string, f func(testing.TB)) bool {\n\tt.Helper()\n\tswitch tb := t.(type) {\n\tcase *testing.B:\n\t\treturn tb.Run(name, func(b *testing.B) {\n\t\t\tb.Helper()\n\t\t\tf(b)\n\t\t})\n\tcase *testing.T:\n\t\treturn tb.Run(name, func(t *testing.T) {\n\t\t\tt.Helper()\n\t\t\tf(t)\n\t\t})\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected %T, want *testing.B or *testing.T\", tb))\n\t}\n}", "func Run(name string, t testing.TB, f func(testing.TB)) {\n\tif tt, ok := t.(*testing.T); ok {\n\t\ttt.Run(name, func(ttt *testing.T) { f(ttt) })\n\t\treturn\n\t}\n\tif tb, ok := t.(*testing.B); ok {\n\t\ttb.Run(name, func(ttb *testing.B) { f(ttb) })\n\t\treturn\n\t}\n\tt.Error(\"invalid test harness\")\n\tt.FailNow()\n}", "func (t *Test) Run() error {\n\treturn t.Wrap(t.run)\n}", "func TestRun(t *testing.T) {\n\tRun()\n}", "func Run(t *testing.T, s suite.TestingSuite) {\n\tsuite.Run(t, s)\n}", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func Test(t *testing.T) { TestingT(t) }", "func (t *T) Run(name string, f interface{}) bool {\n\tt.Helper()\n\tt.validateCallback(f)\n\n\treturn t.T.Run(name, func(test *testing.T) {\n\t\tt.invoke(f, test)\n\t})\n}", "func (t *Test) Run(fn func(ctx TestContext)) {\n\tstart := time.Now()\n\n\tscopes.CI.Infof(\"=== BEGIN: Test: '%s[%s]' ===\", rt.SuiteContext().Settings().TestID, t.t.Name())\n\tdefer func() {\n\t\tend := time.Now()\n\t\tscopes.CI.Infof(\"=== DONE: Test: '%s[%s] (%v)' ===\", rt.SuiteContext().Settings().TestID, t.t.Name(), end.Sub(start))\n\t}()\n\n\tctx := NewContext(t.t, t.labels...)\n\tdefer ctx.Done(t.t)\n\tfn(ctx)\n}", "func TestMain(t *testing.T) { TestingT(t) }", "func Run(t *testing.T, suites ...TCatcher) {\n\trun(t, new(TDDFormatter), suites...)\n}", "func (test Test) Run(t *testing.T) {\n\tt.Logf(\"Starting test %v\", t.Name())\n\tt.Helper()\n\t// Double negative cannot be helped, this is intended to mitigate test failures where a global\n\t// resource is manipulated, e.g.: the default AWS security group.\n\tif !test.RunOptions.NoParallel {\n\t\tt.Parallel()\n\t}\n\tt.Run(\"Python\", func(t *testing.T) {\n\t\trunOpts := integration.ProgramTestOptions{}\n\t\tif test.RunOptions != nil {\n\t\t\trunOpts = *test.RunOptions\n\t\t}\n\t\tconvertOpts := test.Options\n\t\tif test.Python != nil {\n\t\t\tconvertOpts = convertOpts.With(*test.Python)\n\t\t}\n\n\t\ttargetTest := targetTest{\n\t\t\trunOpts: &runOpts,\n\t\t\tconvertOpts: &convertOpts,\n\t\t\tprojectName: test.ProjectName,\n\t\t\tlanguage: \"python\",\n\t\t\truntime: \"python\",\n\t\t}\n\t\ttargetTest.Run(t)\n\t})\n\tt.Run(\"TypeScript\", func(t *testing.T) {\n\t\trunOpts := integration.ProgramTestOptions{}\n\t\tif test.RunOptions != nil {\n\t\t\trunOpts = *test.RunOptions\n\t\t}\n\t\tconvertOpts := test.Options\n\t\tif test.TypeScript != nil {\n\t\t\tconvertOpts = convertOpts.With(*test.TypeScript)\n\t\t}\n\n\t\ttargetTest := targetTest{\n\t\t\trunOpts: &runOpts,\n\t\t\tconvertOpts: &convertOpts,\n\t\t\tprojectName: test.ProjectName,\n\t\t\tlanguage: \"typescript\",\n\t\t\truntime: \"nodejs\",\n\t\t}\n\t\ttargetTest.Run(t)\n\t})\n}", "func (t *Test) Run() error {\n\tfor _, cmd := range t.cmds {\n\t\t// TODO(fabxc): aggregate command errors, yield diffs for result\n\t\t// comparison errors.\n\t\tif err := t.exec(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (ts ApisValidatableTestSuite) Run(t *testing.T) {\n\tt.Parallel()\n\tfor k, v := range ts {\n\t\tt.Run(k, v.Run)\n\t}\n}", "func Run(t *testing.T, maker Maker) {\n\tsuite.Run(t, &baseSuite{maker: maker})\n}", "func (s Suite) Run(t *testing.T) bool {\n\tt.Helper()\n\treturn s(\"\", nil, func(c *config) { c.t = t })\n}", "func Run(t tt, h http.Handler, tcs ...TestCase) {\n\tfor _, tc := range tcs {\n\t\tf := func(t tt) {\n\t\t\trec := httptest.NewRecorder()\n\t\t\treq := httpRequest(&tc.Request)\n\t\t\th.ServeHTTP(rec, req)\n\t\t\tassertResponse(t, rec, &tc.Response)\n\t\t}\n\n\t\tif tc.Name != \"\" {\n\t\t\tt.Run(tc.Name, func(t *testing.T) {\n\t\t\t\tf(t)\n\t\t\t})\n\t\t} else {\n\t\t\tf(t)\n\t\t}\n\t}\n}", "func (t testCommand) Run() error {\n\tif t.shouldFail {\n\t\treturn errors.New(\"I AM ERROR\")\n\t}\n\treturn nil\n}", "func (bt *BackTest) Run() {\n\tlog.Info(common.Backtester, \"running backtester against pre-defined data\")\ndataLoadingIssue:\n\tfor ev := bt.EventQueue.NextEvent(); ; ev = bt.EventQueue.NextEvent() {\n\t\tif ev == nil {\n\t\t\tdataHandlerMap := bt.Datas.GetAllData()\n\t\t\tvar hasProcessedData bool\n\t\t\tfor exchangeName, exchangeMap := range dataHandlerMap {\n\t\t\t\tfor assetItem, assetMap := range exchangeMap {\n\t\t\t\t\tfor currencyPair, dataHandler := range assetMap {\n\t\t\t\t\t\td := dataHandler.Next()\n\t\t\t\t\t\tif d == nil {\n\t\t\t\t\t\t\tif !bt.hasHandledEvent {\n\t\t\t\t\t\t\t\tlog.Errorf(common.Backtester, \"Unable to perform `Next` for %v %v %v\", exchangeName, assetItem, currencyPair)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak dataLoadingIssue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif bt.Strategy.UsingSimultaneousProcessing() && hasProcessedData {\n\t\t\t\t\t\t\t// only append one event, as simultaneous processing\n\t\t\t\t\t\t\t// will retrieve all relevant events to process under\n\t\t\t\t\t\t\t// processSimultaneousDataEvents()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbt.EventQueue.AppendEvent(d)\n\t\t\t\t\t\thasProcessedData = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terr := bt.handleEvent(ev)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(common.Backtester, err)\n\t\t\t}\n\t\t}\n\t\tif !bt.hasHandledEvent {\n\t\t\tbt.hasHandledEvent = true\n\t\t}\n\t}\n}", "func TestRun(t *testing.T) {\n\tsuite.Run(t, new(CategoryTestSuite))\n\tsuite.Run(t, new(ProductTestSuite))\n}", "func (tester Tester) R(test *testing.T) {\n\ttester.init(test)\n\ttester.runMemorizedTests(test)\n\ttester.runGeneratedTests(test)\n}", "func (runner *suiteRunner) run() *Result {\n if runner.tracker.result.RunError == nil && len(runner.tests) > 0 {\n runner.tracker.start()\n if runner.checkFixtureArgs() {\n if runner.runFixture(runner.setUpSuite) {\n for i := 0; i != len(runner.tests); i++ {\n c := runner.runTest(runner.tests[i])\n if c.status == fixturePanickedSt {\n runner.missTests(runner.tests[i+1:])\n break\n }\n }\n } else {\n runner.missTests(runner.tests)\n }\n runner.runFixture(runner.tearDownSuite)\n } else {\n runner.missTests(runner.tests)\n }\n runner.tracker.waitAndStop()\n runner.tempDir.removeAll()\n }\n return &runner.tracker.result\n}", "func run(t *testing.T, formatter Formatter, suites ...TCatcher) {\n\tvar (\n\t\tbeforeAllFound, afterAllFound bool\n\t\tbeforeAll, afterAll, before, after reflect.Value\n\t\ttotalPassed, totalFailed, totalPending, totalNoAssertions int\n\t)\n\n\tflag.Parse()\n\n\tfor _, s := range suites {\n\t\tbeforeAll, afterAll, before, after = reflect.Value{}, reflect.Value{}, reflect.Value{}, reflect.Value{}\n\t\ts.SetT(t)\n\t\ts.Reset()\n\n\t\tiType := reflect.TypeOf(s)\n\n\t\tformatter.PrintSuiteName(strings.Split(iType.String(), \".\")[1])\n\n\t\t// search for Before and After methods\n\t\tfor i := 0; i < iType.NumMethod(); i++ {\n\t\t\tmethod := iType.Method(i)\n\t\t\tif ok, _ := regexp.MatchString(\"^BeforeAll\", method.Name); ok {\n\t\t\t\tif !beforeAllFound {\n\t\t\t\t\tbeforeAll = method.Func\n\t\t\t\t\tbeforeAllFound = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ok, _ := regexp.MatchString(\"^AfterAll\", method.Name); ok {\n\t\t\t\tif !afterAllFound {\n\t\t\t\t\tafterAll = method.Func\n\t\t\t\t\tafterAllFound = true\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ok, _ := regexp.MatchString(\"^Before\", method.Name); ok {\n\t\t\t\tbefore = method.Func\n\t\t\t}\n\t\t\tif ok, _ := regexp.MatchString(\"^After\", method.Name); ok {\n\t\t\t\tafter = method.Func\n\t\t\t}\n\t\t}\n\n\t\tif beforeAll.IsValid() {\n\t\t\tbeforeAll.Call([]reflect.Value{reflect.ValueOf(s)})\n\t\t}\n\n\t\tfor i := 0; i < iType.NumMethod(); i++ {\n\t\t\tmethod := iType.Method(i)\n\t\t\tif ok, _ := regexp.MatchString(*testToRun, method.Name); ok {\n\t\t\t\tif ok, _ := regexp.MatchString(formatter.AllowedMethodsPattern(), method.Name); ok {\n\n\t\t\t\t\ts.SetStatus(&Status{Code: STATUS_NO_ASSERTIONS})\n\n\t\t\t\t\tif before.IsValid() {\n\t\t\t\t\t\tbefore.Call([]reflect.Value{reflect.ValueOf(s)})\n\t\t\t\t\t}\n\n\t\t\t\t\tmethod.Func.Call([]reflect.Value{reflect.ValueOf(s)})\n\n\t\t\t\t\tif after.IsValid() {\n\t\t\t\t\t\tafter.Call([]reflect.Value{reflect.ValueOf(s)})\n\t\t\t\t\t}\n\n\t\t\t\t\tvar info *suiteInfo\n\t\t\t\t\tstatus := s.GetStatus()\n\n\t\t\t\t\tswitch status.Code {\n\t\t\t\t\tcase STATUS_PASS:\n\t\t\t\t\t\tinfo = s.GetInfo()\n\t\t\t\t\t\ttotalPassed++\n\t\t\t\t\tcase STATUS_FAIL:\n\t\t\t\t\t\tinfo = s.GetInfo()\n\t\t\t\t\t\tt.Error(status.ErrorMessage)\n\t\t\t\t\t\ttotalFailed++\n\t\t\t\t\tcase STATUS_PENDING:\n\t\t\t\t\t\tinfo = s.GetInfo()\n\t\t\t\t\t\tinfo.assertions = 0\n\t\t\t\t\t\ttotalPending++\n\t\t\t\t\tcase STATUS_NO_ASSERTIONS:\n\t\t\t\t\t\tinfo = &suiteInfo{0, method.Name}\n\t\t\t\t\t\ttotalNoAssertions++\n\t\t\t\t\t}\n\t\t\t\t\tformatter.PrintStatus(status, info)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif afterAll.IsValid() {\n\t\t\tafterAll.Call([]reflect.Value{reflect.ValueOf(s)})\n\t\t}\n\t}\n\n\tformatter.PrintFinalReport(totalPassed, totalFailed, totalPending, totalNoAssertions)\n}", "func TestSIFTLib2(t *testing.T) { TestingT(t) }", "func TestRunMain(t *testing.T) {\n\tmain()\n}", "func TestTools(t *testing.T) { TestingT(t) }", "func (f *VRFTest) Run() error {\n\tif err := f.createChainlinkJobs(); err != nil {\n\t\treturn err\n\t}\n\tvar ctx context.Context\n\tvar testCtxCancel context.CancelFunc\n\tif f.TestOptions.TestDuration.Seconds() > 0 {\n\t\tctx, testCtxCancel = context.WithTimeout(context.Background(), f.TestOptions.TestDuration)\n\t} else {\n\t\tctx, testCtxCancel = context.WithCancel(context.Background())\n\t}\n\tdefer testCtxCancel()\n\tcancelPerfEvents := f.watchPerfEvents()\n\tcurrentRound := 0\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Info().Msg(\"Test finished\")\n\t\t\ttime.Sleep(f.TestOptions.GracefulStopDuration)\n\t\t\tcancelPerfEvents()\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tlog.Info().Int(\"RoundID\", currentRound).Msg(\"New round\")\n\t\t\tif err := f.requestRandomness(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := f.waitRoundFulfilled(currentRound + 1); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif f.TestOptions.NumberOfRounds != 0 && currentRound >= f.TestOptions.NumberOfRounds {\n\t\t\t\tlog.Info().Msg(\"Final round is reached\")\n\t\t\t\ttestCtxCancel()\n\t\t\t}\n\t\t\tcurrentRound++\n\t\t}\n\t}\n}", "func (t *Test) Run(tc *TestSuite) error {\n\n\tmqutil.Logger.Print(\"\\n--- \" + t.Name)\n\tfmt.Printf(\"\\nRunning test case: %s\\n\", t.Name)\n\terr := t.ResolveParameters(tc)\n\tif err != nil {\n\t\tfmt.Printf(\"... Fail\\n... %s\\n\", err.Error())\n\t\treturn err\n\t}\n\n\treq := resty.R()\n\tif len(tc.ApiToken) > 0 {\n\t\treq.SetAuthToken(tc.ApiToken)\n\t} else if len(tc.Username) > 0 {\n\t\treq.SetBasicAuth(tc.Username, tc.Password)\n\t}\n\n\tpath := GetBaseURL(t.db.Swagger) + t.SetRequestParameters(req)\n\tvar resp *resty.Response\n\n\tt.startTime = time.Now()\n\tswitch t.Method {\n\tcase mqswag.MethodGet:\n\t\tresp, err = req.Get(path)\n\tcase mqswag.MethodPost:\n\t\tresp, err = req.Post(path)\n\tcase mqswag.MethodPut:\n\t\tresp, err = req.Put(path)\n\tcase mqswag.MethodDelete:\n\t\tresp, err = req.Delete(path)\n\tcase mqswag.MethodPatch:\n\t\tresp, err = req.Patch(path)\n\tcase mqswag.MethodHead:\n\t\tresp, err = req.Head(path)\n\tcase mqswag.MethodOptions:\n\t\tresp, err = req.Options(path)\n\tdefault:\n\t\treturn mqutil.NewError(mqutil.ErrInvalid, fmt.Sprintf(\"Unknown method in test %s: %v\", t.Name, t.Method))\n\t}\n\tt.stopTime = time.Now()\n\tfmt.Printf(\"... call completed: %f seconds\\n\", t.stopTime.Sub(t.startTime).Seconds())\n\n\tif err != nil {\n\t\tt.err = mqutil.NewError(mqutil.ErrHttp, err.Error())\n\t} else {\n\t\tmqutil.Logger.Print(resp.Status())\n\t\tmqutil.Logger.Println(string(resp.Body()))\n\t}\n\terr = t.ProcessResult(resp)\n\treturn err\n}", "func (suite FeatureTestSuite) Run(t *testing.T, buildFunc feature.BuildFunc) {\n\tfor _, test := range suite {\n\t\trunTest(t, test, buildFunc)\n\t}\n}", "func TestA(t *testing.T) {}", "func (b *T) Run(name string, f func(t *T)) bool {\n\tsuccess := true\n\tif b.tracker.Active() {\n\t\tsuccess = success && b.t.Run(name, func(t *testing.T) {\n\t\t\tf(&T{t, t, b.tracker.SubTracker()})\n\t\t})\n\t}\n\treturn success\n}", "func (e *Environment) Run(tests ...TestFunc) {\n\tfor _, test := range tests {\n\t\tf := e.New(test)\n\t\te.t.Run(f.name, func(t *testing.T) {\n\t\t\t// Recover from panics to ensure that defer Teardown will run.\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tt.Errorf(\"panic: %s\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tf.t = t\n\t\t\tf.testFn(t, f)\n\t\t})\n\t}\n}", "func (s *FakeJujuRunnerSuite) TestRun(c *gc.C) {\n\ts.runner.Run()\n\ts.runner.Stop()\n\tresult := s.runner.Wait()\n \n\tc.Assert(result.String(), gc.Equals, \"OK: 1 passed\")\n\tc.Assert(result.Succeeded, gc.Equals, 1)\n\tc.Assert(result.RunError, gc.IsNil)\n\tc.Assert(\n\t\tstrings.Contains(s.output.String(), \"Starting service\"), gc.Equals, true)\n}", "func (o *Onpar) Run(t *testing.T) {\n\ttraverse(o.current, func(l *level) {\n\t\tfor _, spec := range l.specs {\n\t\t\tspec.invoke(t, l)\n\t\t}\n\t})\n}", "func (t *T) Run(name string, fn func(t *T)) {\n\tt.T.Run(name, func(tt *testing.T) {\n\t\ttt.Helper()\n\t\tt := *t\n\t\tt.T = tt\n\t\tu := *t.URL\n\t\tt.URL = &u\n\n\t\tfn(&t)\n\t})\n}", "func RunTests(t *testing.T, tests map[string]SubTest) {\n\tfor name, test := range tests {\n\t\tdomainKeeper, ctx, mocks := NewTestKeeper(t, true)\n\t\t// set default mock.Supply not to fail\n\t\tmocks.Supply.SetSendCoinsFromAccountToModule(func(ctx types.Context, addr types.AccAddress, moduleName string, coins types.Coins) error {\n\t\t\treturn nil\n\t\t})\n\t\t// set default fees\n\t\tsetFees := domainKeeper.ConfigurationKeeper.(ConfigurationSetter).SetFees\n\t\tfees := configuration.NewFees()\n\t\tfees.SetDefaults(\"testcoin\")\n\t\tsetFees(ctx, fees)\n\t\t// run sub SubTest\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// run before SubTest\n\t\t\tif test.BeforeTest != nil {\n\t\t\t\tif test.BeforeTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.BeforeTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.BeforeTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\n\t\t\tif test.TestBlockTime != 0 {\n\t\t\t\tt := time.Unix(test.TestBlockTime, 0)\n\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t}\n\t\t\t// run actual SubTest\n\t\t\ttest.Test(t, domainKeeper, ctx, mocks)\n\n\t\t\t// run after SubTest\n\t\t\tif test.AfterTest != nil {\n\t\t\t\tif test.AfterTestBlockTime != 0 {\n\t\t\t\t\tt := time.Unix(test.AfterTestBlockTime, 0)\n\t\t\t\t\tctx = ctx.WithBlockTime(t)\n\t\t\t\t}\n\t\t\t\ttest.AfterTest(t, domainKeeper, ctx, mocks)\n\t\t\t}\n\t\t})\n\t}\n}", "func Run(t *testing.T, configOpt core.ConfigProvider, sdkOpts ...fabsdk.Option) {\n\tsetupAndRun(t, true, configOpt, e2eTest, sdkOpts...)\n}", "func (t *Test) Run(ctx context.Context, opts ...TestOption) (*TestResult, error) {\n\tparsedOpts := &testOptions{\n\t\tvars: &starlark.Dict{},\n\t}\n\tfor _, opt := range opts {\n\t\topt.applyTest(parsedOpts)\n\t}\n\n\tthread := &starlark.Thread{\n\t\tPrint: skyPrint,\n\t}\n\tthread.SetLocal(\"context\", ctx)\n\n\tassertModule := assertmodule.AssertModule()\n\ttestCtx := &starlarkstruct.Module{\n\t\tName: \"skycfg_test_ctx\",\n\t\tMembers: starlark.StringDict(map[string]starlark.Value{\n\t\t\t\"vars\": parsedOpts.vars,\n\t\t\t\"assert\": assertModule,\n\t\t}),\n\t}\n\targs := starlark.Tuple([]starlark.Value{testCtx})\n\n\tresult := TestResult{\n\t\tTestName: t.Name(),\n\t}\n\n\tstartTime := time.Now()\n\t_, err := starlark.Call(thread, t.callable, args, nil)\n\tresult.Duration = time.Since(startTime)\n\tif err != nil {\n\t\t// if there is no assertion error, there was something wrong with the execution itself\n\t\tif len(assertModule.Failures) == 0 {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// there should only be one failure, because each test run gets its own *TestContext\n\t\t// and each assertion failure halts execution.\n\t\tif len(assertModule.Failures) > 1 {\n\t\t\tpanic(\"A test run should only have one assertion failure. Something went wrong with the test infrastructure.\")\n\t\t}\n\t\tresult.Failure = assertModule.Failures[0]\n\t}\n\n\treturn &result, nil\n}", "func TestData(t *testing.T) { TestingT(t) }", "func (envManager *TestEnvManager) RunTest(m runnable) (ret int) {\n\tdefer envManager.TearDown()\n\tif err := envManager.StartUp(); err != nil {\n\t\tlog.Printf(\"Failed to setup framework: %s\", err)\n\t\tret = 1\n\t} else {\n\t\tlog.Printf(\"\\nStart testing ......\")\n\t\tret = m.Run()\n\t}\n\treturn ret\n}", "func runTests(t *testing.T, tests []test) {\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresp := executeRequest(tt.method, tt.url, serialize(tt.req), tt.asAdmin)\n\t\t\tif resp.StatusCode != tt.want {\n\t\t\t\tt.Errorf(\"Unexpected status code %d\", resp.StatusCode)\n\t\t\t}\n\n\t\t\tif tt.body != \"\" {\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tdefer resp.Body.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"Error loading body\")\n\t\t\t\t}\n\t\t\t\tif tt.body != string(bodyBytes) {\n\t\t\t\t\tt.Errorf(\"Unexpected body '%s', expected '%s'\", bodyBytes, tt.body)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (t *TestRuntime) RunTests(m *testing.M) int {\n\treturn t.runTests(m, !testing.Verbose())\n}", "func (m *Maker) Run(t *testing.T, userCalls ...func(*testing.T, gtk.Widgetter)) {\n\tvar w gtk.Widgetter // stores the widget to provide for all calls.\n\tcalls := make([]interface{}, len(userCalls)+1)\n\tcalls[0] = func() gtk.Widgetter {\n\t\tw = m.newW()\n\t\treturn w\n\t}\n\tfor i, call := range userCalls {\n\t\tcalls[i+1] = func() { call(t, w) }\n\t}\n\tm.app.ID = fmt.Sprintf(\"%s%d\", m.baseID, m.counter)\n\tm.counter++\n\tm.app.Run(calls...)\n}", "func (t *TestPhase) Run(_ context.Context, queue *Queue, _, _ chan message.Message, _ RoundUpdate, step uint8) PhaseFn {\n\tt.callback(t.req, t.packet, t.streamer, t.aChan)\n\treturn nil\n}", "func run(name string, b *testing.B, count int, fn func(buf *Buffer, r *Reader)) {\r\n\tb.Run(name, func(b *testing.B) {\r\n\t\tbuf := NewBuffer(count * 20)\r\n\t\tr := NewReader()\r\n\t\tb.ReportAllocs()\r\n\t\tb.ResetTimer()\r\n\t\tfor n := 0; n < b.N; n++ {\r\n\t\t\tbuf.Reset(\"test\")\r\n\t\t\tfn(buf, r)\r\n\t\t}\r\n\t})\r\n}", "func runSuite(t *testing.T, db *H, suite interface{}) {\n\trv := reflect.ValueOf(suite)\n\t//if not pointer quit\n\tif rv.Kind() != reflect.Ptr {\n\t\treturn\n\t}\n\n\trt := rv.Type()\n\tfor i := 0; i < rt.NumMethod(); i++ {\n\t\tm := rt.Method(i)\n\t\tif strings.HasPrefix(m.Name, \"Test\") {\n\t\t\tt.Run(m.Name, func(t *testing.T) {\n\n\t\t\t\tdb, err := localizeLogger(db, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tvar args = []reflect.Value{\n\t\t\t\t\trv,\n\t\t\t\t\treflect.ValueOf(t),\n\t\t\t\t\treflect.ValueOf(db),\n\t\t\t\t}\n\t\t\t\tm.Func.Call(args)\n\t\t\t})\n\t\t}\n\n\t}\n}", "func (b *backfiller) Run(ctx context.Context) {\n\topName := fmt.Sprintf(\"%sBackfiller\", b.name)\n\tctx = logtags.AddTag(ctx, opName, int(b.spec.Table.ID))\n\tctx, span := execinfra.ProcessorSpan(ctx, opName)\n\tdefer span.Finish()\n\tmeta := b.doRun(ctx)\n\texecinfra.SendTraceData(ctx, b.output)\n\tif emitHelper(ctx, &b.out, nil /* row */, meta, func(ctx context.Context) {}) {\n\t\tb.output.ProducerDone()\n\t}\n}", "func Test_Run(t *testing.T) {\n\tr := taskrunner.New()\n\tf := false\n\n\tr.Run(\"Name\", func(ctx context.Context) {\n\t\tf = true\n\t})\n\tr.Wait()\n\n\tassert.Equal(t, true, f)\n}", "func (t TestCases) Run(fn func(string) (string, string), hideInput bool) {\n\tfor _, test := range t {\n\t\tpart1, part2 := fn(test.Input)\n\t\tpassedPart1 := part1 == test.ExpectedPart1 || test.ExpectedPart1 == \"\"\n\t\tpassedPart2 := part2 == test.ExpectedPart2 || test.ExpectedPart2 == \"\"\n\t\tpassed := passedPart1 && passedPart2\n\n\t\tif !passed && !hideInput {\n\t\t\tfmt.Println(\"Input \", test.Input)\n\t\t}\n\t\tif !passedPart1 {\n\t\t\tfmt.Println(\" - PART1: \", part1, \" but expected \", test.ExpectedPart1)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif !passedPart2 {\n\t\t\tfmt.Println(\" - PART2: \", part2, \" but expected \", test.ExpectedPart2)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func Run() {\n\t//tErr()\n\t//tCatch()\n\terr := customErr()\n\tif err != nil {\n\t\tpanic(err) //执行到这里下面的东西就不会再执行了\n\t}\n\tfmt.Println(\"main\")\n}" ]
[ "0.7722541", "0.7657983", "0.71177715", "0.70478946", "0.6633116", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6421186", "0.6322125", "0.6303159", "0.6300831", "0.62991846", "0.62702966", "0.62093663", "0.61966985", "0.6163188", "0.61412096", "0.6128858", "0.6092832", "0.60831976", "0.6077666", "0.6053554", "0.60532135", "0.6014652", "0.59923863", "0.5978061", "0.5966389", "0.59660685", "0.5955541", "0.5942728", "0.59285784", "0.5926876", "0.591545", "0.5903455", "0.59013516", "0.5883311", "0.58406", "0.5828224", "0.5815117", "0.58021533", "0.5791675", "0.5787723", "0.57854366", "0.5782895", "0.5778257", "0.5745735", "0.57372904", "0.57368153", "0.5733547", "0.5727098", "0.5721662" ]
0.7818243
0
mapFS lets us easily instantiate a VFS with a map[string]string (which is less noisy than map[string][]byte in test fixtures).
func mapFS(m map[string]string) *stringMapFS { m2 := make(map[string][]byte, len(m)) filenames := make([]string, 0, len(m)) for k, v := range m { m2[k] = []byte(v) filenames = append(filenames, k) } return &stringMapFS{ FileSystem: ctxvfs.Map(m2), filenames: filenames, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FileMap(m map[string]string) FileSystem {\n\treturn filemapFS(m)\n}", "func NewMemMapFS() FS {\n\treturn afero.NewMemMapFs()\n}", "func Map(f *os.File) (File, error) { return ifile.Open(f) }", "func pathMap(collectionName, basePath string, fileList *map[string][]tilePosition) fs.WalkDirFunc {\n\treturn func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\tstderr.Println(\"Warning: while searching for PNG files: \", err)\n\t\t\treturn nil\n\t\t}\n\t\ttileName := d.Name()\n\t\tlenPath := len(path)\n\t\tif lenPath > 4 && path[lenPath-4:] == \".png\" {\n\t\t\trelPathTile, _ := filepath.Rel(basePath, path)\n\t\t\tvar tp tilePosition\n\t\t\ttp.collection = collectionName\n\t\t\ttp.path = filepath.ToSlash(filepath.Clean(relPathTile))\n\t\t\t(*fileList)[tileName] = append((*fileList)[tileName], tp)\n\t\t}\n\t\treturn nil\n\t}\n}", "func TestMapList(t *testing.T) {\n\t// inpath := \"/Users/vanilla/Downloads/けんけんぱ(けんけ) fantia 2020.03-2021.08\"\n\tbasePath := \"/Users/vanilla/Downloads/けんけんぱ(けんけ) fantia 2020.03-2021.08\"\n\n\tdata := GetFileMapList(basePath, map[string][]string{})\n\t// t.Log(ijson.Pretty(data))\n\tDoPutImage(basePath, data, 1)\n}", "func Map(filename string, contents string) []mr.KeyValue {\n\tkva := []mr.KeyValue{}\n\tkva = append(kva, mr.KeyValue{filename, \"1\"})\n\treturn kva\n}", "func testFS(id string) http.FileSystem {\n\tt := make(tree.Tree)\n\terr := t.AddFileContent(\"dir/file\", []byte(id))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}", "func NewLocalFS(m map[string]struct{}, basePath string) LocalFS {\n\tpfs := make(map[string]*LocalFile, len(m))\n\tfor k := range m {\n\t\tpfs[k] = &LocalFile{\n\t\t\tpath: k,\n\t\t}\n\t}\n\n\treturn LocalFS{\n\t\tm: pfs,\n\t\tbasePath: basePath,\n\t}\n}", "func NewFs() *Fs { return &Fs{make(map[string]*file)} }", "func genJavaMapFile(tdef *compile.TypeDef, env *compile.Env) JavaFileInfo {\n\tname, access := javaTypeName(tdef, env)\n\tdata := struct {\n\t\tAccessModifier string\n\t\tDoc string\n\t\tElemType string\n\t\tFileDoc string\n\t\tKeyType string\n\t\tName string\n\t\tPackage string\n\t\tSourceFile string\n\t\tVdlTypeName string\n\t\tVdlTypeString string\n\t}{\n\t\tAccessModifier: access,\n\t\tDoc: javaDoc(tdef.Doc, tdef.DocSuffix),\n\t\tElemType: javaType(tdef.Type.Elem(), true, env),\n\t\tFileDoc: tdef.File.Package.FileDoc,\n\t\tKeyType: javaType(tdef.Type.Key(), true, env),\n\t\tName: name,\n\t\tPackage: javaPath(javaGenPkgPath(tdef.File.Package.GenPath)),\n\t\tSourceFile: tdef.File.BaseName,\n\t\tVdlTypeName: tdef.Type.Name(),\n\t\tVdlTypeString: tdef.BaseType.String(),\n\t}\n\tvar buf bytes.Buffer\n\terr := parseTmpl(\"map\", mapTmpl).Execute(&buf, data)\n\tif err != nil {\n\t\tlog.Fatalf(\"vdl: couldn't execute map template: %v\", err)\n\t}\n\treturn JavaFileInfo{\n\t\tName: name + \".java\",\n\t\tData: buf.Bytes(),\n\t}\n}", "func (f *FileList) Map() FileMap {\n\treturn f.store\n}", "func (ids *Storage) InitMapFile(fn string) error {\n\tvar fp *os.File\n\tfn = filepath.Clean(fn)\n\n\ts, err := os.Stat(fn)\n\tdefer fp.Close()\n\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"%s does not exists, creating it...\\n\", fn)\n\t\tfp, err = os.Create(fn)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Found %s, proceed\", fn)\n\t\tfp, err = os.Open(fn)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n\n\tif s.Size() > 0 {\n\t\tbuf := make([]byte, s.Size())\n\t\t_, err := io.ReadFull(fp, buf)\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t\tlog.Panicf(\"Panic trying to read the content of %s: %v\\n\", fn, err)\n\t\t}\n\t\terr = json.Unmarshal(buf, &ids.IDs)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n\n\tlog.Printf(\"Map Loaded\")\n\tids.fn = fn\n\treturn nil\n}", "func (t *Torrent) GenPFMap() {\n\tmmap := make([][]*File, t.Size/int(t.PieceLen))\n\n\tfor _, f := range t.Files {\n\t\t// fpof, first piece's index of this file\n\t\t// lpof, last piece's index of this file\n\t\tfpof, lpof := t.getFileOffset(f)\n\n\t\tfor x := fpof; x <= lpof; x++ {\n\t\t\tmmap[int(x)] = append(mmap[int(x)], f)\n\t\t}\n\t}\n\n\tt.PFMap = mmap\n}", "func tfsWrite(imgFile *os.File, imgOffset uint64, fsSize uint64, label string, root map[string]interface{}) (*tfs, error) {\n\ttfs := newTfs(imgFile, imgOffset, fsSize)\n\ttfs.label = label\n\trand.Seed(time.Now().UnixNano())\n\t_, err := rand.Read(tfs.uuid[:])\n\terr = tfs.logInit()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create filesystem log: %v\", err)\n\t}\n\ttfs.encodeTupleHeader(len(root))\n\tfor k, v := range root {\n\t\tif k == \"children\" {\n\t\t\terr = tfs.writeDirEntries(v.(map[string]interface{}))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\ttfs.encodeMetadata(k, v)\n\t\t}\n\t}\n\treturn tfs, tfs.flush()\n}", "func TestVfoMaps(t *testing.T) {\n\n\t// Test VFOValue map\n\tfor vfoName, VFOValue := range goHamlib.VFOValue {\n\t\t_, ok := goHamlib.VFOName[VFOValue]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"VFO %d does not exist in VfoName map\", VFOValue)\n\t\t}\n\t\tif vfoName != goHamlib.VFOName[VFOValue] {\n\t\t\tt.Fatalf(\"Name of VFO inconsisted: %s\", vfoName)\n\t\t}\n\t}\n\n\t// Test VfoName map\n\tfor VFOValue, vfoName := range goHamlib.VFOName {\n\t\t_, ok := goHamlib.VFOValue[vfoName]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"VFO %s does not exist in VFOValue map\", vfoName)\n\t\t}\n\t\tif VFOValue != goHamlib.VFOValue[vfoName] {\n\t\t\tt.Fatalf(\"Value of VFO inconsisted: %s\", vfoName)\n\t\t}\n\t}\n}", "func FileMmap(f *os.File) ([]byte, error) {\n\treturn nil, fmt.Errorf(\"Not support on windons\")\n}", "func (s stage) mapFilesToFilesystems(config types.Config) (map[types.Filesystem][]types.File, error) {\n\tfiles := map[string][]types.File{}\n\tfor _, f := range config.Storage.Files {\n\t\tfiles[f.Filesystem] = append(files[f.Filesystem], f)\n\t}\n\n\tfilesystems := map[string]types.Filesystem{}\n\tfor _, fs := range config.Storage.Filesystems {\n\t\tfilesystems[fs.Name] = fs\n\t}\n\n\tfileMap := map[types.Filesystem][]types.File{}\n\tfor fsn, f := range files {\n\t\tif fs, ok := filesystems[fsn]; ok {\n\t\t\tfileMap[fs] = append(fileMap[fs], f...)\n\t\t} else {\n\t\t\ts.Logger.Crit(\"the filesystem (%q), was not defined\", fsn)\n\t\t\treturn nil, ErrFilesystemUndefined\n\t\t}\n\t}\n\n\treturn fileMap, nil\n}", "func mapF(filename string, contents string) []mapreduce.KeyValue {\n\t// Your code here (Part II).\n\tvar kvs []mapreduce.KeyValue\n\tvar letterContents bytes.Buffer\n\tfor _, r := range contents {\n\t\tif ok := unicode.IsLetter(r); ok {\n\t\t\tletterContents.WriteRune(r)\n\t\t} else {\n\t\t\tletterContents.WriteRune(' ')\n\t\t}\n\t}\n\twords := strings.Fields(letterContents.String())\n\tfor _, w := range words {\n\t\tkv := mapreduce.KeyValue{w, \"\"}\n\t\tkvs = append(kvs, kv)\n\t}\n\treturn kvs\n}", "func mapToConfig(cfgMap map[string]interface{}) (*FSConfig, error) {\n\tif cfgMap == nil {\n\t\treturn DefaultFSConfig(), nil\n\t}\n\tcfg := &FSConfig{}\n\tif err := mapstructure.Decode(cfgMap, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func newStaticFilesMap(files ...string) staticFilesMap {\n\tm := staticFilesMap(make(map[string]struct{}, len(files)))\n\tfor _, k := range files {\n\t\tm[k] = struct{}{}\n\t}\n\treturn m\n}", "func As(ar *txtar.Archive) fs.FS {\n\tm := make(mapfs.MapFS, len(ar.Files))\n\tfor _, f := range ar.Files {\n\t\tm[f.Name] = &mapfs.MapFile{\n\t\t\tData: f.Data,\n\t\t\t// TODO: maybe ModTime: time.Now(),\n\t\t\tSys: f,\n\t\t}\n\t}\n\tm.ChmodAll(0666)\n\treturn m\n}", "func NewMapDisk(ctx context.Context, wg *sync.WaitGroup) *MapDisk {\n\tmd := &MapDisk{\n\t\tstore: make(map[string][]byte),\n\t\tinChan: make(chan Request),\n\t}\n\twg.Add(1)\n\tgo md.serve(ctx, wg)\n\treturn md\n}", "func InMemoryFS(files map[string]string) fs.GlobFS {\n\treturn &inMemoryBundle{files: files}\n}", "func LoadMap(baseURLs []string, URI string) (map[string]interface{}, error) {\n\tURI = strings.TrimSpace(URI)\n\tURIs := getURIa(URI)\n\tmainAssetURI := URIs[0]\n\trawContent := \"\"\n\tresource, err := LoadResourceFromBaseURLs(baseURLs, mainAssetURI, &rawContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatched, err := expandMapWithArgumentsIfMatched(baseURLs, URIs, resource, rawContent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result map[string]interface{}\n\tif matched != nil {\n\t\tresult = toolbox.AsMap(matched)\n\t}\n\n\tif len(result) == 0 {\n\t\tresult = make(map[string]interface{})\n\t\tif resource, err = LoadResourceFromBaseURLs(baseURLs, mainAssetURI, &result); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(URIs) > 1 {\n\t\tif normalized, err := NormalizeMap(result, true); err == nil {\n\t\t\tresult = normalized\n\t\t}\n\t}\n\n\tfor i := 1; i < len(URIs); i++ {\n\t\tvar aMap = data.NewMap()\n\t\tif resource, err = LoadResourceFromBaseURLs(baseURLs, URIs[i], &aMap); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tudf.Register(aMap)\n\t\tresult = toolbox.AsMap(aMap.Expand(result))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, has := result[\"AssetURL\"]; !has {\n\t\tresult[\"AssetURL\"] = resource.URL\n\t}\n\n\treturn result, nil\n}", "func newBlockMapFile(blkSize uint64, regFile regularFile) (*blockMapFile, error) {\n\tfile := &blockMapFile{regFile: regFile}\n\tfile.regFile.impl = file\n\n\ttoFill := uint64(12)\n\tblksUsed := regFile.blksUsed(blkSize)\n\tif blksUsed < toFill {\n\t\ttoFill = blksUsed\n\t}\n\n\tblkMap := regFile.inode.diskInode.Data()\n\tfile.fileToPhysBlks = make([]uint32, toFill)\n\tfor i := uint64(0); i < toFill; i++ {\n\t\tbinary.Unmarshal(blkMap[i*4:(i+1)*4], binary.LittleEndian, &file.fileToPhysBlks[i])\n\t}\n\treturn file, nil\n}", "func NewProblemFilesFromMap(\n\tcontents map[string]string,\n\tname string,\n) ProblemFiles {\n\tf := &inMemoryProblemFiles{\n\t\tcontents: contents,\n\t\tname: name,\n\t}\n\tfor path := range contents {\n\t\tf.files = append(f.files, path)\n\t}\n\tsort.Strings(f.files)\n\treturn f\n}", "func RunMapTask(req Task, namenodeID string) {\n\n\ttempFileDir := Config.LocalfileDir + \"/\" + Config.TempFile\n\n\tfor _, fileName := range req.FileList {\n\t\tfmt.Printf(\"Start Map Task for File %s\\n\", fileName)\n\n\t\t//Fetch SDFSfile to local file system\n\t\tGetFile([]string{fileName, fileName})\n\n\t\t//Scan file\n\t\tdecodedFileName := Config.DecodeFileName(fileName)\n\t\t\n\t\tdata, err := os.Open(Config.LocalfileDir + \"/\" + decodedFileName)\n\t\tdefer data.Close()\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Datanode.RunMapTask: src_file %s os.Open() error\\n\", decodedFileName)\n\t\t\tlog.Println(\"os.Open() error\")\n\t\t\treturn\n\t\t}\n\n\t\tvar scanner = bufio.NewScanner(data)\n\n\t\tvar lineCnt = 0\n\t\tvar buf = \"\"\n\n\t\tfor scanner.Scan() {\n\t\t\t//Deal with EOF\n\t\t\tif lineCnt < 10 {\n\t\t\t\tbuf += scanner.Text() + \"\\n\"\n\t\t\t\tlineCnt++\n\t\t\t} else {\n\t\t\t\t// MapFunc(req.TaskExe)\n\t\t\t\ttemp, err := os.Create(tempFileDir)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Datanode.RunMapTask.Scanner: os.Create() error\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t_, err = temp.WriteString(buf)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Datanode.RunMapTask: temp_file WriteString error\")\n\t\t\t\t\tlog.Println(\"temp_file WriteString error\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\ttemp.Close()\n\n\t\t\t\tcmd := exec.Command(Config.LocalfileDir+\"/\"+req.TaskExe, tempFileDir)\n\t\t\t\tres, err := cmd.Output()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Datanode.RunMapTask: exec.Command.Output Error\")\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tparseMapRes(res, req.Output)\n\n\t\t\t\tlineCnt = 0\n\t\t\t\tbuf = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif lineCnt != 0 {\n\t\t\ttemp, err := os.Create(tempFileDir)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"os.Create() error\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t_, err = temp.WriteString(buf)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Datanode.RunMapTask: temp_file WriteString error\")\n\t\t\t\tlog.Println(\"temp_file WriteString error\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcmd := exec.Command(Config.LocalfileDir+\"/\"+req.TaskExe, tempFileDir)\n\t\t\tres, err := cmd.Output()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Datanode.RunMapTask: exec.Command.Output Error\")\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparseMapRes(res, req.Output)\n\t\t}\n\n\t\tos.Remove(Config.LocalfileDir + \"/\" + decodedFileName)\n\t}\n\n\tos.Remove(tempFileDir)\n\n\tfmt.Printf(\"Map Task %d succeed!\\n\", req.TaskID)\n\n\t//When finish work, RPC namanode\n\taddr := Config.GetIPAddressFromID(namenodeID)\n\tclient := NewClient(addr + \":\" + Config.NamenodePort)\n\tclient.Dial()\n\n\tvar res int\n\tif err := client.rpcClient.Call(\"Namenode.SendWorkerFinishMsg\", Mem.LocalID, &res); err != nil {\n\t\tfmt.Println(\"Datanode.RPC.Namenode.SendWorkerFinishMsg() error\")\n\t}\n\n\tclient.Close()\n\n\treturn\n}", "func (t *LineTable) initFileMap() {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tif t.fileMap != nil {\n\t\treturn\n\t}\n\tm := make(map[string]uint32)\n\n\tif t.version == ver12 {\n\t\tfor i := uint32(1); i < t.nfiletab; i++ {\n\t\t\ts := t.string(t.binary.Uint32(t.filetab[4*i:]))\n\t\t\tm[s] = i\n\t\t}\n\t} else {\n\t\tvar pos uint32\n\t\tfor i := uint32(0); i < t.nfiletab; i++ {\n\t\t\ts := t.stringFrom(t.filetab, pos)\n\t\t\tm[s] = pos\n\t\t\tpos += uint32(len(s) + 1)\n\t\t}\n\t}\n\tt.fileMap = m\n}", "func MapFromFile(path string)(mapData map[string]map[string]string, err error){\n var mapFile = make(map[string]map[string]string)\n var validID = regexp.MustCompile(`sid:(\\d+);`)\n var enablefield = regexp.MustCompile(`^#`)\n \n file, err := os.Open(path)\n if err != nil {\n logs.Error(\"Openning File for export to map: \"+ err.Error())\n return nil, err\n }\n \n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n sid := validID.FindStringSubmatch(scanner.Text())\n if sid != nil {\n lineData := make(map[string]string)\n if enablefield.MatchString(scanner.Text()){\n lineData[\"Enabled\"]=\"Disabled\"\n }else{\n lineData[\"Enabled\"]=\"Enabled\"\n }\n lineData[\"Line\"] = scanner.Text()\n mapFile[sid[1]] = lineData\n }\n }\n return mapFile, nil\n}", "func RunMapStorageTests(t *testing.T, storageFactory MapStorageFactory) {\n\tctx := context.Background()\n\tfor name, f := range mapTestFunctions(t, &mapTests{}) {\n\t\tms, as := storageFactory(ctx, t)\n\t\tt.Run(name, func(t *testing.T) { f(ctx, t, ms, as) })\n\t}\n}", "func MakeFsInMemory() FileSystem { return filesys.MakeFsInMemory() }", "func NewFS(cfgMap map[string]interface{}, opts ...Option) (qfs.Filesystem, error) {\n\tcfg, err := mapToConfig(cfgMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(cfg)\n\t}\n\n\treturn &FS{cfg: cfg}, nil\n}", "func funcMap(i *funcMapInput) template.FuncMap {\n\tvar scratch Scratch\n\n\tr := template.FuncMap{\n\t\t// API functions\n\t\t\"datacenters\": datacentersFunc(i.brain, i.used, i.missing),\n\t\t\"file\": fileFunc(i.brain, i.used, i.missing, i.sandboxPath),\n\t\t\"key\": keyFunc(i.brain, i.used, i.missing),\n\t\t\"keyExists\": keyExistsFunc(i.brain, i.used, i.missing),\n\t\t\"keyOrDefault\": keyWithDefaultFunc(i.brain, i.used, i.missing),\n\t\t\"ls\": lsFunc(i.brain, i.used, i.missing, true),\n\t\t\"safeLs\": safeLsFunc(i.brain, i.used, i.missing),\n\t\t\"node\": nodeFunc(i.brain, i.used, i.missing),\n\t\t\"nodes\": nodesFunc(i.brain, i.used, i.missing),\n\t\t\"secret\": secretFunc(i.brain, i.used, i.missing),\n\t\t\"secrets\": secretsFunc(i.brain, i.used, i.missing),\n\t\t\"service\": serviceFunc(i.brain, i.used, i.missing),\n\t\t\"services\": servicesFunc(i.brain, i.used, i.missing),\n\t\t\"tree\": treeFunc(i.brain, i.used, i.missing, true),\n\t\t\"safeTree\": safeTreeFunc(i.brain, i.used, i.missing),\n\n\t\t// Scratch\n\t\t\"scratch\": func() *Scratch { return &scratch },\n\n\t\t// Helper functions\n\t\t\"base64Decode\": base64Decode,\n\t\t\"base64Encode\": base64Encode,\n\t\t\"base64URLDecode\": base64URLDecode,\n\t\t\"base64URLEncode\": base64URLEncode,\n\t\t\"byKey\": byKey,\n\t\t\"byTag\": byTag,\n\t\t\"contains\": contains,\n\t\t\"containsAll\": containsSomeFunc(true, true),\n\t\t\"containsAny\": containsSomeFunc(false, false),\n\t\t\"containsNone\": containsSomeFunc(true, false),\n\t\t\"containsNotAll\": containsSomeFunc(false, true),\n\t\t\"env\": envFunc(i.env),\n\t\t\"executeTemplate\": executeTemplateFunc(i.t),\n\t\t\"explode\": explode,\n\t\t\"explodeMap\": explodeMap,\n\t\t\"in\": in,\n\t\t\"indent\": indent,\n\t\t\"loop\": loop,\n\t\t\"join\": join,\n\t\t\"trimSpace\": trimSpace,\n\t\t\"parseBool\": parseBool,\n\t\t\"parseFloat\": parseFloat,\n\t\t\"parseInt\": parseInt,\n\t\t\"parseJSON\": parseJSON,\n\t\t\"parseUint\": parseUint,\n\t\t\"plugin\": plugin,\n\t\t\"regexReplaceAll\": regexReplaceAll,\n\t\t\"regexMatch\": regexMatch,\n\t\t\"replaceAll\": replaceAll,\n\t\t\"timestamp\": timestamp,\n\t\t\"toLower\": toLower,\n\t\t\"toJSON\": toJSON,\n\t\t\"toJSONPretty\": toJSONPretty,\n\t\t\"toTitle\": toTitle,\n\t\t\"toTOML\": toTOML,\n\t\t\"toUpper\": toUpper,\n\t\t\"toYAML\": toYAML,\n\t\t\"split\": split,\n\t\t\"byMeta\": byMeta,\n\t\t\"sockaddr\": sockaddr,\n\t\t// Math functions\n\t\t\"add\": add,\n\t\t\"subtract\": subtract,\n\t\t\"multiply\": multiply,\n\t\t\"divide\": divide,\n\t\t\"modulo\": modulo,\n\t}\n\n\tfor _, bf := range i.functionBlacklist {\n\t\tif _, ok := r[bf]; ok {\n\t\t\tr[bf] = blacklisted\n\t\t}\n\t}\n\n\treturn r\n}", "func Map(mapf func(string, string) []KeyValue, mapTask Task, NReducer int) {\n\tencs := make([]*json.Encoder, NReducer)\n\tfs := make([]*os.File, NReducer)\n\n\tfor i := 0; i < NReducer; i++ {\n\t\toname := fmt.Sprintf(\"mr-%v-%v.json\", mapTask.Index, i)\n\t\tf, err := os.Create(oname)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Cannot open file %v\", oname)\n\t\t}\n\t\tenc := json.NewEncoder(f)\n\t\tfs[i] = f\n\t\tencs[i] = enc\n\t}\n\n\tfile, err := os.Open(mapTask.FilePath)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot open %v\", mapTask.FilePath)\n\t}\n\tcontent, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot read %v\", mapTask.FilePath)\n\t}\n\n\tkva := mapf(mapTask.FilePath, string(content))\n\n\tfor _, kv := range kva {\n\t\tid := ihash(kv.Key) % NReducer\n\t\tenc := encs[id]\n\t\terr := enc.Encode(&kv)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Cannot encode Key-Value pair %v\", kv)\n\t\t}\n\t}\n\tfor i := 0; i < NReducer; i++ {\n\t\tfs[i].Close()\n\t}\n\n}", "func (h *OperationHandler) createMapFile(uri []string, ops []*model.Operation) (string, error) {\n\tmapFile := models.CreateMapFile(uri, ops)\n\n\treturn h.writeModelToCAS(mapFile, \"map\")\n}", "func NewMockFS() *MockFS {\n\treturn &MockFS{\n\t\tFiles: map[string]MockFile{},\n\t}\n}", "func mapFile(file *os.File) mmap.MMap {\n\tmemoryMappedFile, err := mmap.Map(file, mmap.RDWR, 0)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error mapping: %s\", err))\n\t}\n\treturn memoryMappedFile\n}", "func NewFileSystem(token string, debug bool) *FileSystem {\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\tclient := putio.NewClient(oauthClient)\n\tclient.UserAgent = defaultUserAgent\n\n\treturn &FileSystem{\n\t\tputio: client,\n\t\tlogger: NewLogger(\"putiofs: \", debug),\n\t}\n}", "func OptionsMap(conf FileScopedOptions) map[string]string {\n\treturn map[string]string{\n\t\tConfigToken.String(): conf.Token,\n\t\tConfigAPIHost.String(): conf.APIHost,\n\t\tConfigDashboardHost.String(): conf.DashboardHost,\n\t\tConfigVerifyTLS.String(): conf.VerifyTLS,\n\t\tConfigEnclaveProject.String(): conf.EnclaveProject,\n\t\tConfigEnclaveConfig.String(): conf.EnclaveConfig,\n\t}\n}", "func NewFileMap(filename string) (*FileMap, error) {\n\tbufb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := string(bufb)\n\tfm := FileMap{\n\t\tFilename: filename,\n\t\tText: buf,\n\t\tCheckText: createCheckText(buf),\n\t\tLines: make([]lineEntry, 0, (len(buf)/32)+1),\n\t}\n\n\t// create lines\n\tbegin := 0\n\tfor idx, run := range fm.Text {\n\t\tif unicode.IsSpace(run) && string(run) == \"\\n\" {\n\t\t\tend := idx\n\t\t\tfm.Lines = append(fm.Lines, lineEntry{begin, end})\n\t\t\tbegin = end + 1\n\t\t}\n\t}\n\n\t// Anything left?\n\tend := len(fm.Text)\n\tif begin <= end {\n\t\tfm.Lines = append(fm.Lines, lineEntry{begin, end})\n\t}\n\n\treturn &fm, nil\n}", "func (s InputSecureFileClassArray) InputSecureFileToMap() map[int64]*InputSecureFile {\n\tr := make(map[int64]*InputSecureFile, len(s))\n\ts.FillInputSecureFileMap(r)\n\treturn r\n}", "func ServiceMap(dir string) map[flux.ResourceID][]string {\n\treturn map[flux.ResourceID][]string{\n\t\tflux.MustParseResourceID(\"default:deployment/helloworld\"): []string{filepath.Join(dir, \"helloworld-deploy.yaml\")},\n\t\tflux.MustParseResourceID(\"default:deployment/locked-service\"): []string{filepath.Join(dir, \"locked-service-deploy.yaml\")},\n\t\tflux.MustParseResourceID(\"default:deployment/test-service\"): []string{filepath.Join(dir, \"test-service-deploy.yaml\")},\n\t}\n}", "func funcMap() template.FuncMap {\n\tr := sprig.TxtFuncMap()\n\n\tl := template.FuncMap{\n\t\t\"fileContents\": fileContents(),\n\t}\n\n\tfor k, v := range l {\n\t\tif _, ok := r[k]; ok {\n\t\t\tk = \"c_\" + k\n\t\t}\n\t\tr[k] = v\n\t}\n\n\treturn r\n}", "func newTestFileSystemWithFile(name string) (*FileNode, *FileSystem, error) {\n\tdir := testDir(name)\n\tfs := newTestFileSystem(dir)\n\tsp := modules.RandomSiaPath()\n\tfs.addTestSiaFile(sp)\n\tsf, err := fs.OpenSiaFile(sp)\n\treturn sf, fs, err\n}", "func expandInstanceFileSharesMap(c *Client, f map[string]InstanceFileShares) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandInstanceFileShares(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func execNewMap(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewMap(args[0].(types.Type), args[1].(types.Type))\n\tp.Ret(2, ret)\n}", "func newFsStore(root string) Backend {\n\treturn &fsStore{\n\t\troot: root,\n\t\tkinds: map[string]bool{},\n\t\tcheckDuration: defaultDuration,\n\t\tdata: map[Key]*resource{},\n\t\tdonec: make(chan struct{}),\n\t\tProbe: probe.NewProbe(),\n\t}\n}", "func (g *Groker) Map() error {\n\n\tfiles, err := g.Arguments.grokfiles()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tfor _, filename := range files {\n\t\tfh, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tsplitFh := bytes.Split(fh, []byte{'\\n'})\n\n\t\tfor _, line := range splitFh {\n\t\t\trgroups := g.FileloadingPattern.FindStringSubmatch(string(line))\n\n\t\t\tif len(rgroups) > 0 {\n\t\t\t\tg.LookupDict[rgroups[grokNameIndex]] = rgroups[grokValueIndex]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *FileMap) init(skipPath string, excludedExt []string) {\n\tp.files = make(map[string]string)\n\tp.skipPath = skipPath\n\tp.excludedExt = excludedExt\n}", "func NewFS(fsys fs.FS) (*KeyStore, error) {\n\tks := KeyStore{\n\t\tstore: make(map[string]*rsa.PrivateKey),\n\t}\n\n\tfn := func(fileName string, dirEntry fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"walkdir failure\")\n\t\t}\n\n\t\tif dirEntry.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif path.Ext(fileName) != \".pem\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tfile, err := fsys.Open(fileName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"opening key file\")\n\t\t}\n\t\tdefer file.Close()\n\n\t\tprivatePEM, err := io.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"reading auth private key\")\n\t\t}\n\n\t\tprivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privatePEM)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"parsing auth private key\")\n\t\t}\n\n\t\tks.store[strings.TrimSuffix(dirEntry.Name(), \".pem\")] = privateKey\n\t\treturn nil\n\t}\n\n\tif err := fs.WalkDir(fsys, \".\", fn); err != nil {\n\t\treturn nil, errors.Wrap(err, \"walking directory\")\n\t}\n\n\treturn &ks, nil\n}", "func TestFS(fsys writefs.WriteFS) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tdirs := []string{\n\t\t\t\"dir1\",\n\t\t\t\"dir1/dirsub1\",\n\t\t\t\"dirempty\",\n\t\t}\n\t\tfiles := []string{\n\t\t\t\"dir1/file1\",\n\t\t\t\"dir1/file2\",\n\t\t\t\"dir1/dirsub1/file3\",\n\t\t}\n\n\t\tt.Run(\"initialize testing FS\", func(t *testing.T) {\n\t\t\tfor _, dir := range dirs {\n\t\t\t\terr := writefs.MkDir(fsys, dir, fs.FileMode(0755))\n\t\t\t\t//if !(err == nil || errors.Is(err, fs.ErrExist)) {\n\t\t\t\t//\tfmt.Println(err, dir)\n\t\t\t\t//}\n\t\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\n\t\t\t}\n\n\t\t\tfor _, file := range files {\n\t\t\t\tfake := []byte(file + \" content\\n\")\n\t\t\t\tn, err := writefs.WriteFile(fsys, file, fake)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(fake), n)\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"pass TestFS\", func(t *testing.T) {\n\t\t\terr := fstest.TestFS(fsys, append(files, dirs...)...)\n\t\t\tassert.NoError(t, err)\n\t\t})\n\n\t\tdirExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.True(t, info.IsDir())\n\t\t\t}\n\t\t}\n\n\t\tfileExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.True(t, info.Mode().IsRegular())\n\t\t\t}\n\t\t}\n\n\t\tfileNotExists := func(t *testing.T, dir string) {\n\t\t\tinfo, err := fs.Stat(fsys, dir)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\t\t\tassert.Nil(t, info)\n\t\t}\n\n\t\tcheckDirCreated := func(t *testing.T, dir string) {\n\t\t\tfileNotExists(t, dir)\n\n\t\t\terr := writefs.Remove(fsys, dir)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrNotExist))\n\n\t\t\tf, err := writefs.OpenFile(fsys, dir, os.O_CREATE, fs.FileMode(0755)|fs.ModeDir)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tdirExists(t, dir)\n\t\t}\n\t\tdirRemove := func(t *testing.T, dir string) {\n\t\t\tf, _ := writefs.OpenFile(fsys, dir, os.O_TRUNC, 0)\n\t\t\tassert.Nil(t, f)\n\t\t\tfileNotExists(t, dir)\n\t\t}\n\t\tcheckDirRemoved := func(t *testing.T, dir string) {\n\t\t\terr := writefs.MkDir(fsys, dir, fs.FileMode(0755))\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\tdirExists(t, dir)\n\n\t\t\tf, err := writefs.OpenFile(fsys, dir, os.O_TRUNC, 0)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tfileNotExists(t, dir)\n\t\t}\n\t\tt.Run(\"creates directories with OpenFile - nested and not recursively\", func(t *testing.T) {\n\t\t\tdirRemove(t, \"dir1/adir/nested\")\n\t\t\tdirRemove(t, \"dir1/adir\")\n\n\t\t\t// nested dir return error\n\t\t\tf, err := writefs.OpenFile(fsys, \"dir1/adir/nested\", os.O_CREATE, fs.FileMode(0755)|fs.ModeDir)\n\t\t\tassert.Error(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\n\t\t\tcheckDirCreated(t, \"dir1/adir\")\n\t\t\tcheckDirCreated(t, \"dir1/adir/nested\")\n\t\t})\n\n\t\tt.Run(\"OpenFile return *PathError on bad paths\", func(t *testing.T) {\n\t\t\tcheckBadPath(t, \"afilename\", \"OpenFile\", func(name string) error {\n\t\t\t\t_, err := writefs.OpenFile(fsys, name, 0, 0)\n\t\t\t\treturn err\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"remove files with OpenFile\", func(t *testing.T) {\n\t\t\tfile := \"dir1/somenewfile\"\n\t\t\t_, err := writefs.WriteFile(fsys, file, []byte(file))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_TRUNC, 0)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Nil(t, f)\n\n\t\t\tfileNotExists(t, file)\n\t\t})\n\n\t\tt.Run(\"remove directories with OpenFile - nested and not recursively\", func(t *testing.T) {\n\t\t\t// non empty dir return error\n\t\t\tf, err := writefs.OpenFile(fsys, \"dir1/adir\", os.O_TRUNC, 0)\n\t\t\tassert.Error(t, err)\n\t\t\tassert.Nil(t, f)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrInvalid))\n\t\t\t//assert.True(t, errors.Is(err, &fs.PathError{}))\n\n\t\t\tcheckDirRemoved(t, \"dir1/adir/nested\")\n\t\t\tcheckDirRemoved(t, \"dir1/adir\")\n\t\t})\n\t\tt.Run(\"create and write on new files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrNotExist))\n\t\t\tfileNotExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_CREATE|os.O_WRONLY, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"ciao\\n\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"set modtime to now\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"set content\", func(t *testing.T) {\n\t\t\t\tbuf := []byte(\"ciao\\n\")\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, buf, actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"write on existing files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"update content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"miao\\n\"), actual)\n\t\t\t})\n\t\t})\n\t\tt.Run(\"write on existing files truncating\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY|os.O_TRUNC, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"set content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"mi\"), actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"appending to existing files\", func(t *testing.T) {\n\t\t\tfile := \"dir1/file1new\"\n\t\t\terr := writefs.Remove(fsys, file)\n\t\t\tassert.True(t, err == nil || errors.Is(err, fs.ErrExist))\n\t\t\t_, err = writefs.WriteFile(fsys, file, []byte(\"ciao\\n\"))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tfileExists(t, file)\n\n\t\t\tf, err := writefs.OpenFile(fsys, file, os.O_WRONLY|os.O_APPEND, fs.FileMode(0644))\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.NotNil(t, f)\n\t\t\t\tbuf := []byte(\"mi\")\n\t\t\t\tn, err := f.Write(buf)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, len(buf), n)\n\t\t\t\terr = f.Close()\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\n\t\t\tt.Run(\"updates modtime\", func(t *testing.T) {\n\t\t\t\tinfo, err := fs.Stat(fsys, file)\n\t\t\t\tif assert.NoError(t, err) {\n\t\t\t\t\tassert.Less(t, time.Now().Sub(info.ModTime()), time.Second)\n\t\t\t\t}\n\t\t\t})\n\t\t\tt.Run(\"updates content\", func(t *testing.T) {\n\t\t\t\tactual, err := fs.ReadFile(fsys, file)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, []byte(\"ciao\\nmi\"), actual)\n\t\t\t})\n\t\t})\n\n\t\tt.Run(\"opening non existing files\", func(t *testing.T) {\n\t\t\tf, err := writefs.OpenFile(fsys, \"unkfile\", os.O_WRONLY, fs.FileMode(0644))\n\t\t\tassert.Error(t, err)\n\t\t\tassert.True(t, errors.Is(err, fs.ErrNotExist))\n\t\t\tassert.Nil(t, f)\n\t\t})\n\t\t/*\n\t\t\tt.Run(\"opening read-only files for write\", func(t *testing.T) {\n\t\t\t\tf, err := writefs.OpenFile(fsys,\"/etc/passwd\", os.O_WRONLY, fs.FileMode(0644))\n\t\t\t\tassert.Error(t, err)\n\t\t\t\tassert.Nil(t, f)\n\t\t\t})\n\t\t*/\n\t}\n}", "func mapPaths(fs afero.Fs, paths []string, f func(afero.Fs, string) (*PackageFilesDigest, error)) []*PackageFilesDigest {\n\tops := make([]*PackageFilesDigest, 0)\n\tfor _, path := range paths {\n\t\top, err := f(fs, path)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"WARNING: operator: %v is invalid\", path)\n\t\t\tcontinue\n\t\t}\n\t\tops = append(ops, op)\n\t}\n\n\treturn ops\n}", "func TestNew(t *testing.T) {\n\tif testing.Short() && !build.VLONG {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\t// Create filesystem.\n\troot := filepath.Join(testDir(t.Name()), \"fs-root\")\n\tfs := newTestFileSystem(root)\n\t// Check fields.\n\tif fs.parent != nil {\n\t\tt.Fatalf(\"fs.parent shoud be 'nil' but wasn't\")\n\t}\n\tif *fs.name != \"\" {\n\t\tt.Fatalf(\"fs.staticName should be %v but was %v\", \"\", *fs.name)\n\t}\n\tif *fs.path != root {\n\t\tt.Fatalf(\"fs.path should be %v but was %v\", root, *fs.path)\n\t}\n\tif fs.threads == nil || len(fs.threads) != 0 {\n\t\tt.Fatal(\"fs.threads is not an empty initialized map\")\n\t}\n\tif fs.threadUID != 0 {\n\t\tt.Fatalf(\"fs.threadUID should be 0 but was %v\", fs.threadUID)\n\t}\n\tif fs.directories == nil || len(fs.directories) != 0 {\n\t\tt.Fatal(\"fs.directories is not an empty initialized map\")\n\t}\n\tif fs.files == nil || len(fs.files) != 0 {\n\t\tt.Fatal(\"fs.files is not an empty initialized map\")\n\t}\n\t// Create the filesystem again at the same location.\n\t_ = newTestFileSystem(*fs.path)\n}", "func MakeMap(kt *types.T, kvs ...T) *Map {\n\tif len(kvs)%2 != 0 {\n\t\tpanic(\"uneven makemap\")\n\t}\n\tm := new(Map)\n\tfor i := 0; i < len(kvs); i += 2 {\n\t\tm.Insert(Digest(kvs[i], kt), kvs[i], kvs[i+1])\n\t}\n\treturn m\n}", "func (DummyStore) SetMap(key string, value map[string]interface{}) error {\n\treturn nil\n}", "func TestTypeMap(t *testing.T) {\n\tL := Init()\n\tdefer L.Close()\n\n\tm := map[string]string{\"test\": \"art\"}\n\n\tRegister(L, \"\", Map{\n\t\t\"m\": m,\n\t})\n\n\tconst code = `assert(m.test == 'art')\nassert(m.Test == nil)`\n\n\t// Accessing map with wrong key type must fail.\n\tconst code2 = `_=m[5]`\n\n\terr := L.DoString(code)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func readFromFS(paths []string) (map[string][]byte, error) {\n\tvar err error\n\tresult := make(map[string][]byte)\n\tfor _, path := range paths {\n\t\tfsRegistryMu.Lock()\n\t\tfs, ok := fsRegistry[path]\n\t\tif !ok {\n\t\t\tfs, err = newFS(path)\n\t\t\tif err != nil {\n\t\t\t\tfsRegistryMu.Unlock()\n\t\t\t\treturn nil, fmt.Errorf(\"error while parsing path %q: %w\", path, err)\n\t\t\t}\n\t\t\tif err := fs.Init(); err != nil {\n\t\t\t\tfsRegistryMu.Unlock()\n\t\t\t\treturn nil, fmt.Errorf(\"error while initializing path %q: %w\", path, err)\n\t\t\t}\n\t\t\tfsRegistry[path] = fs\n\t\t}\n\t\tfsRegistryMu.Unlock()\n\n\t\tlist, err := fs.List()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to list files from %q\", fs)\n\t\t}\n\n\t\tcLogger.Infof(\"found %d files to read from %q\", len(list), fs)\n\n\t\tif len(list) < 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tts := time.Now()\n\t\tfiles, err := fs.Read(list)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while reading files from %q: %w\", fs, err)\n\t\t}\n\t\tcLogger.Infof(\"finished reading %d files in %v from %q\", len(list), time.Since(ts), fs)\n\n\t\tfor k, v := range files {\n\t\t\tif _, ok := result[k]; ok {\n\t\t\t\treturn nil, fmt.Errorf(\"duplicate found for file name %q: file names must be unique\", k)\n\t\t\t}\n\t\t\tresult[k] = v\n\t\t}\n\t}\n\treturn result, nil\n}", "func (p EntPackage) Map(mapName string, rootDirs ...string) EntPackage {\n\tp.maps[mapName] = map[string]airfreight.Ent{}\n\tfor _, rootDir := range rootDirs {\n\t\tmapDir(p.maps[mapName], rootDir, \"\")\n\t}\n\treturn p\n}", "func TestFS(t *testing.T) {\n\ttempDir, err := ioutil.TempDir(\"\", \"kivik.test.\")\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create temp dir to test FS driver: %s\\n\", err)\n\t\treturn\n\t}\n\tos.RemoveAll(tempDir) // So the driver can re-create it as desired\n\tdefer os.RemoveAll(tempDir) // To clean up after tests\n\tclient, err := kivik.New(context.Background(), \"fs\", tempDir)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to connect to FS driver: %s\\n\", err)\n\t\treturn\n\t}\n\tclients := &kt.Context{\n\t\tRW: true,\n\t\tAdmin: client,\n\t}\n\tkiviktest.RunTestsInternal(clients, kiviktest.SuiteKivikFS, t)\n}", "func (s InputSecureFileArray) FillMap(to map[int64]InputSecureFile) {\n\tfor _, value := range s {\n\t\tto[value.GetID()] = value\n\t}\n}", "func ConfigMapFromTestFile(t *testing.T, name string, allowed ...string) *corev1.ConfigMap {\n\tt.Helper()\n\n\tb, err := ioutil.ReadFile(fmt.Sprintf(\"testdata/%s.yaml\", name))\n\tif err != nil {\n\t\tt.Fatalf(\"ReadFile() = %v\", err)\n\t}\n\n\tvar cm corev1.ConfigMap\n\n\t// Use github.com/ghodss/yaml since it reads json struct\n\t// tags so things unmarshal properly\n\tif err := yaml.Unmarshal(b, &cm); err != nil {\n\t\tt.Fatalf(\"yaml.Unmarshal() = %v\", err)\n\t}\n\n\tif len(cm.Data) != len(allowed) {\n\t\t// See here for why we only check in empty ConfigMaps:\n\t\t// https://github.com/knative/serving/issues/2668\n\t\tt.Errorf(\"Data = %v, wanted allowed\", cm.Data)\n\t}\n\tallow := sets.NewString(allowed...)\n\tfor key := range cm.Data {\n\t\tif !allow.Has(key) {\n\t\t\tt.Errorf(\"Encountered key %q in %q that wasn't on the allowed list\", key, name)\n\t\t}\n\t}\n\n\t// If the ConfigMap has no data entries, then make sure we don't have\n\t// a `data:` key, or it will undo the whole motivation for leaving the\n\t// data empty: https://github.com/knative/serving/issues/2668\n\tif len(cm.Data) == 0 {\n\t\tvar u unstructured.Unstructured\n\t\tif err := yaml.Unmarshal(b, &u); err != nil {\n\t\t\tt.Errorf(\"yaml.Unmarshal(%q) = %v\", name, err)\n\t\t}\n\t\tif _, ok := u.Object[\"data\"]; ok {\n\t\t\tt.Errorf(\"%q should omit its empty `data:` section.\", name)\n\t\t}\n\t}\n\n\treturn &cm\n}", "func WriteFileMap(bs blobserver.StatReceiver, file *Builder, r io.Reader) (blob.Ref, error) {\n\treturn writeFileMapRolling(bs, file, r)\n}", "func expandImageRawDiskMap(c *Client, f map[string]ImageRawDisk) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandImageRawDisk(c, &item)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func InitMapStorage() *MapURLStorage {\n\treturn &MapURLStorage{\n\t\tStorage: make(map[string]string),\n\t}\n}", "func TestVfsSetup(t *testing.T) {\n\tgraphtest.GetDriver(t, \"vfs\")\n}", "func MapViewOfFile(hFileMappingObject HANDLE, dwDesiredAccess DWORD, dwFileOffsetHigh DWORD, dwFileOffsetLow DWORD, dwNumberOfBytesToMap SIZE_T) LPVOID {\n\tret1 := syscall6(mapViewOfFile, 5,\n\t\tuintptr(hFileMappingObject),\n\t\tuintptr(dwDesiredAccess),\n\t\tuintptr(dwFileOffsetHigh),\n\t\tuintptr(dwFileOffsetLow),\n\t\tuintptr(dwNumberOfBytesToMap),\n\t\t0)\n\treturn (LPVOID)(unsafe.Pointer(ret1))\n}", "func statikFS() http.Handler {\n\tstatikFS, err := fs.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn http.FileServer(statikFS)\n}", "func FSInfo(file string) (FSInfoData, error) {\n\tvar cinfo C.struct_ploop_info\n\tvar info FSInfoData\n\tcfile := C.CString(file)\n\tdefer cfree(cfile)\n\n\tret := C.ploop_get_info_by_descr(cfile, &cinfo)\n\tif ret == 0 {\n\t\tinfo.blocksize = uint64(cinfo.fs_bsize)\n\t\tinfo.blocks = uint64(cinfo.fs_blocks)\n\t\tinfo.blocks_free = uint64(cinfo.fs_bfree)\n\t\tinfo.inodes = uint64(cinfo.fs_inodes)\n\t\tinfo.inodes_free = uint64(cinfo.fs_ifree)\n\t}\n\n\treturn info, mkerr(ret)\n}", "func TestParseProcSmaps(t *testing.T) {\n\tfor _, tst := range smapsTest {\n\t\tf, err := ioutil.TempFile(\"\", \"process_stats_test\")\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unable to create tempory file : %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, err = f.WriteString(tst.data)\n\t\terr2 := f.Close()\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\t_ = os.RemoveAll(f.Name())\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unable to write to tempory file : %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err2 != nil {\n\t\t\t\tt.Errorf(\"Unable to close tempory file : %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmem := parseProcSmaps(f.Name())\n\t\t\tif mem != tst.res {\n\t\t\t\tt.Errorf(\"Incorrect value from parseProcSmaps. Expected %d found %d\",\n\t\t\t\t\tmem, tst.res)\n\t\t\t}\n\t\t}()\n\t}\n\n\tif parseProcSmaps(\"\") != -1 {\n\t\tt.Errorf(\"Expected parseProcSmaps to fail when passed invalid path\")\n\t}\n}", "func (wf WorldFile) FromMap(x float64, y float64) image.Point {\n\n\tdenom := (wf.A*wf.E - wf.D*wf.B)\n\n\tfx := (wf.E*x - wf.B*y + wf.B*wf.F - wf.E*wf.C) / denom\n\tfy := (-wf.D*x + wf.A*y + wf.D*wf.C - wf.A*wf.F) / denom\n\n\treturn image.Pt(round(fx), round(fy))\n}", "func TestNewFS(t *testing.T) {\n\t// Do not attempt to create this path, the test validates\n\t// so that NewFSObjectLayer initializes non existing paths\n\t// and successfully returns initialized object layer.\n\tdisk := filepath.Join(globalTestTmpDir, \"minio-\"+nextSuffix())\n\tdefer os.RemoveAll(disk)\n\n\t_, err := NewFSObjectLayer(\"\")\n\tif err != errInvalidArgument {\n\t\tt.Errorf(\"Expecting error invalid argument, got %s\", err)\n\t}\n\t_, err = NewFSObjectLayer(disk)\n\tif err != nil {\n\t\terrMsg := \"Unable to recognize backend format, Disk is not in FS format.\"\n\t\tif err.Error() == errMsg {\n\t\t\tt.Errorf(\"Expecting %s, got %s\", errMsg, err)\n\t\t}\n\t}\n}", "func Map(vs []string, f func(string) string) []string {\n\tvsm := make([]string, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = f(v)\n\t}\n\treturn vsm\n}", "func Map(vs []string, f func(string) string) []string {\n\tvsm := make([]string, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = f(v)\n\t}\n\treturn vsm\n}", "func Map(vs []string, f func(string) string) []string {\n\tvsm := make([]string, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = f(v)\n\t}\n\treturn vsm\n}", "func LoadSectorMap(diskbytes []byte) (SectorMap, error) {\n\tsm := SectorMap(make([]byte, 560))\n\tsector09, err := disk.ReadSector(diskbytes, 0, 9)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tsector0A, err := disk.ReadSector(diskbytes, 0, 0xA)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tsector0B, err := disk.ReadSector(diskbytes, 0, 0xB)\n\tif err != nil {\n\t\treturn sm, err\n\t}\n\tcopy(sm[0:0x30], sector09[0xd0:])\n\tcopy(sm[0x30:0x130], sector0A)\n\tcopy(sm[0x130:0x230], sector0B)\n\treturn sm, nil\n}", "func NewFilesystem(_ context.Context, cfgMap map[string]interface{}) (qfs.Filesystem, error) {\n\treturn NewFS(cfgMap)\n}", "func getServerFdMap() map[string]listenerFdMap {\n\tsfm := make(map[string]listenerFdMap)\n\tserverMapping.RLockFunc(func(m map[string]interface{}) {\n\t\tfor k, v := range m {\n\t\t\tsfm[k] = v.(*Server).getListenerFdMap()\n\t\t}\n\t})\n\treturn sfm\n}", "func mapfn(kvs ...interface{}) (map[string]interface{}, error) {\n\tif len(kvs)%2 != 0 {\n\t\treturn nil, errors.New(\"map requires even number of arguments.\")\n\t}\n\tm := make(map[string]interface{})\n\tfor i := 0; i < len(kvs); i += 2 {\n\t\ts, ok := kvs[i].(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"even args to map must be strings.\")\n\t\t}\n\t\tm[s] = kvs[i+1]\n\t}\n\treturn m, nil\n}", "func expandStoredInfoTypeDictionaryCloudStoragePathMap(c *Client, f map[string]StoredInfoTypeDictionaryCloudStoragePath, res *StoredInfoType) (map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := make(map[string]interface{})\n\tfor k, item := range f {\n\t\ti, err := expandStoredInfoTypeDictionaryCloudStoragePath(c, &item, res)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif i != nil {\n\t\t\titems[k] = i\n\t\t}\n\t}\n\n\treturn items, nil\n}", "func (ids *Storage) updateMap(key, action string) (string, error) {\n\tvar id string\n\tf, err := os.OpenFile(ids.fn, os.O_WRONLY|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Printf(\"Error opening the file %s: %v\\n\", ids.fn, err)\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\tswitch action {\n\tcase \"del\":\n\t\tdelete(ids.IDs, key)\n\tcase \"put\":\n\t\tid = fmt.Sprintf(\"%x\", md5.Sum([]byte(key)))\n\t\tids.IDs[id] = key\n\t}\n\ttmp, err := json.Marshal(ids.IDs)\n\tif err != nil {\n\t\tlog.Printf(\"Error Marshalling the map to json %s: %v\\n\", ids.IDs, err)\n\t\treturn \"\", err\n\t}\n\n\tn, err := f.Write(tmp)\n\tif err != nil {\n\t\tlog.Printf(\"Error writing in the file %s: %v\\n\", ids.fn, err)\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"Updated file %v, written %d bytes, err: %v\\n\", ids.fn, n, err)\n\treturn id, nil\n}", "func NewMmap(filename string, mode int) (*Mmap, error) {\n\tm := &Mmap{\n\t\tMmapBytes: make([]byte, 0),\n\t\tFileName: filename,\n\t}\n\n\tfileMode := os.O_RDWR\n\tfileCreateMode := os.O_RDWR | os.O_CREATE | os.O_TRUNC\n\tif mode == ModeCreate {\n\t\tfileMode = fileCreateMode\n\t}\n\tfile, err := os.OpenFile(filename, fileMode, 0664)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfileInfo, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.FileLen = fileInfo.Size()\n\tif mode == ModeCreate || m.FileLen == 0 {\n\t\tsyscall.Ftruncate(int(file.Fd()), m.FileLen+preAllocatedSpace)\n\t\tm.FileLen = m.FileLen + preAllocatedSpace\n\t}\n\tm.MmapBytes, err = syscall.Mmap(int(file.Fd()), 0, int(m.FileLen), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"mapping file error\")\n\t}\n\tm.FileHandler = file\n\treturn m, nil\n}", "func NewMemFs() FileSystem {\n\treturn &memFS{\n\t\tfiles: &hashmap.HashMap{},\n\t}\n}", "func wcMapF(filename string, contents string) []mapreduce.KeyValue {\n\t// TODO: you have to write this function\n\treturnKV := []mapreduce.KeyValue{}\n\n\tisValidStr := func(c rune) bool {\n\t\treturn !unicode.IsLetter(c) && !unicode.IsNumber(c)\n\t}\n\n\tstringArray := strings.FieldsFunc(contents, isValidStr)\n\tcontentsLen := len(stringArray)\n\n\tfor i:=0; i<contentsLen;i++ {\n\t\tcurrentWord := stringArray[i]\n\t\tisContains, location := sliceContains(returnKV, currentWord)\n\n\t\tif isContains{\n\t\t\ttmp, _ := strconv.Atoi(returnKV[location].Value)\n\t\t\treturnKV[location].Value = strconv.Itoa(tmp + 1)\n\t\t} else {\n\t\t\tnewPair := mapreduce.KeyValue{\n\t\t\t\tKey: currentWord,\n\t\t\t\tValue: \"1\"}\n\t\t\treturnKV = append(returnKV, newPair)\n\t\t}\n\t}\n\n\treturn returnKV\n}", "func TestMap(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\t// Create a new bucket.\n\tletters, err := bx.New([]byte(\"letters\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"alpha\")},\n\t\t{[]byte(\"B\"), []byte(\"beta\")},\n\t\t{[]byte(\"C\"), []byte(\"gamma\")},\n\t}\n\n\t// Insert items into `letters` bucket.\n\tif err := letters.Insert(items); err != nil {\n\t\tfmt.Println(\"could not insert items!\")\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to apply to each item in bucket.\n\t// Here, we're just going to collect the items just inserted.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\t// Now map the `do` function over each item.\n\tif err := letters.Map(do); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Finally, check to see if our results match the originally\n\t// inserted items.\n\tfor i, want := range items {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func writeMapFile(filename string, target interface{}) error {\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = toml.NewEncoder(f).Encode(target); err != nil {\n\t\treturn err\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TestMap() {\n\tm := NewMap(4, 3)\n\t\n\tm.Reset()\n\t\n\tif m.String() != `. . . \n. . . \n. . . \n. . . \n` {\n\t\tPanicf(\"map is wrong size, got `%s`\", m)\n\t}\n\t\n\tloc := m.FromRowCol(3, 2)\n\trow, col := m.FromLocation(loc)\n\t\n\tif row != 3 || col != 2 {\n\t\tPanicf(\"conversion broken, got (%v, %v), wanted (3, 2)\", row, col)\n\t}\n\t\n\tloc2 := m.FromRowCol(3, -1)\n\t\n\tif loc2 != loc {\n\t\tPanicf(\"from xy broken, got (%v), wanted (%v)\", loc2, loc)\n\t}\n\t\n\tn := m.FromRowCol(2, 2)\n\ts := m.FromRowCol(4, 2)\n\te := m.FromRowCol(3, 3)\n\tw := m.FromRowCol(3, 1)\n\t\n\tif n != m.Move(loc, North) {Panicf(\"Move north is broken\")}\n\tif s != m.Move(loc, South) {Panicf(\"Move south is broken\")}\n\tif e != m.Move(loc, East) {Panicf(\"Move east is broken\")}\n\tif w != m.Move(loc, West) {Panicf(\"Move west is broken\")}\n\t\n\tm.AddAnt(n, MY_ANT)\n\tm.AddAnt(s, MY_ANT)\n\t\n\tif m.String() != `. . a \n. . . \n. . a \n. . . \n` {\n\t\tPanicf(\"map put ants in wrong place, got `%s`\", m)\n\t}\n\t\n\tfmt.Println(\"TestMap PASS\")\n}", "func NewFS(dataDir string) Interface {\n\treturn &fsLoader{dataDir: dataDir}\n}", "func doMap(\njobName string, // the name of the MapReduce job\nmapTaskNumber int, // which map task this is\ninFile string,\nnReduce int, // the number of reduce task that will be run (\"R\" in the paper)\nmapF func(file string, contents string) []KeyValue,\n) {\n\t// TODO:\n\t// You will need to write this function.\n\t// You can find the filename for this map task's input to reduce task number\n\t// r using reduceName(jobName, mapTaskNumber, r). The ihash function (given\n\t// below doMap) should be used to decide which file a given key belongs into.\n\t//\n\t// The intermediate output of a map task is stored in the file\n\t// system as multiple files whose name indicates which map task produced\n\t// them, as well as which reduce task they are for. Coming up with a\n\t// scheme for how to store the key/value pairs on disk can be tricky,\n\t// especially when taking into account that both keys and values could\n\t// contain newlines, quotes, and any other character you can think of.\n\t//\n\t// One format often used for serializing data to a byte stream that the\n\t// other end can correctly reconstruct is JSON. You are not required to\n\t// use JSON, but as the output of the reduce tasks *must* be JSON,\n\t// familiarizing yourself with it here may prove useful. You can write\n\t// out a data structure as a JSON string to a file using the commented\n\t// code below. The corresponding decoding functions can be found in\n\t// common_reduce.go.\n\t//\n\t// enc := json.NewEncoder(file)\n\t// for _, kv := ... {\n\t// err := enc.Encode(&kv)\n\t//\n\t// Remember to close the file after you have written all the values!\n\n\n\t//setp 1 read file\n\tcontents, err := ioutil.ReadFile(inFile)\n\tif err != nil {\n\t\tlog.Fatal(\"do map error for inFile \",err)\n\t}\n\t//setp 2 call user user-map method ,to get kv\n\tkvResult := mapF(inFile, string(contents))\n\n\t/**\n\t * setp 3 use key of kv generator nReduce file ,partition\n\t * a. create tmpFiles\n\t * b. create encoder for tmpFile to write contents\n\t * c. partition by key, then write tmpFile\n\t */\n\n\tvar tmpFiles [] *os.File = make([] *os.File, nReduce)\n\tvar encoders [] *json.Encoder = make([] *json.Encoder, nReduce)\n\n\tfor i := 0; i < nReduce; i++ {\n\t\ttmpFileName := reduceName(jobName,mapTaskNumber,i)\n\t\ttmpFiles[i],err = os.Create(tmpFileName)\n\t\tif err!=nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tdefer tmpFiles[i].Close()\n\t\tencoders[i] = json.NewEncoder(tmpFiles[i])\n\t\tif err!=nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfor _ , kv := range kvResult {\n\t\thashKey := int(ihash(kv.Key)) % nReduce\n\t\terr := encoders[hashKey].Encode(&kv)\n\t\tif err!=nil {\n\t\t\tlog.Fatal(\"do map encoders \",err)\n\t\t}\n\t}\n\n}", "func (s InputSecureFileArray) ToMap() map[int64]InputSecureFile {\n\tr := make(map[int64]InputSecureFile, len(s))\n\ts.FillMap(r)\n\treturn r\n}", "func NewMap(client *clientv3.Client, path string, value interface{}, codec Codec, handlers ...EventHandler) (Map, error) {\n\t// Check value type.\n\ttyp := reflect.TypeOf(value)\n\tif typ.Kind() != reflect.Ptr {\n\t\treturn nil, ErrValueTypeNotPointer\n\t}\n\t// Create cache.\n\treturn newCache(client, path, typ.Elem(), codec, handlers...)\n}", "func doMap(\n\tjobName string, // the name of the MapReduce job\n\tmapTaskNumber int, // which map task this is\n\tinFile string,\n\tnReduce int, // the number of reduce task that will be run (\"R\" in the paper)\n\tmapF func(file string, contents string) []KeyValue,\n) {\n\tcontent, err := ioutil.ReadFile(inFile)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tkeyValues := mapF(inFile, string(content))\n\treduceFiles := make(map[string]*os.File)\n\n\tfor _, kv := range keyValues {\n\t\treduceTaskNumber := ihash(kv.Key) % nReduce\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\treduceFileName := reduceName(jobName, mapTaskNumber, reduceTaskNumber)\n\n\t\tif reduceFiles[reduceFileName] == nil {\n\t\t\tf, err := os.OpenFile(reduceFileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\treduceFiles[reduceFileName] = f\n\t\t}\n\n\t\tf := reduceFiles[reduceFileName]\n\t\tenc := json.NewEncoder(f)\n\t\tenc.Encode(&kv)\n\t}\n\n\tfor _, f := range reduceFiles {\n\t\tf.Close()\n\t}\n}", "func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {\n\t// Parse config into Options struct\n\topt := new(Options)\n\terr := configstruct.Set(m, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(opt.Headers)%2 != 0 {\n\t\treturn nil, errors.New(\"odd number of headers supplied\")\n\t}\n\tfs.Debugf(nil, \"found headers: %v\", opt.Headers)\n\n\trootIsDir := strings.HasSuffix(root, \"/\")\n\troot = strings.Trim(root, \"/\")\n\n\tif !strings.HasSuffix(opt.URL, \"/\") {\n\t\topt.URL += \"/\"\n\t}\n\tif opt.Pass != \"\" {\n\t\tvar err error\n\t\topt.Pass, err = obscure.Reveal(opt.Pass)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"couldn't decrypt password: %w\", err)\n\t\t}\n\t}\n\tif opt.Vendor == \"\" {\n\t\topt.Vendor = \"other\"\n\t}\n\troot = strings.Trim(root, \"/\")\n\n\tif opt.Enc == encoder.EncodeZero && opt.Vendor == \"sharepoint-ntlm\" {\n\t\topt.Enc = defaultEncodingSharepointNTLM\n\t}\n\n\t// Parse the endpoint\n\tu, err := url.Parse(opt.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf := &Fs{\n\t\tname: name,\n\t\troot: root,\n\t\topt: *opt,\n\t\tendpoint: u,\n\t\tendpointURL: u.String(),\n\t\tpacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(opt.PacerMinSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),\n\t\tprecision: fs.ModTimeNotSupported,\n\t}\n\n\tclient := fshttp.NewClient(ctx)\n\tif opt.Vendor == \"sharepoint-ntlm\" {\n\t\t// Disable transparent HTTP/2 support as per https://golang.org/pkg/net/http/ ,\n\t\t// otherwise any connection to IIS 10.0 fails with 'stream error: stream ID 39; HTTP_1_1_REQUIRED'\n\t\t// https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-10/http2-on-iis says:\n\t\t// 'Windows authentication (NTLM/Kerberos/Negotiate) is not supported with HTTP/2.'\n\t\tt := fshttp.NewTransportCustom(ctx, func(t *http.Transport) {\n\t\t\tt.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}\n\t\t})\n\n\t\t// Add NTLM layer\n\t\tclient.Transport = &safeRoundTripper{\n\t\t\tfs: f,\n\t\t\trt: ntlmssp.Negotiator{RoundTripper: t},\n\t\t}\n\t}\n\tf.srv = rest.NewClient(client).SetRoot(u.String())\n\n\tf.features = (&fs.Features{\n\t\tCanHaveEmptyDirectories: true,\n\t}).Fill(ctx, f)\n\tif opt.User != \"\" || opt.Pass != \"\" {\n\t\tf.srv.SetUserPass(opt.User, opt.Pass)\n\t} else if opt.BearerToken != \"\" {\n\t\tf.setBearerToken(opt.BearerToken)\n\t} else if f.opt.BearerTokenCommand != \"\" {\n\t\terr = f.fetchAndSetBearerToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif opt.Headers != nil {\n\t\tf.addHeaders(opt.Headers)\n\t}\n\tf.srv.SetErrorHandler(errorHandler)\n\terr = f.setQuirks(ctx, opt.Vendor)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !f.findHeader(opt.Headers, \"Referer\") {\n\t\tf.srv.SetHeader(\"Referer\", u.String())\n\t}\n\n\tif root != \"\" && !rootIsDir {\n\t\t// Check to see if the root actually an existing file\n\t\tremote := path.Base(root)\n\t\tf.root = path.Dir(root)\n\t\tif f.root == \".\" {\n\t\t\tf.root = \"\"\n\t\t}\n\t\t_, err := f.NewObject(ctx, remote)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, fs.ErrorObjectNotFound) || errors.Is(err, fs.ErrorIsDir) {\n\t\t\t\t// File doesn't exist so return old f\n\t\t\t\tf.root = root\n\t\t\t\treturn f, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\t// return an error with an fs which points to the parent\n\t\treturn f, fs.ErrorIsFile\n\t}\n\treturn f, nil\n}", "func getMapList() []string {\n\tfiles, err := dry.ListDirFiles(default_map_data_dir)\n\tif err != nil {\n\t\treturn []string{}\n\t} else {\n\t\tfmt.Println(files)\n\t\treturn dry.StringMap(func(s string) string {\n\t\t\treturn strings.Replace(s, path.Ext(s), \"\", 1)\n\t\t}, files)\n\t\t// return files\n\t}\n}", "func New() *FS {\n\treturn &FS{\n\t\tdir: &dir{\n\t\t\tchildren: make(map[string]childI),\n\t\t},\n\t}\n}", "func (s *StorageBase) SetMap(ctx context.Context, sessionId string, mapData map[string]interface{}, ttl time.Duration) error {\n\treturn ErrorDisabled\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}", "func _escFS(useLocal bool) http.FileSystem {\n\tif useLocal {\n\t\treturn _escLocal\n\t}\n\treturn _escStatic\n}" ]
[ "0.7712532", "0.62511665", "0.6213728", "0.6151995", "0.6064215", "0.59997946", "0.5880542", "0.5823566", "0.5793622", "0.5762857", "0.57039267", "0.5660694", "0.55813694", "0.5567053", "0.5543323", "0.55052394", "0.5480834", "0.5477243", "0.5444505", "0.5433696", "0.5377666", "0.53569883", "0.5334358", "0.5331561", "0.53209126", "0.5288113", "0.5274552", "0.52523607", "0.5244865", "0.52388036", "0.5231997", "0.5228085", "0.519141", "0.51700735", "0.5163822", "0.5139686", "0.5138938", "0.5137572", "0.5134689", "0.51332086", "0.51286685", "0.51144314", "0.5108974", "0.5095644", "0.50853896", "0.507728", "0.5063877", "0.5053542", "0.5042577", "0.50425214", "0.5041295", "0.5024182", "0.5015927", "0.50058955", "0.5001003", "0.4993589", "0.49897495", "0.49747887", "0.496625", "0.49624237", "0.49468294", "0.49428037", "0.49423683", "0.49394158", "0.49381873", "0.49371794", "0.49342123", "0.49238148", "0.49206173", "0.49186257", "0.49065486", "0.49061114", "0.49061114", "0.49061114", "0.49056983", "0.4903177", "0.4892859", "0.4884936", "0.48775855", "0.48715064", "0.48676273", "0.4865241", "0.48647824", "0.48585987", "0.48574328", "0.48571113", "0.48521465", "0.48301652", "0.482732", "0.48236448", "0.48071346", "0.4804543", "0.47963592", "0.47944736", "0.47914425", "0.47896105", "0.4783444", "0.4783444", "0.4783444", "0.4783444" ]
0.82970136
0
Print prints post indexs friendly
func (p *Index) Print() { fmt.Println(strings.Repeat("#", p.Level), p) for _, c := range p.Children { c.Print() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PostsIndexHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Posts index\")\n}", "func ShowIndex() {\n\tfmt.Printf(\"%v\\n\", indexText)\n}", "func build_index(pss []Post, index, pre, next int, indexname string) {\n\n\tvar doc bytes.Buffer\n\tvar body, name string\n\tvar ips Indexposts\n\tvar tml *template.Template\n\tvar err error\n\tips.Conf = conf\n\tips.Posts = pss\n\tips.Slug = indexname\n\tif pre != 0 {\n\t\tips.PreviousF = true\n\t\tips.Previous = pre\n\t} else {\n\t\tips.PreviousF = false\n\t}\n\tif next > 0 {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t} else if next == -1 {\n\t\tips.NextF = false\n\t} else {\n\t\tips.NextF = true\n\t\tips.Next = next\n\t}\n\tif next == 0 {\n\t\tips.NextLast = true\n\t}\n\n\tips.Links = conf.Links\n\tips.Logo = conf.Logo\n\tif indexname == \"index\" {\n\t\tips.Main = true\n\t} else {\n\t\tips.Main = false\n\t}\n\tips.Disqus = false\n\tif indexname == \"index\" {\n\t\ttml, err = template.ParseFiles(\"./templates/index.html\", \"./templates/base.html\")\n\t} else {\n\t\ttml, err = template.ParseFiles(\"./templates/cat-index.html\", \"./templates/base.html\")\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error in parsing: \", err)\n\t}\n\terr = tml.ExecuteTemplate(&doc, \"base\", ips)\n\tif err != nil {\n\t\tfmt.Println(\"Error in executing the template: \", err)\n\t}\n\tbody = doc.String()\n\tif next == -1 {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s.html\", indexname)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s.html\", indexname)\n\t\t}\n\t} else {\n\t\tif indexname == \"index\" {\n\t\t\tname = fmt.Sprintf(\"./output/%s-%d.html\", indexname, index)\n\t\t} else {\n\t\t\tname = fmt.Sprintf(\"./output/categories/%s-%d.html\", indexname, index)\n\t\t}\n\t}\n\tf, err := os.Create(name)\n\tdefer f.Close()\n\tn, err := io.WriteString(f, body)\n\n\tif err != nil {\n\t\tfmt.Println(\"Write error: \", n, err)\n\t}\n\t// For Sitemap\n\tsmap := Sitemap{Loc: conf.URL + name[9:], Lastmod: current_time.Format(\"2006-01-02\"), Priority: \"0.5\"}\n\tSDB[smap.Loc] = smap\n}", "func IndexPost(ctx *iris.Context) {\n\n\ttemplatePaginacion = ``\n\n\tvar resultados []GrupoPersonaModel.GrupoPersonaMgo\n\tvar IDToObjID bson.ObjectId\n\tvar arrObjIds []bson.ObjectId\n\tvar arrToMongo []bson.ObjectId\n\n\tcadenaBusqueda = ctx.FormValue(\"searchbox\")\n\tbuscarEn = ctx.FormValue(\"buscaren\")\n\n\tif cadenaBusqueda != \"\" {\n\n\t\tdocs := GrupoPersonaModel.BuscarEnElastic(cadenaBusqueda)\n\n\t\tif docs.Hits.TotalHits > 0 {\n\t\t\tnumeroRegistros = docs.Hits.TotalHits\n\n\t\t\tpaginasTotales = Totalpaginas()\n\n\t\t\tfor _, item := range docs.Hits.Hits {\n\t\t\t\tIDToObjID = bson.ObjectIdHex(item.Id)\n\t\t\t\tarrObjIds = append(arrObjIds, IDToObjID)\n\t\t\t}\n\n\t\t\tif numeroRegistros <= int64(limitePorPagina) {\n\t\t\t\tfor _, v := range arrObjIds[0:numeroRegistros] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t} else if numeroRegistros >= int64(limitePorPagina) {\n\t\t\t\tfor _, v := range arrObjIds[0:limitePorPagina] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresultados = GrupoPersonaModel.GetEspecifics(arrToMongo)\n\n\t\t\tMoConexion.FlushElastic()\n\n\t\t}\n\n\t}\n\n\ttemplatePaginacion = ConstruirPaginacion()\n\n\tctx.Render(\"GrupoPersonaIndex.html\", map[string]interface{}{\n\t\t\"result\": resultados,\n\t\t\"cadena_busqueda\": cadenaBusqueda,\n\t\t\"PaginacionT\": template.HTML(templatePaginacion),\n\t})\n\n}", "func (*Term) print(cs []*Column, idx int) string {\n\tret := fmt.Sprint(\"| \")\n\tfor _, c := range cs {\n\t\tformat := fmt.Sprintf(\"%%-%dv\", c.Len)\n\t\tif idx < 0 {\n\t\t\tret += fmt.Sprintf(format, c.Name)\n\t\t} else {\n\t\t\tret += fmt.Sprintf(format, c.Values[idx])\n\t\t}\n\t\tret += fmt.Sprint(\" | \")\n\t}\n\tret += fmt.Sprintln(\"\")\n\treturn ret\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"index de uma função\")\n}", "func printPostAndComments(post Item, offset int, postState string) {\n\tfmt.Printf(\"\\n\\n[%d (%s)]: %s\\n\", post.ID, postState, post.Text)\n\tfmt.Println(\"Комментарии: \")\n\tprintComments(post, offset)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"s-senpai, please don't hurt me ;_;\\n\")\n}", "func index_handler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa go is cool\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\n\tfmt.Fprintln(w, \"Steve and Kyle Podcast: #api\")\n\tfmt.Fprintln(w, \"Number of episodes in database:\", EpCount())\n\tfmt.Fprintln(w, \"Created by Derek Slenk\")\n\tfmt.Println(\"Endpoint Hit: Index\")\n}", "func writeIndexEntries(p []*post, o string, t postListing) error {\n\tvar m string\n\tswitch t {\n\tcase index:\n\t\tm = \"index_template.html\"\n\tcase rss:\n\t\tm = \"rss_template.rss\"\n\tcase archive:\n\t\tm = \"archive_template.html\"\n\t}\n\te, err := template.ParseFiles(filepath.Join(templatesrc, m))\n\tif checkError(err) {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(o)\n\tif checkError(err) {\n\t\treturn err\n\t}\n\terr = e.Execute(f, p)\n\tif checkError(err) {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa, Nice!\")\n}", "func (n *OpenBazaarNode) getPostIndex() ([]postData, error) {\n\tindexPath := path.Join(n.RepoPath, \"root\", \"posts.json\")\n\n\tvar index []postData\n\n\t_, ferr := os.Stat(indexPath)\n\tif !os.IsNotExist(ferr) {\n\t\t// Read existing file\n\t\tfile, err := ioutil.ReadFile(indexPath)\n\t\tif err != nil {\n\t\t\treturn index, err\n\t\t}\n\t\terr = json.Unmarshal(file, &index)\n\t\tif err != nil {\n\t\t\treturn index, err\n\t\t}\n\t}\n\treturn index, nil\n}", "func create_index_files(ps []Post, indexname string) {\n\tvar prev, next int\n\tindex_page_flag := false\n\tindex := 1\n\tnum := 0\n\tlength := len(ps)\n\tsort.Sort(ByODate(ps))\n\tsort_index := make([]Post, 0)\n\tfor i := range ps {\n\t\tif ps[i].Changed {\n\t\t\tindex_page_flag = true\n\t\t}\n\t\tsort_index = append(sort_index, ps[i])\n\t\tnum = num + 1\n\t\tif num == POSTN {\n\t\t\tif !check_index(indexname, index) {\n\t\t\t\tindex_page_flag = true\n\t\t\t}\n\n\t\t\t/* Only changed indexes should get rebuild*/\n\t\t\tif index_page_flag == true {\n\t\t\t\tindex_page_flag = false\n\t\t\t\tsort.Sort(ByDate(sort_index))\n\t\t\t\tif index == 1 {\n\t\t\t\t\tprev = 0\n\t\t\t\t} else {\n\t\t\t\t\tprev = index - 1\n\t\t\t\t}\n\t\t\t\tif (index*POSTN) < length && (length-index*POSTN) > POSTN {\n\t\t\t\t\tnext = index + 1\n\t\t\t\t} else if (index * POSTN) == length {\n\t\t\t\t\tnext = -1\n\t\t\t\t} else {\n\t\t\t\t\tnext = 0\n\t\t\t\t}\n\n\t\t\t\tbuild_index(sort_index, index, prev, next, indexname)\n\t\t\t}\n\n\t\t\tsort_index = make([]Post, 0)\n\t\t\tindex = index + 1\n\t\t\tnum = 0\n\n\t\t}\n\t}\n\tif len(sort_index) > 0 {\n\t\tsort.Sort(ByDate(sort_index))\n\t\tbuild_index(sort_index, 0, index-1, -1, indexname)\n\n\t}\n}", "func (data *Invasion) Print(s string) {\n log.Printf(\"[iter %5d] %s\", data.Iteration, s)\n}", "func (c CategoryPostController) Index(ctx *fasthttp.RequestCtx) {\n\tpaginate, _, _ := c.Paginate(ctx, \"id\", \"inserted_at\", \"updated_at\")\n\n\tvar posts []model.PostDEP\n\tvar postSlug model.PostSlug\n\tvar postDetail model.PostDetail\n\tvar postCategoryAssignment model.PostCategoryAssignment\n\tvar category model.Category\n\tvar user model.User\n\tc.GetDB().QueryWithModel(fmt.Sprintf(`\n\t\tSELECT \n\t\t\tp.id as id, p.author_id as author_id, u.username as author_username, \n\t\t\tp.inserted_at as inserted_at, ps.slug as slug, pd.title as title, \n\t\t\tpd.description as description, pd.content as content\n\t\tFROM %s AS p\n\t\tLEFT OUTER JOIN %s AS ps ON p.id = ps.post_id\n\t\tLEFT OUTER JOIN %s AS ps2 ON ps.post_id = ps2.post_id AND ps.id < ps2.id\n\t\tINNER JOIN %s AS pd ON p.id = pd.post_id\n\t\tLEFT OUTER JOIN %s AS pd2 ON pd.post_id = pd2.post_id AND pd.id < pd2.id\n\t\tINNER JOIN %s AS u ON p.author_id = u.id\n\t\tINNER JOIN %s AS pca ON p.id = pca.post_id\n\t\tINNER JOIN %s AS c ON pca.category_id = c.id\n\t\tWHERE ps2.id IS NULL AND pd2.id IS NULL AND (c.id::text = $1::text OR c.slug = $1)\n\t\tORDER BY %s %s\n\t\tLIMIT $2 OFFSET $3\n\t`, c.Model.TableName(), postSlug.TableName(), postSlug.TableName(), postDetail.TableName(),\n\t\tpostDetail.TableName(), user.TableName(), postCategoryAssignment.TableName(), category.TableName(),\n\t\tpaginate.OrderField,\n\t\tpaginate.OrderBy),\n\t\t&posts,\n\t\tphi.URLParam(ctx, \"categoryID\"),\n\t\tpaginate.Limit,\n\t\tpaginate.Offset)\n\n\tvar count int64\n\tcount, _ = c.App.Cache.Get(cmn.GetRedisKey(\"post\", \"count\")).Int64()\n\tif count == 0 {\n\t\tc.GetDB().DB.Get(&count, fmt.Sprintf(`\n\t\t\tSELECT count(p.id) FROM %s AS p\n\t\t\tINNER JOIN %s AS pd ON p.id = pd.post_id\n\t\t\tLEFT OUTER JOIN %s AS pd2 ON pd.post_id = pd2.post_id AND pd.id < pd2.id\n\t\t\tWHERE pd2.id IS NULL\n\t\t`, c.Model.TableName(), postDetail.TableName(), postDetail.TableName()))\n\t}\n\n\tc.JSONResponse(ctx, model2.ResponseSuccess{\n\t\tData: posts,\n\t\tTotalCount: count,\n\t}, fasthttp.StatusOK)\n}", "func (d deck) print() {\n\tfor index, card := range d {\n\t\tfmt.Println(index, card)\n\t}\n}", "func tableInfoIndexShow(meta *halproto.TableMetadata) {\n\tiMeta := meta.GetIndexMeta()\n\tinsStr := fmt.Sprintf(\"%d[%d]\", iMeta.GetNumInserts(), iMeta.GetNumInsertFailures())\n\tupdStr := fmt.Sprintf(\"%d[%d]\", iMeta.GetNumUpdates(), iMeta.GetNumUpdateFailures())\n\tdelStr := fmt.Sprintf(\"%d[%d]\", iMeta.GetNumDeletes(), iMeta.GetNumDeleteFailures())\n\tfmt.Printf(\"%-30s%-10d%-10s%-10d%-10s%-10d%-10s%-10s%-10s%-10s\\n\",\n\t\tmeta.GetTableName(),\n\t\tmeta.GetTableId(),\n\t\tutils.TableKindToStr(meta.GetKind()),\n\t\tiMeta.GetCapacity(),\n\t\t\"-\",\n\t\tiMeta.GetUsage(),\n\t\t\"-\",\n\t\tinsStr,\n\t\tupdStr,\n\t\tdelStr)\n}", "func (s Service) IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tisAuthenticated, userID := s.isAuthenticated(r)\n\n\tposts, err := s.postStore.GetAll()\n\tif err != nil {\n\t\tlog.Println(err)\n\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\terr = s.templates.ExecuteTemplate(w, \"index\", map[string]interface{}{\n\t\t\"isAuthenticated\": isAuthenticated,\n\t\t\"userID\": userID,\n\t\t\"posts\": posts,\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func IndexPost(ctx *iris.Context) {\n\n\tvar Send CotizacionModel.SCotizacion\n\n\tNameUsrLoged, MenuPrincipal, MenuUsr, errSes := Session.GetDataSession(ctx) //Retorna los datos de la session\n\tSend.SSesion.Name = NameUsrLoged\n\tSend.SSesion.MenuPrincipal = template.HTML(MenuPrincipal)\n\tSend.SSesion.MenuUsr = template.HTML(MenuUsr)\n\tif errSes != nil {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = errSes.Error()\n\t\tctx.Render(\"ZError.html\", Send)\n\t\treturn\n\t}\n\n\tvar Cabecera, Cuerpo string\n\n\tgrupo := ctx.FormValue(\"Grupox\")\n\tif grupo != \"\" {\n\t\tgru, _ := strconv.Atoi(grupo)\n\t\tlimitePorPagina = gru\n\t}\n\n\tcadenaBusqueda = ctx.FormValue(\"searchbox\")\n\t//Send.Cotizacion.EVARIABLECotizacion.VARIABLE = cadenaBusqueda //Variable a autilizar para regresar la cadena de búsqueda.\n\n\tif cadenaBusqueda != \"\" {\n\n\t\tdocs := CotizacionModel.BuscarEnElastic(cadenaBusqueda)\n\n\t\tif docs.Hits.TotalHits > 0 {\n\t\t\tarrIDElastic = []bson.ObjectId{}\n\n\t\t\tfor _, item := range docs.Hits.Hits {\n\t\t\t\tIDElastic = bson.ObjectIdHex(item.Id)\n\t\t\t\tarrIDElastic = append(arrIDElastic, IDElastic)\n\t\t\t}\n\n\t\t\tnumeroRegistros = len(arrIDElastic)\n\n\t\t\tarrToMongo = []bson.ObjectId{}\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:numeroRegistros] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:limitePorPagina] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMoConexion.FlushElastic()\n\n\t\t\tCabecera, Cuerpo := CotizacionModel.GeneraTemplatesBusqueda(CotizacionModel.GetEspecifics(arrToMongo))\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t} else {\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = CotizacionModel.GeneraTemplatesBusqueda(CotizacionModel.GetEspecifics(arrIDMgo[0:numeroRegistros]))\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = CotizacionModel.GeneraTemplatesBusqueda(CotizacionModel.GetEspecifics(arrIDMgo[0:limitePorPagina]))\n\t\t\t}\n\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t\tSend.SIndex.SRMsj = \"No se encontraron resultados para: \" + cadenaBusqueda + \" .\"\n\t\t}\n\n\t\tSend.SEstado = true\n\n\t} else {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = \"No se recibió una cadena de consulta, favor de escribirla.\"\n\t\tSend.SResultados = false\n\t}\n\tSend.SIndex.SGrupo = template.HTML(CargaCombos.CargaComboMostrarEnIndex(limitePorPagina))\n\tctx.Render(\"CotizacionIndex.html\", Send)\n\n}", "func IndexPost(ctx *iris.Context) {\n\n\tvar Send ProductoModel.SProducto\n\tNameUsrLoged, MenuPrincipal, MenuUsr, errSes := Session.GetDataSession(ctx) //Retorna los datos de la session\n\tSend.SSesion.Name = NameUsrLoged\n\tSend.SSesion.MenuPrincipal = template.HTML(MenuPrincipal)\n\tSend.SSesion.MenuUsr = template.HTML(MenuUsr)\n\tif errSes != nil {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = errSes.Error()\n\t\tctx.Render(\"ZError.html\", Send)\n\t\treturn\n\t}\n\n\tvar Cabecera, Cuerpo string\n\n\tgrupo := ctx.FormValue(\"Grupox\")\n\tif grupo != \"\" {\n\t\tgru, _ := strconv.Atoi(grupo)\n\t\tlimitePorPagina = gru\n\t}\n\n\tcadenaBusqueda = ctx.FormValue(\"searchbox\")\n\t//Send.Producto.EVARIABLEProducto.VARIABLE = cadenaBusqueda //Variable a autilizar para regresar la cadena de búsqueda.\n\n\tif cadenaBusqueda != \"\" {\n\n\t\tdocs := ProductoModel.BuscarEnElastic(cadenaBusqueda)\n\n\t\tif docs.Hits.TotalHits > 0 {\n\t\t\tarrIDElastic = []bson.ObjectId{}\n\n\t\t\tfor _, item := range docs.Hits.Hits {\n\t\t\t\tIDElastic = bson.ObjectIdHex(item.Id)\n\t\t\t\tarrIDElastic = append(arrIDElastic, IDElastic)\n\t\t\t}\n\n\t\t\tnumeroRegistros = len(arrIDElastic)\n\n\t\t\tarrToMongo = []bson.ObjectId{}\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:numeroRegistros] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:limitePorPagina] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMoConexion.FlushElastic()\n\n\t\t\tCabecera, Cuerpo := ProductoModel.GeneraTemplatesBusqueda(ProductoModel.GetEspecifics(arrToMongo))\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t} else {\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = ProductoModel.GeneraTemplatesBusqueda(ProductoModel.GetEspecifics(arrIDMgo[0:numeroRegistros]))\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = ProductoModel.GeneraTemplatesBusqueda(ProductoModel.GetEspecifics(arrIDMgo[0:limitePorPagina]))\n\t\t\t}\n\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t\tSend.SIndex.SRMsj = \"No se encontraron resultados para: \" + cadenaBusqueda + \" .\"\n\t\t}\n\n\t\tSend.SEstado = true\n\n\t} else {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = \"No se recibió una cadena de consulta, favor de escribirla.\"\n\t\tSend.SResultados = false\n\t}\n\tSend.SIndex.SGrupo = template.HTML(CargaCombos.CargaComboMostrarEnIndex(limitePorPagina))\n\tctx.Render(\"ProductoIndex.html\", Send)\n\n}", "func showIndex(c *gin.Context) {\n\trender(\n\t\tc,\n\t\tgin.H{\n\t\t\t\"title\": \"Home Page\",\n\t\t\t\"payload\": films,\n\t\t},\n\t\ttemplates.Index,\n\t)\n}", "func (po *Post) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Post(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v, \", po.ID))\n\tbuilder.WriteString(\"create_time=\")\n\tbuilder.WriteString(po.CreateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"update_time=\")\n\tbuilder.WriteString(po.UpdateTime.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"slug=\")\n\tbuilder.WriteString(po.Slug)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"title=\")\n\tbuilder.WriteString(po.Title)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"content=\")\n\tbuilder.WriteString(po.Content)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"content_html=\")\n\tbuilder.WriteString(po.ContentHTML)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"summary=\")\n\tbuilder.WriteString(po.Summary)\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"published_at=\")\n\tbuilder.WriteString(po.PublishedAt.Format(time.ANSIC))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"view_count=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", po.ViewCount))\n\tbuilder.WriteString(\", \")\n\tbuilder.WriteString(\"public=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", po.Public))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func IndexPost(ctx *iris.Context) {\n\n\tvar Send CajaModel.SCaja\n\n\tNameUsrLoged, MenuPrincipal, MenuUsr, errSes := Session.GetDataSession(ctx) //Retorna los datos de la session\n\tSend.SSesion.Name = NameUsrLoged\n\tSend.SSesion.MenuPrincipal = template.HTML(MenuPrincipal)\n\tSend.SSesion.MenuUsr = template.HTML(MenuUsr)\n\tif errSes != nil {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = errSes.Error()\n\t\tctx.Render(\"ZError.html\", Send)\n\t\treturn\n\t}\n\n\tvar Cabecera, Cuerpo string\n\n\tgrupo := ctx.FormValue(\"Grupox\")\n\tif grupo != \"\" {\n\t\tgru, _ := strconv.Atoi(grupo)\n\t\tlimitePorPagina = gru\n\t}\n\n\tcadenaBusqueda = ctx.FormValue(\"searchbox\")\n\t//Send.Caja.EVARIABLECaja.VARIABLE = cadenaBusqueda //Variable a autilizar para regresar la cadena de búsqueda.\n\n\tif cadenaBusqueda != \"\" {\n\n\t\tdocs := CajaModel.BuscarEnElastic(cadenaBusqueda)\n\n\t\tif docs.Hits.TotalHits > 0 {\n\t\t\tarrIDElastic = []bson.ObjectId{}\n\n\t\t\tfor _, item := range docs.Hits.Hits {\n\t\t\t\tIDElastic = bson.ObjectIdHex(item.Id)\n\t\t\t\tarrIDElastic = append(arrIDElastic, IDElastic)\n\t\t\t}\n\n\t\t\tnumeroRegistros = len(arrIDElastic)\n\n\t\t\tarrToMongo = []bson.ObjectId{}\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:numeroRegistros] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tfor _, v := range arrIDElastic[0:limitePorPagina] {\n\t\t\t\t\tarrToMongo = append(arrToMongo, v)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tMoConexion.FlushElastic()\n\n\t\t\tCabecera, Cuerpo := CajaModel.GeneraTemplatesBusqueda(CajaModel.GetEspecifics(arrToMongo))\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t} else {\n\t\t\tif numeroRegistros <= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = CajaModel.GeneraTemplatesBusqueda(CajaModel.GetEspecifics(arrIDMgo[0:numeroRegistros]))\n\t\t\t} else if numeroRegistros >= limitePorPagina {\n\t\t\t\tCabecera, Cuerpo = CajaModel.GeneraTemplatesBusqueda(CajaModel.GetEspecifics(arrIDMgo[0:limitePorPagina]))\n\t\t\t}\n\n\t\t\tSend.SIndex.SCabecera = template.HTML(Cabecera)\n\t\t\tSend.SIndex.SBody = template.HTML(Cuerpo)\n\n\t\t\tpaginasTotales = MoGeneral.Totalpaginas(numeroRegistros, limitePorPagina)\n\t\t\tPaginacion := MoGeneral.ConstruirPaginacion(paginasTotales, 1)\n\t\t\tSend.SIndex.SPaginacion = template.HTML(Paginacion)\n\n\t\t\tSend.SIndex.SRMsj = \"No se encontraron resultados para: \" + cadenaBusqueda + \" .\"\n\t\t}\n\n\t\tSend.SEstado = true\n\n\t} else {\n\t\tSend.SEstado = false\n\t\tSend.SMsj = \"No se recibió una cadena de consulta, favor de escribirla.\"\n\t\tSend.SResultados = false\n\t}\n\tSend.SIndex.SGrupo = template.HTML(CargaCombos.CargaComboMostrarEnIndex(limitePorPagina))\n\tctx.Render(\"CajaIndex.html\", Send)\n\n}", "func (d deck) print() {\n\n\t// assign index and value of every element in cards slice to the variables, idx and card.\n\tfor idx, card := range d {\n\t\tfmt.Println(idx, card)\n\t}\n}", "func (s Segments) Print(w io.Writer) error {\n\tfor i, seg := range s {\n\t\t_, err := fmt.Fprintf(w, \"%d: %v\\n\", i, seg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func PrintSet(index int){\n\tset:=table[index]\n\tPrintUnicode(set.start,set.cnt)\n\tfmt.Printf(\"#%3d %4X~%4X %s %s\\n\",index,set.start,set.end(),set.key,set.desc)\n}", "func index(w http.ResponseWriter, r *http.Request){\n\terr := templ.ExecuteTemplate(w, \"index\", nil)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t}\n}", "func (s *StackInt) Print() {\nlength := len(s.s)\nfor i := 0; i < length; i++ {\nfmt.Print(s.s[i], \" \")\n}\nfmt.Println()\n}", "func (a Ant) PrintSolution(){\n count := 0;\n fmt.Printf(\"Solucion: \")\n for count < len((*a.solution)){\n fmt.Printf(\"%d \", (*a.solution)[count])\n count = count +1\n }\n fmt.Printf(\"\\n\")\n}", "func indexHandler1( w http.ResponseWriter, r *http.Request){\n\n\treg, err := regexp.Compile(\"[^a-zA-Z0-9]+\")\n\tfmt.Fprintf(w, \"word\"+\" \"+\"count\")\n\tfmt.Fprintf(w,\"\\n----------\\n\")\n\tfor key, val := range wordcountMap {\n\n\t\tfmt.Println(strings.TrimRight(key, \" \"), val)\n\t\tfmt.Fprintf(w, reg.ReplaceAllString(key, \"\")+\" \"+strconv.Itoa(val))\n\t\tfmt.Fprintf(w,\"\\n\")\n\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "func ShowPostsHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"showing posts\")\n}", "func (q *SubmitQueue) Dump() {\n\tfor i, item := range q.items {\n\t\tfmt.Printf(\"[%2d] %s:%d %s\\n\", i, item.Repo, item.PRNumber, item.Sha1)\n\t}\n}", "func (e Edge) Print() {\n fmt.Printf(\"%d --(%f)-- %d\\n\", e.v1_index, e.weight, e.v2_index)\n}", "func Index(w http.ResponseWriter, data interface{}) {\n\trender(tpIndex, w, data)\n}", "func (hn *HeadNode) Print() {\n\tcur := hn.head.index\n\tfor i := 0; i < hn.para[0]; i++ {\n\t\tfmt.Printf(\"%+v \", cur[0].Node)\n\t\tcur = cur[0].index\n\t}\n\tfmt.Println()\n}", "func (it IndexType) String() string {\n\treturn [...]string{\"HASH\", \"JSON\"}[it]\n}", "func (n *OpenBazaarNode) UpdatePostIndex(post *pb.SignedPost) error {\n\tld, err := n.extractpostData(post)\n\tif err != nil {\n\t\treturn err\n\t}\n\tindex, err := n.getPostIndex()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.updatePostOnDisk(index, ld)\n}", "func (matrix *Matrix) printMatrix() {\n\n\tfor i := 0; i < len(matrix.Indexes); i++ {\n\t\tfmt.Print(matrix.Indexes[i].Index, \"[ \")\n\t\tfor j := 0; j < len(matrix.Indexes[i].Departments); j++ {\n\t\t\tfmt.Print(\"[ \")\n\t\t\tfor k := 0; k < len(matrix.Indexes[i].Departments[j].Ratings); k++ {\n\t\t\t\ttext, _ := matrix.Indexes[i].Departments[j].Ratings[k].Lista.ToString()\n\t\t\t\tfmt.Print(\"[ \", text, \" ]\")\n\n\t\t\t}\n\t\t\tfmt.Print(\"] \")\n\t\t}\n\t\tfmt.Println(\"]\")\n\t}\n}", "func (vd *Verb_Index) Tag() string { return \"index\" }", "func (d deck) print() {\n\t// loop declaration to iterate over slice till its range\n\tfor index, cards := range d {\n\t\tfmt.Println(index, cards)\n\t}\n}", "func (w Wrdr) LogPost(wrddx int, nwwrd string, stmp int64) {\n\tsrc, chc := w.DeDex(wrddx)\n\tlg := WrdLg{\n\t\tWord: nwwrd,\n\t\tFlavor: \"post\",\n\t\tSource: src,\n\t\tChoice: chc,\n\t\tTime: stmp,\n\t}\n\tw.Lgr.Encode(&lg)\n}", "func ShowPost(c buffalo.Context) error {\n\tdatabase := c.Value(\"tx\").(*pop.Connection)\n\n\tpost := &models.Post{}\n\n\tif txErr := database.Eager().Find(post, c.Param(\"post_id\")); txErr != nil {\n\n\t\tnotFoundResponse := utils.NewErrorResponse(\n\t\t\thttp.StatusNotFound,\n\t\t\t\"post_id\",\n\t\t\tfmt.Sprintf(\"The requested post %s is removed or move to somewhere else.\", c.Param(\"post_id\")),\n\t\t)\n\t\treturn c.Render(http.StatusNotFound, r.JSON(notFoundResponse))\n\t}\n\n\tpostResponse := PostResponse{\n\t\tCode: fmt.Sprintf(\"%d\", http.StatusOK),\n\t\tData: post,\n\t}\n\treturn c.Render(http.StatusOK, r.JSON(postResponse))\n}", "func (d *Diagnosis) indexHandler(w http.ResponseWriter, r *http.Request) {\n\tvar profiles []profile\n\tfor _, p := range pprof.Profiles() {\n\t\tprofiles = append(profiles, profile{\n\t\t\tName: p.Name(),\n\t\t\tHref: p.Name() + \"?debug=1\",\n\t\t\tDesc: profileDescriptions[p.Name()],\n\t\t\tCount: p.Count(),\n\t\t})\n\t}\n\n\t// Adding other profiles exposed from within this package\n\tfor _, p := range []string{\"cmdline\", \"profile\", \"trace\"} {\n\t\tprofiles = append(profiles, profile{\n\t\t\tName: p,\n\t\t\tHref: p,\n\t\t\tDesc: profileDescriptions[p],\n\t\t})\n\t}\n\n\tsort.Slice(profiles, func(i, j int) bool {\n\t\treturn profiles[i].Name < profiles[j].Name\n\t})\n\n\tif err := indexTmpl.Execute(w, map[string]interface{}{\n\t\t\"AppName\": d.appName,\n\t\t\"PathPrefix\": d.pathPrefix,\n\t\t\"Profiles\": profiles,\n\t}); err != nil {\n\t\td.log.Error(err)\n\t}\n}", "func handleIndex(w http.ResponseWriter, r *http.Request) {\n\tmsg := fmt.Sprintf(\"You've called url %s\", r.URL.String())\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(http.StatusOK) // 200\n\tw.Write([]byte(msg))\n}", "func printPlaintextTable(w http.ResponseWriter, r *http.Request, vVDest [][]byte) {\n\n\t//c := appengine.NewContext(r)\n\tb1 := new(bytes.Buffer)\n\tdefer func() {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.Write(b1.Bytes())\n\t}()\n\n\tfor i0 := 0; i0 < len(vVDest); i0++ {\n\t\tb1.WriteString(\"--\")\n\t\tb1.Write(vVDest[i0])\n\t\tb1.WriteString(\"--\")\n\t\tb1.WriteString(\"\\n\")\n\t}\n\n}", "func (R *RaftMember) printLog() string {\n\tnumEntries := 5\n\tif R.Log == nil {\n\t\treturn \"\"\n\t}\n\tvar top, mid, bottom string\n\tstopper := \"|\"\n\ttop = stopper\n\tbottom = stopper\n\tmid = stopper\n\tstart := max(0, len(R.Log)-numEntries) // make the start 10 back from the end\n\tfor i, v := range R.Log[start:] {\n\t\targs := strings.Split(v.Entry, \",\")\n\t\tif args[0] == \"Guess\" {\n\t\t\tv.Entry = args[1][:6] + \" Guessed:\" + args[2]\n\n\t\t} else if args[0] == \"PointScored\" {\n\t\t\tv.Entry = args[1][:6] + \": \" + args[2]\n\t\t}\n\t\tl1 := len(strconv.Itoa(i))\n\t\tl2 := len(strconv.Itoa(v.Term))\n\t\tl3 := len(v.Entry)\n\t\tvar padNum int\n\t\tif l1 >= l2 && l1 >= l3 {\n\t\t\tpadNum = l1\n\t\t} else if l2 > l1 && l2 >= l3 {\n\t\t\tpadNum = l2\n\t\t} else {\n\t\t\tpadNum = l3\n\t\t}\n\t\ttop = top + pad(strconv.Itoa(i+start), padNum) + stopper\n\t\tmid = mid + pad(strconv.Itoa(v.Term), padNum) + stopper\n\t\tbottom = bottom + pad(v.Entry, padNum) + stopper\n\t}\n\ttop = \"Log Index:\" + top + \"\\n\"\n\ttop += (\" \") //offset the headings...\n\tsep := \"\"\n\tfor j := 0; j < len(bottom); j++ {\n\t\tsep += \"-\"\n\t}\n\ttop += sep\n\ttop += \"\\n Term:\" + mid + \"\\n \"\n\ttop += sep\n\ttop += \"\\n Entry:\" + bottom\n\ttop += \"\\n\"\n\treturn top\n}", "func (rl RangeList) Print() {\n\tfor i := 0; i < len(rl.list); i++ {\n\t\tfmt.Printf(\"%s%d, %d%s \", \"[\", rl.list[i][leftIdx], rl.list[i][rightIdx], \")\")\n\t}\n\tfmt.Println()\n}", "func Printem(args ...int) {\n\tfor _, i := range args {\n\t\tfmt.Println(i)\n\t}\n}", "func (eh *Hashset) PrintAll() {\n\tfor _, page := range eh.pages {\n\t\tfor _, v := range page.items {\n\t\t\tfmt.Println(v)\n\t\t}\n\t}\n}", "func printIt(in []Entry) {\n\tfor i := 0; i < len(in); i++ {\n\t\tfmt.Println(in[i].t, in[i].w)\n\t}\n}", "func (a Article) Print() {\n\tfmt.Println(\"---\")\n\n\tvar articleType string\n\n\tswitch a.Type {\n\tcase Post:\n\t\tarticleType = \"Post\"\n\tcase Snippet:\n\t\tarticleType = \"Snippet\"\n\tcase Page:\n\t\tarticleType = \"Page\"\n\t}\n\n\tif a.Type != Snippet {\n\t\tfmt.Printf(\"title: %s\\n\", a.Title)\n\t}\n\n\tfmt.Printf(\"author: %s\\n\", a.Author)\n\tfmt.Printf(\"type: %s\\n\", articleType)\n\tfmt.Println(\"tags: \")\n\tif a.DateModified != nil {\n\t\tfmt.Printf(\"date: %v\\n\", a.DateModified.Format(DefaultDateFormat))\n\t}\n\n\tif a.DateUpdated != nil {\n\t\tfmt.Printf(\"date: %v\\n\", a.DateUpdated.Format(DefaultDateFormat))\n\t}\n\n\tif len(a.AppID) > 0 {\n\t\tfmt.Printf(\"appid: %v\\n\", a.AppID)\n\t}\n\n\tif a.Draft {\n\t\tfmt.Printf(\"draft: true\\n\")\n\t}\n\n\tif a.Meta != nil {\n\t}\n\n\tfmt.Println(\"---\")\n\tfmt.Println(\"\")\n}", "func jsonPrint(posts Posts) {\n\tpostJSON, err := json.MarshalIndent(posts, \"\", \" \")\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"JSON data: \\n %s\\n\", string(postJSON))\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func Index(w http.ResponseWriter, data *IndexData) {\n\trender(tpIndex, w, data)\n}", "func index() string {\n\tvar buffer bytes.Buffer\n\tvar id = 0\n\tvar class = 0\n\tbuffer.WriteString(indexTemplate)\n\tlock.Lock()\n\tfor folderName, folder := range folders {\n\t\tbuffer.WriteString(fmt.Sprintf(\"<h2>%s</h2>\", folderName))\n\t\tfor _, source := range folder {\n\t\t\tif !anyNonRead(source) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsort.Sort(source)\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"<h3>%s</h3>\", source.Title))\n\t\t\tbuffer.WriteString(fmt.Sprintf(`<button onClick=\"hideAll('source_%d'); return false\">Mark all as read</button>`, class))\n\t\t\tbuffer.WriteString(\"<ul>\")\n\n\t\t\tfor _, entry := range source.Entries {\n\t\t\t\tif entry.Read {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<li id=\"entry_%d\">`, id))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<button class=\"source_%d\" onClick=\"hide('entry_%d', '%s'); return false\">Mark Read</button> `, class, id, entry.Url))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<a href=\"%s\">%s</a>`, entry.Url, entry.Title))\n\t\t\t\tbuffer.WriteString(\"</li>\")\n\t\t\t\tid += 1\n\t\t\t}\n\t\t\tbuffer.WriteString(\"</ul>\")\n\t\t\tclass += 1\n\t\t}\n\t}\n\tlock.Unlock()\n\tbuffer.WriteString(\"</body></html>\")\n\treturn buffer.String()\n}", "func printMap(form url.Values) {\n\tfmt.Println(\"BEGIN<PRINTING>\")\n\tfor key, value := range(form) {\n\t\tfmt.Printf(\"<%v> -> <%v>\\n\", key, value)\n\t}\n\tfmt.Println(\"END<PRINTING>\")\n}", "func indexHandler(res http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(res, \"You requested: \"+req.URL.Path)\n}", "func ReturnALLPosts(response http.ResponseWriter, request *http.Request){\n\tvar posts []Post\n\t \n\trequest.ParseForm()\n\tvar u string = request.URL.Path\n\tquery := request.URL.Query()\n\tindex,_ := strconv.Atoi(query.Get(\"index\")) // Getting Cursor value from user to implement cursor paggination\n\tuid := u[13:]\n\t\n \n\n\t\tcollection := client.Database(\"Go_task\").Collection(\"posts\")\n\t\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\t\tdefer cancel()\n\t\tcursor, err := collection.Find(ctx, bson.M{\"uid\":uid})\n\t\tif err != nil {\n\t\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse.Write([]byte(`{ \"message\": \"` + err.Error() + `\" }`))\n\t\t\treturn\n\t\t}\n\t\tdefer cursor.Close(ctx)\n\t\tfor cursor.Next(ctx) {\n\t\t\tvar post Post\n\t\t\tcursor.Decode(&post)\n\t\t\n\t\t\tposts = append(posts, post)\n\n\t\t}\n\t\t\n\t\tif err = cursor.Err(); err != nil {\n\t\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\t\tresponse.Write([]byte(`{ \"message\": \"` + err.Error() + `\" }`))\n\t\t\treturn\n\t\t}\n\t\t\n\t\tjson.NewEncoder(response).Encode(posts[index:])\n}", "func indexApiHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Write([]byte(\"Go card!\\n\"))\n}", "func ShowPosting(ctx *gin.Context) {\n\tvar posting []models.PostItem\n\terr := models.DB.Find(&posting).Error\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, map[string] interface{}{\n\t\t\t\"status\": http.StatusInternalServerError,\n\t\t\t\"message\": \"Gagal\",\n\t\t})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, map[string] interface{}{\n\t\t\"status\": http.StatusOK,\n\t\t\"data\": posting,\n\t})\n}", "func (c Threads) Index() revel.Result {\n results, err := c.Txn.Select(models.Thread{},\n `SELECT * FROM Thread`)\n if err != nil {\n // TODO: Catch it\n panic(err)\n }\n\n var threads []*models.Thread\n for _, r := range results {\n t := r.(*models.Thread)\n threads = append(threads, t)\n }\n\n sort.Sort(SortThreads(threads))\n return c.Render(threads)\n}", "func (idx Index) StringDump(showMutationInfo bool) string {\n\ts := fmt.Sprintf(\"\\nLabel: %d\\n\", idx.Label)\n\tif showMutationInfo {\n\t\ts += fmt.Sprintf(\"Last Mutation ID: %d\\n\", idx.LastMutId)\n\t\ts += fmt.Sprintf(\"Last Modification Time: %s\\n\", idx.LastModTime)\n\t\ts += fmt.Sprintf(\"Last Modification User: %s\\n\", idx.LastModUser)\n\t\ts += fmt.Sprintf(\"Last Modification App: %s\\n\\n\", idx.LastModApp)\n\t}\n\n\ts += fmt.Sprintf(\"Total blocks: %d\\n\", len(idx.Blocks))\n\tfor zyx, svc := range idx.Blocks {\n\t\tizyxStr := BlockIndexToIZYXString(zyx)\n\t\ts += fmt.Sprintf(\"Block %s:\\n\", izyxStr)\n\t\tfor sv, count := range svc.Counts {\n\t\t\ts += fmt.Sprintf(\" Supervoxel %10d: %d voxels\\n\", sv, count)\n\t\t}\n\t\ts += fmt.Sprintf(\"\\n\")\n\t}\n\treturn s\n}", "func (b *Builder) Print(w io.Writer) (n int, err error) {\n\tp := func(nn int, e error) {\n\t\tn += nn\n\t\tif err == nil {\n\t\t\terr = e\n\t\t}\n\t}\n\tt, err := b.build()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tp(fmt.Fprintf(w, `var availableLocales = \"und`))\n\tfor _, loc := range b.locale {\n\t\tif loc.id != \"und\" {\n\t\t\tp(fmt.Fprintf(w, \",%s\", loc.id))\n\t\t}\n\t}\n\tp(fmt.Fprint(w, \"\\\"\\n\\n\"))\n\tp(fmt.Fprintf(w, \"const varTop = 0x%x\\n\\n\", b.varTop))\n\tp(fmt.Fprintln(w, \"var locales = [...]tableIndex{\"))\n\tfor _, loc := range b.locale {\n\t\tif loc.id == \"und\" {\n\t\t\tp(t.fprintIndex(w, loc.index.handle, loc.id))\n\t\t}\n\t}\n\tfor _, loc := range b.locale {\n\t\tif loc.id != \"und\" {\n\t\t\tp(t.fprintIndex(w, loc.index.handle, loc.id))\n\t\t}\n\t}\n\tp(fmt.Fprint(w, \"}\\n\\n\"))\n\tn, _, err = t.fprint(w, \"main\")\n\treturn\n}", "func (qt *Quadtree) Print() {\n\tmaxCoord := Dim(1) << (qt.Level - 1)\n\tfor y := -maxCoord; y < maxCoord; y++ {\n\t\tfmt.Printf(\"%3d: \", y)\n\t\tfor x := -maxCoord; x < maxCoord; x++ {\n\t\t\tfmt.Print(qt.Cell(x, y), \" \")\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\t}\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func (node *ShowIndex) Format(buf *bytes.Buffer, f FmtFlags) {\n\tbuf.WriteString(\"SHOW INDEXES FROM \")\n\tFormatNode(buf, f, node.Table)\n}", "func (v Vertex) Print() {\n fmt.Printf(\"Vertice: %d\\n Feromona Ini: %f\\n Feromona Act: %f\\n\", v.index, v.pheromone_init, v.pheromone)\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 Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hola, este es el inicio\")\n}", "func (d deck) print() {\n\tfor i, v := range d {\n\t\tfmt.Println(i, v)\n\t}\n}", "func (jobstore *JobStore) printJobs(w http.ResponseWriter) {\n\tfor _, job := range jobstore.job {\n\t\tfmt.Fprintf(w, \"Job: %s triggered by %s took %v \\n\", job.name, job.scm.user, job.duration)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i+1, card)\n\t}\n\tfmt.Println(\"----------------\")\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"RadioChecker API v0.4\\n\\nCopyright (C) 2017 Paul Haunschmied.\\nwww.radiochecker.com\")\n}", "func (r *RequestListIndex) String() string {\n\treturn fmt.Sprintf(\"id: %s, type: list index, key: %s\"+\n\t\t\", index: %d\", r.ID, r.Key, r.Index)\n}", "func (s *SkipList) print() {\n\tx := s.Header\n\t// fmt.Println(s.level, s.max)\n\tcount := 0\n\tfmt.Println(\"Height:\", s.level+1)\n\tfor x.Forward[0] != nil {\n\t\tfmt.Println(count, len(x.Forward), x.Forward[0].Key, x.Forward[0].Value)\n\t\tx = x.Forward[0]\n\t\tcount++\n\t}\n}", "func index(c echo.Context) error {\n\tpprof.Index(c.Response().Writer, c.Request())\n\treturn nil\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\ta := \"hello from index router\"\n\tfmt.Fprintln(w, a)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome to this example API\\n\")\n}", "func (di pdfDocInfo) print() {\n\tfmt.Printf(\"Filename: %s\\n\", di.Filename)\n\tfmt.Printf(\" Pages: %d\\n\", di.NumPages)\n\tfmt.Printf(\" Title: %s\\n\", di.Title)\n\tfmt.Printf(\" Author: %s\\n\", di.Author)\n\tfmt.Printf(\" Subject: %s\\n\", di.Subject)\n\tfmt.Printf(\" Keywords: %s\\n\", di.Keywords)\n\tfmt.Printf(\" Creator: %s\\n\", di.Creator)\n\tfmt.Printf(\" Producer: %s\\n\", di.Producer)\n\tfmt.Printf(\" CreationDate: %s\\n\", di.CreationDate)\n\tfmt.Printf(\" ModDate: %s\\n\", di.ModDate)\n\tfmt.Printf(\" Trapped: %s\\n\", di.Trapped)\n\n\tif di.CustomInfo != nil {\n\t\tfor k, v := range di.CustomInfo {\n\t\t\tfmt.Printf(\" %s: %s\\n\", k, v)\n\t\t}\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdata, err := newPageData(1)\n\tif err != nil {\n\t\thttp.NotFound(w, r)\n\t}\n\terr = t.ExecuteTemplate(w, \"index\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (i *Index) ToMarkdown() (s string) {\n\tvar b strings.Builder\n\n\tfmt.Fprintln(&b, \"Notenindex\")\n\tfmt.Fprintf(&b, \"erstellt am %s\\n\", time.Now().Format(\"02.01.2006 um 15:04 Uhr\"))\n\tfmt.Fprintln(&b)\n\n\tfmt.Fprintln(&b, \"# Liste\")\n\tfmt.Fprintln(&b)\n\tfor _, sheet := range i.List {\n\t\tfmt.Fprintf(&b, \"(%d) %s\\n\", sheet.Index, sheet.Name)\n\t}\n\n\tfmt.Fprintln(&b)\n\tfmt.Fprintln(&b, \"# Nach Name\")\n\tfmt.Fprintln(&b)\n\tfor _, key := range i.SortedNames() {\n\t\tsheets := i.ByName[key]\n\t\tlist := strings.Join(sheetStrings(sheets), \",\")\n\t\tfmt.Fprintf(&b, \"%s:\\n\", key)\n\t\tfmt.Fprintln(&b, \" \"+list)\n\t}\n\n\t// fmt.Fprintln(&b)\n\t// fmt.Fprintln(&b, \"# Nach Wort\")\n\t// fmt.Fprintln(&b)\n\t// for _, word := range i.SortedWords() {\n\t// \tsheets := i.ByWord[word]\n\t// \tlist := strings.Join(sheetStrings(sheets), \",\")\n\t// \tfmt.Fprintln(&b, word+\":\")\n\t// \tfmt.Fprintln(&b, \" \"+list)\n\t// }\n\t// fmt.Fprintln(&b)\n\n\treturn b.String()\n}", "func (q *queue) Print() {\n\tif q.count == 0 {\n\t\tout(\"queue is empty\\n\")\n\t\treturn\n\t}\n\ti := q.first\n\tfor count := 0; i != nil && count < q.count; count++ {\n\t\tout(\"%d \", i.data)\n\t\ti = i.next\n\t}\n\tout(\"\\n\")\n}", "func printSlice(slice []string) error {\n\tfor index, val := range slice {\n\t\tfmt.Println(index, \": \", val)\n\t}\n\treturn nil\n}", "func ExamplePrint() {\n\n\tprintTable(n, testAgainst[1:])\n\t//Output:\n\t//1 x 1 = 1\n\t//1 x 2 = 2\n\t//1 x 3 = 3\n}", "func h_root_post(w http.ResponseWriter, r *http.Request, ids []string) {\n\tfmt.Printf(\">>>h_root_post\\n\")\n\tfmt.Printf(\"<<<h_root_post\\n\")\n}", "func (list *APTAuditList) printAll() {\n\tfor _, result := range list.results {\n\t\tfmt.Print(result)\n\t}\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\n\tctx, span := trace.StartSpan(ctx, \"indexHandler\")\n\tdefer span.End()\n\n\tlog.Debugf(ctx, \"Hi, 1\")\n\tlog.Infof(ctx, \"Hi, 2\")\n\n\tfmt.Fprint(w, \"Hello, World!\")\n}", "func (d deck) print () {\n\tfor i, card := range d {\n\t\tfmt.Println(i, \"card:\", card)\n\t}\n}", "func showPost(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"cache-control\", \"no-store, no-cache, must-revalidate\")\n\tsession := sessions.Start(w, r)\n\n\tif len(session.GetString(\"username\")) == 0 {\n\t\thttp.Redirect(w, r, \"/login\", 301)\n\t}\n\n\tcurrentUser := QueryUser(session.GetString(\"username\"))\n\tvars := mux.Vars(r)\n\tpost_id := vars[\"id\"]\n\n\tvar posts = post{}\n\tvar timestamp time.Time\n\tvar yeahed string\n\n\tdb.QueryRow(\"SELECT posts.id, created_by, community_id, created_at, body, image, username, nickname, avatar, online FROM posts LEFT JOIN users ON users.id = created_by WHERE posts.id = ?\", post_id).\n\t\tScan(&posts.ID, &posts.CreatedBy, &posts.CommunityID, &timestamp, &posts.Body, &posts.Image, &posts.PosterUsername, &posts.PosterNickname, &posts.PosterIcon, &posts.PosterOnline)\n\tposts.CreatedAt = humanTiming(timestamp)\n\n\tdb.QueryRow(\"SELECT id FROM yeahs WHERE yeah_post = ? AND yeah_by = ? AND on_comment=0\", posts.ID, currentUser.ID).Scan(&yeahed)\n\tif yeahed != \"\" {\n\t\tposts.Yeahed = true\n\t}\n\n\tdb.QueryRow(\"SELECT COUNT(id) FROM yeahs WHERE yeah_post = ? AND on_comment=0\", post_id).Scan(&posts.YeahCount)\n\tdb.QueryRow(\"SELECT COUNT(id) FROM comments WHERE post = ?\", post_id).Scan(&posts.CommentCount)\n\n\tyeah_rows, _ := db.Query(\"SELECT yeahs.id, username, avatar FROM yeahs LEFT JOIN users ON users.id = yeah_by WHERE yeah_post = ? AND yeah_by != ? AND on_comment=0 ORDER BY yeahs.id DESC\", post_id, currentUser.ID)\n\tvar yeahs []yeah\n\n\tfor yeah_rows.Next() {\n\n\t\tvar row = yeah{}\n\n\t\terr = yeah_rows.Scan(&row.ID, &row.Username, &row.Avatar)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tyeahs = append(yeahs, row)\n\n\t}\n\tyeah_rows.Close()\n\n\tcomment_rows, _ := db.Query(\"SELECT comments.id, created_by, created_at, body, image, username, nickname, avatar, online FROM comments LEFT JOIN users ON users.id = created_by WHERE post = ? ORDER BY created_at ASC\", post_id)\n\tvar comments []comment\n\n\tfor comment_rows.Next() {\n\n\t\tvar row = comment{}\n\t\tvar timestamp time.Time\n\n\t\terr = comment_rows.Scan(&row.ID, &row.CreatedBy, &timestamp, &row.Body, &row.Image, &row.CommenterUsername, &row.CommenterNickname, &row.CommenterIcon, &row.CommenterOnline)\n\t\trow.CreatedAt = humanTiming(timestamp)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tdb.QueryRow(\"SELECT 1 FROM yeahs WHERE yeah_post = ? AND yeah_by = ? AND on_comment=1\", row.ID, currentUser.ID).Scan(&row.Yeahed)\n\n\t\tdb.QueryRow(\"SELECT COUNT(id) FROM yeahs WHERE yeah_post = ? AND on_comment=1\", row.ID).Scan(&row.YeahCount)\n\n\t\tcomments = append(comments, row)\n\n\t}\n\tcomment_rows.Close()\n\n\tcommunity := QueryCommunity(strconv.Itoa(posts.CommunityID))\n\tpjax := r.Header.Get(\"X-PJAX\") == \"\"\n\n\tvar data = map[string]interface{}{\n\t\t\"Title\": posts.PosterNickname + \"'s post\",\n\t\t\"Pjax\": pjax,\n\t\t\"CurrentUser\": currentUser,\n\t\t\"Community\": community,\n\t\t\"Post\": posts,\n\t\t\"Yeahs\": yeahs,\n\t\t\"Comments\": comments,\n\t}\n\n\terr := templates.ExecuteTemplate(w, \"post.html\", data)\n\tif err != nil {\n\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\n\t}\n\n\treturn\n\n}", "func (a App) Posts(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\n\t// easier to do\n\ttmpl := buildView(\"posts\")\n\n\t// Loop through rows using only one struct\n\trows, err := db.Query(\"SELECT * FROM posts\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar p Post\n\n\t\tif err := rows.Scan(&p.Id, &p.Title, &p.Body); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\n\t\tposts = append(posts, p)\n\t}\n\n\t//////\n\tpd := PageData{\n\t\tPageTitle: \"Hello Gophercon!\",\n\t\tPosts: posts,\n\t}\n\n\t// easier to understand what's going on??\n\terr = tmpl.ExecuteTemplate(res, \"layout\", pd)\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t}\n\n}", "func (ps PlanSlice) Print() {\n\tfor _, p := range ps {\n\t\tconsole.Println(p.NameVersion(), human.ByteSize(p.Size))\n\t}\n\tconsole.Flush()\n}", "func Print(url string, stAPI string) ([]string, []text.WriteOption, []text.WriteOption) {\n\twrappedText := make([]string, 0)\n\twrappedOpt := make([]text.WriteOption, 0)\n\twrappedState := make([]text.WriteOption, 0)\n\tdt := time.Now()\n\n\tstURL := url + stAPI\n\n\tresponse, err := http.Get(stURL)\n\tif err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tdata, _ := ioutil.ReadAll(response.Body)\n\n\t\tvar jsonData = gjson.Parse(string(data)).Value().(map[string]interface{})\n\n\t\tif jsonData[\"status\"] != \"ok\" {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\twrappedText = append(wrappedText, dt.Format(\"Updated (01-02-2006 15:04:05)\")+\"(\"+jsonData[\"status\"].(string)+\")\\n\\n\")\n\t\t\twrappedOpt = append(wrappedOpt, text.WriteCellOpts(cell.FgColor(cell.ColorYellow)))\n\t\t\twrappedState = append(wrappedState, text.WriteReplace())\n\n\t\t\tnumArticles, _ := strconv.Atoi(gjson.Get(string(data), \"totalResults\").Array()[0].String())\n\t\t\tresultTitle := gjson.Get(string(data), \"articles.#.title\").Array()\n\t\t\tresultDesc := gjson.Get(string(data), \"articles.#.description\").Array()\n\t\t\tresultURL := gjson.Get(string(data), \"articles.#.url\").Array()\n\n\t\t\tfor i := 0; i < numArticles/2-1; i++ {\n\n\t\t\t\tfilterDesc := strings.ReplaceAll(resultDesc[i].String(), \"\\u00a0\", \"\")\n\t\t\t\tdescLength := len(filterDesc)\n\t\t\t\tif descLength < 300 {\n\t\t\t\t\tif descLength == 0 {\n\t\t\t\t\t\tmaxLength = 0\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmaxLength = len(filterDesc) - 1\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmaxLength = 300\n\t\t\t\t}\n\n\t\t\t\twrappedText = append(wrappedText, resultTitle[i].String()+\"\\n\")\n\t\t\t\twrappedOpt = append(wrappedOpt, text.WriteCellOpts(cell.FgColor(cell.ColorGreen)))\n\t\t\t\twrappedState = append(wrappedState, nil)\n\n\t\t\t\twrappedText = append(wrappedText, filterDesc[:maxLength]+\"\\n\")\n\t\t\t\twrappedOpt = append(wrappedOpt, text.WriteCellOpts(cell.FgColor(cell.ColorRed)))\n\t\t\t\twrappedState = append(wrappedState, nil)\n\n\t\t\t\twrappedText = append(wrappedText, resultURL[i].String()+\"\\n\\n\")\n\t\t\t\twrappedOpt = append(wrappedOpt, text.WriteCellOpts(cell.FgColor(cell.ColorBlue)))\n\t\t\t\twrappedState = append(wrappedState, nil)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn wrappedText, wrappedOpt, wrappedState\n\n}", "func (srv *Server) handlePost(res http.ResponseWriter, req *http.Request) {\n\tfor _, rute := range srv.routePosts {\n\t\tvals, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\trute.endpoint.call(res, req, srv.evals, vals)\n\t\t\treturn\n\t\t}\n\t}\n\tres.WriteHeader(http.StatusNotFound)\n}", "func Index(w http.ResponseWriter, r *http.Request, us httprouter.Params) {\n\tfmt.Fprint(w, \"WELCOMEEE!\")\n}", "func (h *MaxKeyHeap) Print() {\n\tfor i := 0; i < h.Len(); i++ {\n\t\tfmt.Printf(\"%v \", (*h)[i])\n\t}\n\tprintln(\"\")\n}", "func HandleIndex(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tname := p.ByName(\"name\")\n\tresponse := snakes[name].Info\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr := json.NewEncoder(w).Encode(response)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: response write: \" + err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Index: \" + name)\n}", "func (idx Resource) PostIndex(w http.ResponseWriter, r *http.Request) {\n\tredirectTarget := \"/\"\n\temailUser := r.FormValue(\"emailuser\")\n\tpassword := r.FormValue(\"passwordfield\")\n\n\t// If the session is there, direct to upload page\n\t// sess, err := session.GetSessionStore(w, r)\n\t// if err != nil {\n\t// \tHandleSessionError(w, err)\n\t// \treturn\n\t// }\n\tidx.logger.Info(\"Post on this resource.\")\n\tidx.logger.Infoln(emailUser, password)\n\tif (emailUser == \"[email protected]\") && (password == \"admin\") {\n\n\t\tidx.logger.Info(\"Successfully logged in there , now what?\")\n\t\tsess, _ := idx.store.GetSession(r)\n\t\tsess.Values[\"user\"] = emailUser\n\t\tif err := sess.Save(r, w); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tredirectTarget = \"/protected\"\n\t\thttp.Redirect(w, r, redirectTarget, http.StatusSeeOther)\n\t\treturn\n\t}\n\n\thttp.Redirect(w, r, redirectTarget, http.StatusFound)\n}", "func print_table(chunks []Chunk) {\n\tfmt.Println()\n\tfmt.Println(\" Tag | Payload | Pos1 | Pos2\")\n\tfmt.Println(\"------------------|----------------------------------------------------------------\")\n\tfor i := range chunks {\n\t\tpayload := chunks[i].payload\n\t\tn := 40\n\t\tif len(payload) < 40 {\n\t\t\tn = len(payload)\n\t\t}\n\t\tif len(payload) > 0 {\n\t\t\ttag := chunks[i].tag\n\t\t\tif tag == \"\" {\n\t\t\t\ttag = \"...\"\n\t\t\t}\n\t\t\tfmt.Printf(\" %-16s | %-40s | %-8d | %-8d\\n\", tag, payload[:n],\n\t\t\t\tchunks[i].pos1, chunks[i].pos2)\n\t\t}\n\t}\n\tfmt.Println()\n}", "func (k *Index) String() string {\n\treturn fmt.Sprintf(\"%d\", uint32(*k))\n}" ]
[ "0.66788685", "0.5935315", "0.5923084", "0.56648165", "0.56418276", "0.55612767", "0.54678756", "0.54465073", "0.5369691", "0.5350121", "0.5270831", "0.52468544", "0.5185681", "0.5174471", "0.5150493", "0.5095161", "0.50651455", "0.5047249", "0.50279534", "0.5025031", "0.50164044", "0.5007348", "0.5000821", "0.50001067", "0.50000525", "0.49972072", "0.49940017", "0.49913567", "0.49904272", "0.49638113", "0.49624863", "0.49622014", "0.4946652", "0.49313226", "0.49255326", "0.4924286", "0.49195075", "0.49177176", "0.49163148", "0.4906546", "0.4904941", "0.48874655", "0.48821992", "0.4880283", "0.4875172", "0.4873464", "0.48442772", "0.48243263", "0.48224646", "0.47998568", "0.4795737", "0.47884345", "0.47866824", "0.47811115", "0.47811115", "0.47672567", "0.47639933", "0.4760687", "0.47562942", "0.47535655", "0.47486508", "0.4748251", "0.4746724", "0.47450858", "0.47427928", "0.4736601", "0.47232848", "0.47185043", "0.4712751", "0.47072837", "0.47014824", "0.46994105", "0.46991706", "0.46950904", "0.46940884", "0.46922427", "0.4690943", "0.46869102", "0.46858144", "0.46814314", "0.4678916", "0.4672114", "0.4654329", "0.46486446", "0.46422148", "0.46413356", "0.4641099", "0.4636989", "0.46341684", "0.46303582", "0.4628384", "0.46237206", "0.46233165", "0.46218446", "0.46175534", "0.46153522", "0.46074754", "0.46031588", "0.46012297", "0.4599287" ]
0.6082166
1
New returns indexes with data bytes
func New(data []byte) []*Index { return NewWithReader(bytes.NewReader(data)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(data []byte) *Index {}", "func New(data []byte) *Index", "func New(data []byte) *suffixarray.Index", "func (x *Index) Bytes() []byte", "func newFileIndex(offset int, size int) (fileIndex, error) {\n\n\tif size > maxKeySize {\n\t\treturn fileIndex{}, fmt.Errorf(\"cannot store key of size bigger than %d. size was %d\", maxKeySize, size)\n\t}\n\tss := uint16(size)\n\n\tif offset > maxValueSize {\n\t\treturn fileIndex{}, fmt.Errorf(\"cannot store value of size bigger than %d. size was %d\", maxValueSize, offset)\n\t}\n\too := uint32(offset)\n\n\ts := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(s, ss)\n\to := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(o, oo)\n\tb, err := Concat(6, o, s)\n\tif err != nil {\n\t\treturn fileIndex{}, fmt.Errorf(\"could not create fileIndex for [%d,%d] %w\", offset, size, err)\n\t}\n\treturn fileIndex{\n\t\tbytes: b,\n\t\toffset: uint64(oo),\n\t\tsize: ss,\n\t}, nil\n}", "func (x *Index) Bytes() []byte {}", "func IndexBytes(x *suffixarray.Index,) []byte", "func CreateNewIndex(rawItems PointArray, dim, nTree, k int, m Metric) (Index, error) {\n\t// verify that given items have same dimension\n\tl := rawItems.Len()\n\tif l < 2 {\n\t\treturn nil, errNotEnoughItems\n\t}\n\tits := make([]*item, l)\n\t//idToItem := make(map[itemId]*item, l)\n\tfor i:=0; i < l; i++{\n\t\tv := rawItems.At(i)\n\t\tif v.Dimension() != dim {\n\t\t\treturn nil, errDimensionMismatch\n\t\t}\n\t\tit := &item{\n\t\t\tid: itemId(i),\n\t\t\tvector: v,\n\t\t}\n\t\tits[i] = it\n\t\t//idToItem[it.id] = it\n\t}\n\tidx := &index{\n\t\tmetric: m,\n\t\tdim: dim,\n\t\tk: k,\n\t\titemIDToItem: rawItems,\n\t\troots: make([]*node, nTree),\n\t\tnodeIDToNode: map[nodeId]*node{},\n\t\tmux: &sync.Mutex{},\n\t}\n\n\t// build\n\tidx.build(its, nTree)\n\treturn idx, nil\n}", "func newHashArray(indexSize int) hashArray {\n\tha := make(hashArray, indexSize)\n\tfor i := 0; i < indexSize; i += 1 {\n\t\tha[i] = -1\n\t}\n\n\treturn ha\n}", "func newUnionFindData(n int) *unionFindData {\n\tuf := &unionFindData{\n\t\tid: make([]int, n),\n\t\tcount: n,\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tuf.id[i] = i\n\t}\n\treturn uf\n}", "func newQueueIndex(dataDir string) (*queueIndex, error) {\n\tindexFile := path.Join(dataDir, cIndexFileName)\n\tindexArena, err := newArena(indexFile, cIndexFileSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueIndex{\n\t\tindexFile: indexFile,\n\t\tindexArena: indexArena,\n\t}, nil\n}", "func CreateIndex(dataLen int, lessFunc func(i, j int) bool) []int {\n\tindex := make([]int, dataLen)\n\tfor i := 0; i < dataLen; i++ {\n\t\tindex[i] = i\n\t}\n\tquicksort(index, 0, dataLen-1, lessFunc)\n\treturn index\n}", "func NewIndex(data []byte) (*Index, error) {\n\tvar i Index\n\tdec := gob.NewDecoder(bytes.NewBuffer(data))\n\tif err := dec.Decode(&i); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &i, nil\n}", "func newSegmentKeysIndex(quota int, srcKeyCount int,\n\tkeyAvgSize int) *segmentKeysIndex {\n\tnumIndexableKeys := quota / (keyAvgSize + 4 /* 4 for the offset */)\n\tif numIndexableKeys == 0 {\n\t\treturn nil\n\t}\n\n\thop := (srcKeyCount / numIndexableKeys) + 1\n\n\tdata := make([]byte, numIndexableKeys*keyAvgSize)\n\toffsets := make([]uint32, numIndexableKeys)\n\n\treturn &segmentKeysIndex{\n\t\tnumIndexableKeys: numIndexableKeys,\n\t\tnumKeys: 0,\n\t\tnumKeyBytes: 0,\n\t\tdata: data,\n\t\toffsets: offsets,\n\t\thop: hop,\n\t\tsrcKeyCount: srcKeyCount,\n\t}\n}", "func (i *IndexTile) IndexFromBytes(b []byte) error {\n\tif len(b) < 21 {\n\t\treturn fmt.Errorf(\"Illegal IndexTile: too few bytes (%d)\", len(b))\n\t}\n\tdataShape, err := dvid.BytesToDataShape(b[0:dvid.DataShapeBytes])\n\tif err != nil {\n\t\treturn err\n\t}\n\tscaling := Scaling(b[dvid.DataShapeBytes])\n\terr = i.IndexZYX.IndexFromBytes(b[dvid.DataShapeBytes+2:])\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.plane = dataShape\n\ti.scaling = scaling\n\treturn nil\n}", "func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}", "func (ht *historyTable) newSearch() {\n\tfor i := range ht {\n\t\tht[i].stat /= 8\n\t}\n}", "func New(data []byte) []byte {\n\tresult := sha256.Sum256(data)\n\treturn result[:]\n}", "func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}", "func bytesGetItem(o Object, index Object) Object {\n\tt := o.Type()\n\tvalue := o.(Bytes).Value()\n\tif index.IsInstance(IntType) {\n\t\ti := seqCheckedIndex(t, len(value), index.(Int).Value())\n\t\treturn NewInt(int(value[i]))\n\t} else if index.IsInstance(SliceType) {\n\t\tstart, stop, step, len := index.(Slice).CalcSlice(len(value))\n\t\tif step == 1 {\n\t\t\treturn NewBytes(value[start:stop]...)\n\t\t}\n\t\tsliced := make([]byte, len)\n\t\ti := 0\n\t\tfor j := start; j != stop; j += step {\n\t\t\tsliced[i] = value[j]\n\t\t\ti++\n\t\t}\n\t\treturn NewBytes(sliced...)\n\t} else {\n\t\tpanic(RaiseType(TypeErrorType, fmt.Sprintf(\n\t\t\t\"%s indices must be integers or slices, not %s\",\n\t\t\tt.Name(), index.Type().Name())))\n\t}\n}", "func newIndex(name string) (index *ind) {\n\tindex = new(ind)\n\tindex.name = name\n\tindex.Storage = map[string][]string{}\n\tindex.Domains = map[string]bool{}\n\treturn\n}", "func newTestList() LinkedList {\n\treturn newList(16384, 8192, func(baseIdx int, data []int) {\n\t\tfor i := range data {\n\t\t\tdata[i] = baseIdx + i\n\t\t}\n\t})\n}", "func Index(a, b []byte) int", "func newKey() key {\n\treturn &[32]byte{}\n}", "func NewData() *Data {\n\tnmap := make(map[interface{}]int)\n\treturn &Data{\n\t\tm: nmap,\n\t}\n\t// return make(Data)\n}", "func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}", "func createBatch(xs []*storobj.Object) indexedBatch {\n\tvar bi indexedBatch\n\tbi.Data = xs\n\tbi.Index = make([]int, len(xs))\n\tfor i := 0; i < len(xs); i++ {\n\t\tbi.Index[i] = i\n\t}\n\treturn bi\n}", "func New(path string) (ip *Indexio, err error) {\n\tvar i Indexio\n\t// Initialize functions map for marshaling and unmarshaling\n\tfm := turtleDB.NewFuncsMap(marshal, unmarshal)\n\t// Create new instance of turtleDB\n\tif i.db, err = turtleDB.New(\"indexio\", path, fm); err != nil {\n\t\treturn\n\t}\n\t// Initialize indexes bucket\n\tif err = i.db.Update(initBucket); err != nil {\n\t\treturn\n\t}\n\t// Assign ip as a pointer to i\n\tip = &i\n\treturn\n}", "func (z *Writer) newBuffers() {\n\tbSize := z.Header.BlockMaxSize\n\tbuf := getBuffer(bSize)\n\tz.data = buf[:bSize] // Uncompressed buffer is the first half.\n}", "func newFromBytes(bytes []byte) BitStream {\n\tresult := New()\n\tfor _, b := range bytes {\n\t\tnewBS := NewFromFullByte(b)\n\t\tresult.Append(newBS)\n\t}\n\n\treturn result\n}", "func newIndexedConcat() concat {\n\tnl := []byte{byte('\\n')}\n\treturn concat{\n\t\tjoin: func(element store.Element) ([]byte, error) {\n\t\t\tb, err := Concat(len(element.Value)+len(nl), element.Value, nl)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not serialize value %w\", err)\n\t\t\t}\n\t\t\treturn b, nil\n\t\t},\n\t\tsplit: func(key store.Key, data []byte) (store.Element, error) {\n\t\t\tn := len(data) - len(nl)\n\t\t\treturn store.NewElement(key, data[0:n]), nil\n\t\t},\n\t}\n}", "func NewDataNode(lens StreamIndex) DataNode {\n\tl, restLens := lens.PopIndex()\n\tdata := make([]DataNode, l)\n\tif !restLens.Empty() {\n\t\tfor i := 0; i < l; i++ {\n\t\t\tdata[i] = NewDataNode(restLens)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < l; i++ {\n\t\t\tdata[i] = &streamLeaf{nil}\n\t\t}\n\t}\n\treturn &streamNode{data}\n}", "func newIndexCache(size uint64) *indexCache {\n\treturn &indexCache{sizecache.New(size), sync.NewCond(&sync.Mutex{}), map[addr]struct{}{}}\n}", "func New(values ...uint16) (l *List) {\n\tl = &List{} // init the ptr\n\tfor _, value := range values {\n\t\tl.Insert(value)\n\t}\n\treturn l\n}", "func (x *Index) Lookup(s []byte, n int) (result []int) {}", "func IndexLookup(x *suffixarray.Index, s []byte, n int) []int", "func (ix *Index) bytes() (*[]byte, error) {\n\tb, err := jsonBytes(ix)\n\treturn &b, err\n}", "func (w *Writer) newAccessor(nodes map[node.ID][]byte) *shardAccessor {\n\t// For any node that HStar3 reads, it also writes its sibling. Therefore we\n\t// can pre-allocate this many items for the writes slice.\n\t// TODO(pavelkalinnikov): The actual number of written nodes will be slightly\n\t// bigger by at most the number of written leaves. Try allocating precisely.\n\twrites := make([]Node, 0, len(nodes))\n\treturn &shardAccessor{w: w, reads: nodes, writes: writes}\n}", "func (tree *Tree23) newNode() TreeNodeIndex {\n\n\t// Recycle a deleted node.\n\tif tree.treeNodesFreePositions.len() > 0 {\n\t\tnode := TreeNodeIndex(tree.treeNodesFreePositions.pop())\n\t\treturn node\n\t}\n\n\t// Resize the cache and get more memory.\n\t// Resize our cache by 2x or 1.25x of the previous length. This is in accordance to slice append resizing.\n\tl := len(tree.treeNodes)\n\tif tree.treeNodesFirstFreePos >= l {\n\t\tappendSize := int(float64(l) * 1.25)\n\t\tif l < 1000 {\n\t\t\tappendSize = l * 2\n\t\t}\n\t\ttree.treeNodes = append(tree.treeNodes, make([]treeNode, appendSize)...)\n\t}\n\n\t// Get node from cached memory.\n\ttree.treeNodesFirstFreePos++\n\treturn TreeNodeIndex(tree.treeNodesFirstFreePos - 1)\n}", "func New() *Data {\n\treturn &Data{Values: make(map[Key][]byte)}\n}", "func newDefinitionsIndex(definitions []clusterv1.ClusterClassStatusVariable) definitionsIndex {\n\ti := definitionsIndex{}\n\tfor _, def := range definitions {\n\t\ti.store(def)\n\t}\n\treturn i\n}", "func (x *Index) Lookup(s []byte, n int) (result []int)", "func (b *buffer) index(i uint32) *unsafe.Pointer {\n\treturn risky.Index(unsafe.Pointer(&b.data), ptrSize, uintptr(i))\n}", "func getIndices(b []byte) [16]int {\n\n\tif len(b) != 6 {\n\t\tpanic(\"invalid index array size\")\n\t}\n\n\tdata := binary.BigEndian.Uint64(append([]byte{0, 0}, b...))\n\n\tix := [16]int{}\n\tfor i := 0; i < 16; i++ {\n\t\t//Bit shift data right by i*3 and & with 0x0111 to get index\n\t\tix[i] = int((data >> uint(i*3)) & 7)\n\t}\n\treturn ix\n}", "func NewIndexed(filepath string) (*ListFile, error) {\n\tfile, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while OpenFile: %s\", err)\n\t}\n\n\tlf := &ListFile{\n\t\tfile: file,\n\t\tmu: &sync.RWMutex{},\n\t\t// Main index for the lines of the file:\n\t\tmainIndex: hashsearch.New(),\n\t\t// Allow to create custom indexes:\n\t\tsecondaryIndexes: make(map[string]*Index),\n\t}\n\n\terr = lf.loadExistingToMainIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loadExistingToMainIndex: %s\", err)\n\t}\n\n\treturn lf, nil\n}", "func newDocumentIndex(opts *iface.CreateDocumentDBOptions) iface.StoreIndex {\n\treturn &documentIndex{\n\t\tindex: map[string][]byte{},\n\t\topts: opts,\n\t}\n}", "func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0}\n}", "func readPosIndex(posIndexFilename string) (*dataIndex, error) {\n index := dataIndex{}\n\n infile, err := os.Open(posIndexFilename)\n defer infile.Close()\n if err != nil {\n return nil, fmt.Errorf(\"can't open %s: %v\", posIndexFilename, err)\n }\n r := bufio.NewReader(infile)\n if (r == nil) {\n return nil, fmt.Errorf(\"can't read %s: %v\" + posIndexFilename, err)\n }\n\n var readerr error = nil\n for ; readerr == nil ; {\n bytebuf, readerr := r.ReadBytes('\\n')\n if readerr != nil && readerr != io.EOF {\n panic(readerr)\n }\n if len(bytebuf) == 0 {\n break;\n }\n line := string(bytebuf)\n if line[0:2] == \" \" {\n // comment line\n continue\n }\n fields := strings.SplitN(strings.TrimSpace(line), \" \", -1)\n lemma := readStoredLemma(fields[0])\n pos_tag := oneCharPosTagToPosId(fields[1])\n synset_cnt, _ := strconv.Atoi(fields[2]) // number of senses of the <lemma, pos> pair\n p_cnt, _ := strconv.Atoi(fields[3]) // number of different pointers that lemma has in all synsets containing it.\n field_index := 4\n relationships := make([]int, p_cnt)\n // consume p_cnt pointer symbols\n for i := 0; i < p_cnt; i++ {\n relationships[i], _ = RELATIONSHIP_POINTER_SYMBOLS[fields[field_index]]\n field_index++\n }\n field_index++ // sense_cnt is redundant with synset_cnt, so skip it\n tagsense_cnt, _ := strconv.Atoi(fields[field_index])\n field_index++\n synsetOffsets := make([]int, synset_cnt)\n for i := 0; i < synset_cnt; i++ {\n synsetOffsets[i], _ = strconv.Atoi(fields[field_index])\n field_index++\n }\n\n _, exists := index[lemma]\n if exists {\n fmt.Printf(\"WARNING: %s already exists. Overwriting.\\n\", lemma)\n }\n index[lemma] = DataIndexEntry {\n PartOfSpeech: pos_tag,\n SynsetCount: synset_cnt,\n Relationships: relationships,\n TagSenseCount: tagsense_cnt,\n SynsetOffsets: synsetOffsets,\n }\n }\n\n return &index, nil\n}", "func newArray(from, to int) (result []int) {\n\tresult = make([]int, to-from+1)\n\tfor i := 0; i < cap(result); i++ {\n\t\tresult[i] = from + i\n\t}\n\treturn result\n}", "func (allc *Allocator) new(size uint32) uint32 {\n\t// Multiple goroutines might modify offset value.\n\t// We need to calculate new offset atomically.\n\t// TODO overflow\n\tnewOffset := atomic.AddUint32(&allc.offset, size)\n\treturn newOffset - size\n}", "func newpcdataprog(prog *obj.Prog, index int32) *obj.Prog {\n\tvar from Node\n\tvar to Node\n\n\tNodconst(&from, Types[TINT32], obj.PCDATA_StackMapIndex)\n\tNodconst(&to, Types[TINT32], int64(index))\n\tpcdata := unlinkedprog(obj.APCDATA)\n\tpcdata.Lineno = prog.Lineno\n\tNaddr(&pcdata.From, &from)\n\tNaddr(&pcdata.To, &to)\n\treturn pcdata\n}", "func (s *Server) getIndexes(w http.ResponseWriter, r *http.Request) {\n\tfs, err := s.db.List(\"file\")\n\tif err != nil {\n\t\ts.logf(\"error listing files from mpd for building indexes: %v\", err)\n\t\twriteXML(w, errGeneric)\n\t\treturn\n\t}\n\tfiles := indexFiles(fs)\n\n\twriteXML(w, func(c *container) {\n\t\tc.Indexes = &indexesContainer{\n\t\t\tLastModified: time.Now().Unix(),\n\t\t}\n\n\t\t// Incremented whenever it's time to create a new index for a new\n\t\t// initial letter\n\t\tidx := -1\n\n\t\tvar indexes []index\n\n\t\t// A set of initial characters, used to deduplicate the addition of\n\t\t// nwe indexes\n\t\tseenChars := make(map[rune]struct{}, 0)\n\n\t\tfor _, f := range files {\n\t\t\t// Filter any non-top level items\n\t\t\tif strings.Contains(f.Name, string(os.PathSeparator)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Initial rune is used to create an index name\n\t\t\tc, _ := utf8.DecodeRuneInString(f.Name)\n\t\t\tname := string(c)\n\n\t\t\t// If initial rune is a digit, put index under a numeric section\n\t\t\tif unicode.IsDigit(c) {\n\t\t\t\tc = '#'\n\t\t\t\tname = \"#\"\n\t\t\t}\n\n\t\t\t// If a new rune appears, create a new index for it\n\t\t\tif _, ok := seenChars[c]; !ok {\n\t\t\t\tseenChars[c] = struct{}{}\n\t\t\t\tindexes = append(indexes, index{Name: name})\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\tindexes[idx].Artists = append(indexes[idx].Artists, artist{\n\t\t\t\tName: f.Name,\n\t\t\t\tID: strconv.Itoa(f.ID),\n\t\t\t})\n\t\t}\n\n\t\tc.Indexes.Indexes = indexes\n\t})\n}", "func (tf tFiles) newIndexIterator(tops *tOps, icmp *iComparer, slice *util.Range, ro *opt.ReadOptions) iterator.IteratorIndexer {\n\tif slice != nil {\n\t\tvar start, limit int\n\t\tif slice.Start != nil {\n\t\t\tstart = tf.searchMax(icmp, internalKey(slice.Start))\n\t\t}\n\t\tif slice.Limit != nil {\n\t\t\tlimit = tf.searchMin(icmp, internalKey(slice.Limit))\n\t\t} else {\n\t\t\tlimit = tf.Len()\n\t\t}\n\t\ttf = tf[start:limit]\n\t}\n\treturn iterator.NewArrayIndexer(&tFilesArrayIndexer{\n\t\ttFiles: tf,\n\t\ttops: tops,\n\t\ticmp: icmp,\n\t\tslice: slice,\n\t\tro: ro,\n\t})\n}", "func NewData() *Data {\n d := &Data{}\n d.hashMap = make(map[int]string)\n return d\n}", "func newShortTestList() LinkedList {\n\treturn newList(1024, 8*1024, func(baseIdx int, data []int) {\n\t\tfor i := range data {\n\t\t\tdata[i] = baseIdx + i\n\t\t}\n\t})\n}", "func Constructor(length int) SnapshotArray {\n\ts := make([]map[int]int, 0, 128)\n\tc := make(map[int]int, 32)\n\treturn SnapshotArray{\n\t\tsnaps: s,\n\t\tcurrent: c,\n\t\tid: 0,\n\t}\n}", "func (x *Index) Read(r io.Reader) error", "func newDataset(epoch uint64) interface{} {\n\tds := &dataset{\n\t\tepoch: epoch,\n\t\tdateInit: 0,\n\t\tdataset: make([]uint64, TBLSIZE*DATALENGTH*PMTSIZE*32),\n\t}\n\t//truehashTableInit(ds.evenDataset)\n\n\treturn ds\n}", "func newLoadIndex(f *rule.File, after []string) int {\n\tif len(after) == 0 {\n\t\treturn 0\n\t}\n\tindex := 0\n\tfor _, r := range f.Rules {\n\t\tfor _, a := range after {\n\t\t\tif r.Kind() == a && r.Index() >= index {\n\t\t\t\tindex = r.Index() + 1\n\t\t\t}\n\t\t}\n\t}\n\treturn index\n}", "func createIndexes(ts *Schema, ti *Info, idxs []schema.Index, store *stor.Stor) {\n\tif len(idxs) == 0 {\n\t\treturn\n\t}\n\tts.Indexes = slices.Clip(ts.Indexes) // copy on write\n\tnold := len(ts.Indexes)\n\tfor i := range idxs {\n\t\tix := &idxs[i]\n\t\tif ts.FindIndex(ix.Columns) != nil {\n\t\t\tpanic(\"duplicate index: \" +\n\t\t\t\tstr.Join(\"(,)\", ix.Columns) + \" in \" + ts.Table)\n\t\t}\n\t\tts.Indexes = append(ts.Indexes, *ix)\n\t}\n\tidxs = ts.SetupNewIndexes(nold)\n\tn := len(ti.Indexes)\n\tti.Indexes = slices.Clip(ti.Indexes) // copy on write\n\tfor i := range idxs {\n\t\tbt := btree.CreateBtree(store, &ts.Indexes[n+i].Ixspec)\n\t\tti.Indexes = append(ti.Indexes, index.OverlayFor(bt))\n\t}\n}", "func (t ObjectType) NewData(baseType interface{}, sliceLen, bufSize int) ([]*Data, error) {\n\treturn t.conn.NewData(baseType, sliceLen, bufSize)\n}", "func (self *LSHforest) Index() {\n\t// iterate over the empty indexed hash tables\n\tfor i := range self.hashTables {\n\t\t// transfer contents from the corresponding band in the initial hash table\n\t\tfor HashedSignature, keys := range self.InitialHashTables[i] {\n\t\t\tself.hashTables[i] = append(self.hashTables[i], band{HashedSignature, keys})\n\t\t}\n\t\t// sort the new hashtable and store it in the corresponding slot in the indexed hash tables\n\t\tsort.Sort(self.hashTables[i])\n\t\t// clear the initial hashtable that has just been processed\n\t\tself.InitialHashTables[i] = make(initialHashTable)\n\t}\n}", "func indexEnc() {\n\tfor i := 0; i < indexSize; i++ {\n\t\tindexItemEnc(testData[i], i)\n\t}\n}", "func newPage(db *Database, pageHead *pageHead) *page {\n\tp := page{\n\t\tdb: db,\n\t\tindex: db.dbHead.pageCount + 1,\n\t\tpageHead: pageHead,\n\t\tdata: make([]byte, db.dbHead.pageSize-PAGE_HEAD_SIZE),\n\t}\n\tdb.dbHead.pageCount++\n\tdb.writeHead()\n\treturn &p\n}", "func (x *Index) Read(r io.Reader) error {}", "func NewFromByteSlice(items []byte) *SliceOfByte {\n\tslicy := &SliceOfByte{items}\n\treturn slicy\n}", "func newItems() *items {\n\treturn &items{\n\t\tdata: make([]*list, 0),\n\t\tlen: 0,\n\t}\n}", "func newOffsetInjector(c *cluster) *offsetInjector {\n\treturn &offsetInjector{c: c}\n}", "func New(index bleve.Index, name string) (*Lexicon, error) {\n\tlexicon, err := OpenOrCreate(\"lexicon.bleve\", LexiconMapping)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbatch := lexicon.NewBatch()\n\tdict, err := index.FieldDict(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tentry, err := dict.Next()\n\t\tif err != nil || entry == nil {\n\t\t\tbreak\n\t\t}\n\t\terr = batch.Index(entry.Term, token{Value: entry.Term})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr = lexicon.Batch(batch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Lexicon{\n\t\tIndex: lexicon,\n\t\tMaxDiff: 2,\n\t}, nil\n}", "func newBuffer(buf []byte) *Buffer {\n\treturn &Buffer{data: buf}\n}", "func New(size int) *DB {\n\treturn &DB{\n\t\tdocs: make(map[int][]byte, size),\n\t\tall: intset.NewBitSet(0),\n\t}\n}", "func (client *RPCClient) getLocalIndex() map[string]FileMetaData {\n\tlocalIndex := map[string]FileMetaData{}\n\tpath := client.BaseDir + \"/\" + INDEX_FILE\n\n\tif fileExists(client.BaseDir + \"/\" + INDEX_FILE) {\n\t\tcontent, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlines := bytes.Split(content, []byte(\"\\n\"))\n\t\tfor _, line := range lines {\n\t\t\tif len(line) < 2 {\n\t\t\t\tcontinue //ignore \"\" and \" \" lines\n\t\t\t}\n\t\t\tpLine := bytes.Split(line, []byte(\",\"))\n\t\t\tfname := string(pLine[0])\n\t\t\tv, _ := strconv.Atoi(string(pLine[1]))\n\t\t\thList := strings.Split(string(pLine[2]), \" \")\n\t\t\tmetaData := FileMetaData{Filename: fname, Version: v, BlockHashList: hList}\n\t\t\tlocalIndex[fname] = metaData\n\t\t}\n\t} else { // if file doesn't exist, create it\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tf.Close()\n\t}\n\n\treturn localIndex\n}", "func NewBinary(d []byte) *Binary {\n\treturn &Binary{d, -1}\n}", "func NewBinary(d []byte) *Binary {\n\treturn &Binary{d, -1}\n}", "func generateIndex(textsNumber int, wordsNumber int) *Index {\n\ttitles := make([]string, textsNumber)\n\tentries := make(map[string]Set)\n\tfor i := 0; i < textsNumber; i++ {\n\t\ttitles[i] = fmt.Sprintf(\"title-with-number-%d\", i)\n\t}\n\tfor i := 0; i < wordsNumber; i++ {\n\t\tset := Set{}\n\t\tfor j := 0; j < textsNumber; j++ {\n\t\t\tset.Put(j)\n\t\t}\n\t\tentries[fmt.Sprintf(\"w%d\", i)] = set\n\t}\n\treturn &Index{\n\t\tTitles: titles,\n\t\tData: entries,\n\t}\n}", "func newFileRepositoryIndex(ctxt context.Context, repoName string) (*fileRepositoryIndex, error) {\n\n\tindex := &fileRepositoryIndex{}\n\n\tindex.repoName = repoName\n\n\tindex.repoDir = filepath.Join(file.RepositoriesDirPath(ctxt), repoName)\n\n\tindex.path = filepath.Join(index.repoDir, file.IndexFileName)\n\n\tif !file.DirExists(index.repoDir) {\n\t\treturn nil, errors.NotFound.Newf(\"repository directory at %s does not exist\",\n\t\t\tindex.repoDir)\n\t}\n\n\treturn index, nil\n\n}", "func New(i int) *Buffer {\n\treturn &Buffer{\n\t\tsize: i,\n\t}\n}", "func TestEngine_WriteIndex_Append(t *testing.T) {\n\te := OpenDefaultEngine()\n\tdefer e.Close()\n\n\t// Append points to index.\n\tif err := e.WriteIndex(map[string][][]byte{\n\t\t\"cpu\": [][]byte{\n\t\t\tappend(u64tob(1), 0x10),\n\t\t\tappend(u64tob(2), 0x20),\n\t\t},\n\t\t\"mem\": [][]byte{\n\t\t\tappend(u64tob(0), 0x30),\n\t\t},\n\t}, nil, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Start transaction.\n\ttx := e.MustBegin(false)\n\tdefer tx.Rollback()\n\n\t// Iterate over \"cpu\" series.\n\tc := tx.Cursor(\"cpu\")\n\tif k, v := c.Seek(u64tob(0)); !reflect.DeepEqual(k, []byte{0, 0, 0, 0, 0, 0, 0, 1}) || !reflect.DeepEqual(v, []byte{0x10}) {\n\t\tt.Fatalf(\"unexpected key/value: %x / %x\", k, v)\n\t} else if k, v = c.Next(); !reflect.DeepEqual(k, []byte{0, 0, 0, 0, 0, 0, 0, 2}) || !reflect.DeepEqual(v, []byte{0x20}) {\n\t\tt.Fatalf(\"unexpected key/value: %x / %x\", k, v)\n\t} else if k, _ = c.Next(); k != nil {\n\t\tt.Fatalf(\"unexpected key/value: %x / %x\", k, v)\n\t}\n\n\t// Iterate over \"mem\" series.\n\tc = tx.Cursor(\"mem\")\n\tif k, v := c.Seek(u64tob(0)); !reflect.DeepEqual(k, []byte{0, 0, 0, 0, 0, 0, 0, 0}) || !reflect.DeepEqual(v, []byte{0x30}) {\n\t\tt.Fatalf(\"unexpected key/value: %x / %x\", k, v)\n\t} else if k, _ = c.Next(); k != nil {\n\t\tt.Fatalf(\"unexpected key/value: %x / %x\", k, v)\n\t}\n}", "func NewCursor(b []byte, startIndex int) (c Cursor) {\n\tc.Index = startIndex\n\tc.bytes = b\n\treturn c\n}", "func NewBulk(data []byte) *EncodeData {\n\tans := &EncodeData{}\n\tans.Type = TypeBulk\n\tans.Value = data\n\treturn ans\n}", "func CreateBleveMemIndex() (bleve.Index, error) {\n\t// Create a new index.\n\tmapping := bleve.NewIndexMapping()\n\tindex, err := bleve.NewMemOnly(mapping)\n\treturn index, err\n}", "func NewMainDataIndex() (*DataIndex, error) {\n\tif mainDataIndex != nil {\n\t\treturn mainDataIndex, nil\n\t}\n\n\ti := &DataIndex{Name: mainIndexName}\n\terr := error(nil)\n\n\ti.Http, err = NewHttpClient(i.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.BlobStore, err = NewS3Store(\"datadex.archives\", i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmainDataIndex = i\n\treturn mainDataIndex, nil\n}", "func newLeafListBytes(values [][]byte) *TypedLeafListBytes {\n\tbytes := make([]byte, 0)\n\ttypeopts := make([]int32, 0)\n\tfor _, v := range values {\n\t\tbytes = append(bytes, v...)\n\t\ttypeopts = append(typeopts, int32(len(v)))\n\t}\n\ttypedLeafListBytes := TypedLeafListBytes{\n\t\tBytes: bytes,\n\t\tType: ValueType_LEAFLIST_BYTES, // Contains the lengths of each byte array in list\n\t\tTypeOpts: typeopts,\n\t}\n\treturn &typedLeafListBytes\n}", "func genValue(i int, ev *replication.BinlogEvent) []byte {\n\traw := ev.RawData\n\trowValueIndex := ev.Event.(*replication.RowsEvent).RowValueIndex\n\treturn raw[rowValueIndex[i]:rowValueIndex[i+1]] // 共享内存\n}", "func (cs *UnsafeCounterIndex) Pack() {\n\tif len(cs.counters) == 0 {\n\t\treturn\n\t}\n\tcounters := make([]Counter, 0, len(cs.counters))\n\tfor h, idx := range cs.index {\n\t\tpacked := idx[:0]\n\t\tfor _, i := range idx {\n\t\t\tc := cs.Get(i)\n\t\t\tif c.Count != 0 {\n\t\t\t\tpacked = append(packed, len(counters))\n\t\t\t\tcounters = append(counters, Counter{\n\t\t\t\t\tCount: c.Count,\n\t\t\t\t\tValues: c.Values,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif len(packed) == 0 {\n\t\t\tdelete(cs.index, h)\n\t\t} else {\n\t\t\tcs.index[h] = packed\n\t\t}\n\t}\n\tcs.counters = counters\n}", "func New(dataset []float64) *LearnedIndex {\n\n\tst := search.NewSortedTable(dataset)\n\t// store.Flush(st)\n\n\tx, y := linear.Cdf(st.Keys)\n\tlen_ := len(dataset)\n\tm := linear.Fit(x, y)\n\tguesses := make([]int, len_)\n\tscaledY := make([]int, len_)\n\tmaxErr, minErr := 0, 0\n\tfor i, k := range x {\n\t\tguesses[i] = scale(m.Predict(k), len_)\n\t\tscaledY[i] = scale(y[i], len_)\n\t\tresidual := residual(guesses[i], scaledY[i])\n\t\tif residual > maxErr {\n\t\t\tmaxErr = residual\n\t\t} else if residual < minErr {\n\t\t\tminErr = residual\n\t\t}\n\t}\n\treturn &LearnedIndex{M: m, Len: len_, ST: st, MinErrBound: minErr, MaxErrBound: maxErr}\n}", "func grow(s reflect.Value, extra int) (reflect.Value, int, int) {\n\ti0 := s.Len()\n\ti1 := i0 + extra\n\tif i1 < i0 {\n\t\tpanic(\"reflect.Append: slice overflow\")\n\t}\n\tm := s.Cap()\n\tif i1 <= m {\n\t\treturn s.Slice(0, i1), i0, i1\n\t}\n\tif m == 0 {\n\t\tm = extra\n\t} else {\n\t\tfor m < i1 {\n\t\t\tif i0 < 1024 {\n\t\t\t\tm += m\n\t\t\t} else {\n\t\t\t\tm += m / 4\n\t\t\t}\n\t\t}\n\t}\n\tt := reflect.MakeSlice(s.Type(), i1, m)\n\treflect.Copy(t, s)\n\treturn t, i0, i1\n}", "func (cs *CounterIndex) Pack() {\n\tcs.mu.Lock()\n\tcs.index.Pack()\n\tcs.mu.Unlock()\n}", "func (m Mixtape) buildIndex() MixtapeIndex{\n\tmi := MixtapeIndex{}\n\t// Initialize the MixtapeIndex structure so its variables aren't nil\n\tmi.init()\n\n\t// Note for the below, as per the spec, `:=` re-uses the variable in the loop's scope. In the context of pointers,\n\t// it means it will be the same address in each operation.\n\t// Index the Users\n\tfor i, _ := range m.Users {\n\t\tu := m.Users[i]\n\t\tmi.Users[u.Id] = &u\n\t}\n\n\t// Index the Playlists\n\tfor i, _ := range m.Playlists {\n\t\tp := m.Playlists[i]\n\t\tmi.Playlists[p.Id] = &p\n\n\t\t// Keep the playlist upper bound index updated\n\t\tid, _ := strconv.Atoi(p.Id)\n\t\tfmt.Println(id)\n\t\tif id > mi.PlaylistIdUpperBound {\n\t\t\tmi.PlaylistIdUpperBound = id\n\t\t}\n\t}\n\n\t// Index the Songs\n\tfor i, _ := range m.Songs{\n\t\ts := m.Songs[i]\n\t\tmi.Songs[s.Id] = &s\n\t}\n\n\tfmt.Printf(\"Mixtape Index: \\n%#v\\n\", mi)\n\n\treturn mi\n}", "func newData(name string, data []byte) *FsData {\n\treturn &FsData{*newFile(name), data}\n}", "func New(path string) (*Index, error) {\n\tkvdb, err := pudge.Open(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Index{\n\t\tdb: kvdb,\n\t\tpath: path,\n\t}, nil\n}", "func New(ds datastore.TxnDatastore, api API, h P2PHost, lr iplocation.LocationResolver) (*MinerIndex, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\tmi := &MinerIndex{\n\t\tapi: api,\n\t\tds: ds,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\th: h,\n\t\tlr: lr,\n\t\tchMeta: make(chan struct{}, 1),\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}, 2),\n\t}\n\tif err := mi.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo mi.start()\n\tgo mi.metaWorker()\n\treturn mi, nil\n}", "func newLevelSlice(iter iterator) LevelSlice {\n\ts := LevelSlice{iter: iter}\n\tif iter.r != nil {\n\t\ts.length = iter.r.subtreeCount\n\t}\n\ts.verifyInvariants()\n\treturn s\n}", "func newBaseCount() baseCount {\n\treturn baseCount{words: make(map[word]int)}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_metadata_metadata_proto_rawDescGZIP(), []int{0}\n}", "func (i *IndexedData) Assemble() error {\n\n\ti.values = i.ValuesBuffer.Bytes()\n\ti.ValuesBuffer = bytes.Buffer{}\n\n\treturn i.assembleBlockReferences()\n}", "func (c *index) Create(sctx sessionctx.Context, rm kv.RetrieverMutator, indexedValues []types.Datum, h int64, opts ...table.CreateIdxOptFunc) (int64, error) {\n\tvar opt table.CreateIdxOpt\n\tfor _, fn := range opts {\n\t\tfn(&opt)\n\t}\n\tss := opt.AssertionProto\n\twriteBufs := sctx.GetSessionVars().GetWriteStmtBufs()\n\tskipCheck := sctx.GetSessionVars().LightningMode || sctx.GetSessionVars().StmtCtx.BatchCheck\n\tkey, distinct, err := c.GenIndexKey(sctx.GetSessionVars().StmtCtx, indexedValues, h, writeBufs.IndexKeyBuf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tctx := opt.Ctx\n\tif opt.Untouched {\n\t\ttxn, err1 := sctx.Txn(true)\n\t\tif err1 != nil {\n\t\t\treturn 0, err1\n\t\t}\n\t\t// If the index kv was untouched(unchanged), and the key/value already exists in mem-buffer,\n\t\t// should not overwrite the key with un-commit flag.\n\t\t// So if the key exists, just do nothing and return.\n\t\t_, err = txn.GetMemBuffer().Get(ctx, key)\n\t\tif err == nil {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\n\t// save the key buffer to reuse.\n\twriteBufs.IndexKeyBuf = key\n\tif !distinct {\n\t\t// non-unique index doesn't need store value, write a '0' to reduce space\n\t\tvalue := []byte{'0'}\n\t\tif opt.Untouched {\n\t\t\tvalue[0] = kv.UnCommitIndexKVFlag\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif skipCheck {\n\t\tvalue := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tvalue = append(value, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, value)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.None)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tif ctx != nil {\n\t\tif span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {\n\t\t\tspan1 := span.Tracer().StartSpan(\"index.Create\", opentracing.ChildOf(span.Context()))\n\t\t\tdefer span1.Finish()\n\t\t\tctx = opentracing.ContextWithSpan(ctx, span1)\n\t\t}\n\t} else {\n\t\tctx = context.TODO()\n\t}\n\n\tvar value []byte\n\tvalue, err = rm.Get(ctx, key)\n\t// If (opt.Untouched && err == nil) is true, means the key is exists and exists in TiKV, not in txn mem-buffer,\n\t// then should also write the untouched index key/value to mem-buffer to make sure the data\n\t// is consistent with the index in txn mem-buffer.\n\tif kv.IsErrNotFound(err) || (opt.Untouched && err == nil) {\n\t\tv := EncodeHandle(h)\n\t\tif opt.Untouched {\n\t\t\tv = append(v, kv.UnCommitIndexKVFlag)\n\t\t}\n\t\terr = rm.Set(key, v)\n\t\tif ss != nil {\n\t\t\tss.SetAssertion(key, kv.NotExist)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\thandle, err := DecodeHandle(value)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn handle, kv.ErrKeyExists\n}", "func execNewSlice(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.NewSlice(args[0].(types.Type))\n\tp.Ret(1, ret)\n}", "func (i *index) Read(indexOff int64) (off uint32, indexPos uint64, err error) {\n\tif i.size == 0 {\n\t\treturn 0, 0, io.EOF\n\t}\n\n\trealIndexOff := uint32(indexOff)\n\tif indexOff == -1 {\n\t\trealIndexOff = uint32((i.size / entWidth) - 1)\n\t}\n\n\tindexPos = uint64(realIndexOff) * entWidth\n\tif i.size < indexPos+entWidth {\n\t\treturn 0, 0, io.EOF\n\t}\n\n\tdataOff := enc.Uint32(i.mmap[indexPos : indexPos+offWidth])\n\tdataPos := enc.Uint64(i.mmap[indexPos+offWidth : indexPos+entWidth])\n\treturn dataOff, dataPos, nil\n}" ]
[ "0.79869044", "0.7944773", "0.7573943", "0.5867695", "0.58580136", "0.5837126", "0.5720842", "0.5598529", "0.5588068", "0.54242134", "0.54236424", "0.528123", "0.5256683", "0.5216906", "0.52155143", "0.52113605", "0.5207757", "0.5173901", "0.5173302", "0.5166521", "0.5165284", "0.51431584", "0.5131144", "0.51210374", "0.5120576", "0.5114", "0.5102131", "0.5097731", "0.50636584", "0.50465876", "0.50437224", "0.49915078", "0.49788257", "0.4978811", "0.49750096", "0.496432", "0.4962073", "0.49607903", "0.49554843", "0.49513686", "0.49445534", "0.49412596", "0.4933401", "0.49116975", "0.49098322", "0.4903552", "0.48820466", "0.48818868", "0.48687738", "0.48639137", "0.48561257", "0.48495427", "0.4842507", "0.48373735", "0.48338196", "0.48307437", "0.48221382", "0.4820787", "0.480746", "0.48014078", "0.47970346", "0.47890776", "0.478854", "0.47801322", "0.47733486", "0.47545445", "0.4751714", "0.47479445", "0.47440174", "0.47439128", "0.47397774", "0.47341463", "0.47240973", "0.472388", "0.472388", "0.47097465", "0.47087514", "0.4708121", "0.47079223", "0.47078997", "0.47040877", "0.47035113", "0.46939367", "0.46929988", "0.46911374", "0.46878704", "0.46873122", "0.46871004", "0.46864522", "0.4686213", "0.46837053", "0.4683313", "0.46663257", "0.4665725", "0.4657061", "0.4654725", "0.46541342", "0.46538243", "0.4646715", "0.4637635" ]
0.70452243
3
NewWithReader returns indexes with a reader
func NewWithReader(r io.Reader) []*Index { var ( z = html.NewTokenizer(r) currentLevel int currentText string currentLinkText string currentAnchor string nodeDeep int indexs []*Index ) for { token := z.Next() if token == html.ErrorToken { break } if token == html.EndTagToken { if nodeDeep == 1 && currentLevel > 0 { indexs = append(indexs, &Index{ Level: currentLevel, Title: currentText, Link: currentLinkText, Anchor: currentAnchor, }) currentLevel = 0 currentText = "" currentLinkText = "" currentAnchor = "" nodeDeep-- } continue } if token == html.StartTagToken { name, hasAttr := z.TagName() lv := parseIndexLevel(name) if lv > 0 { currentLevel = lv if hasAttr { for { k, v, isMore := z.TagAttr() if bytes.Equal(k, []byte("id")) { currentAnchor = string(v) } if !isMore { break } } } nodeDeep++ } if currentLevel > 0 && string(name) == "a" { if hasAttr { for { k, v, isMore := z.TagAttr() if bytes.Equal(k, []byte("href")) { currentLinkText = string(v) } if !isMore { break } } } } } if token == html.TextToken && currentLevel > 0 { currentText += string(z.Text()) } } indexs = assembleIndex(indexs) return indexs }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(br *bam.Reader, idxio io.Reader) (*Reader, error) {\n\tidx, err := bam.ReadIndex(idxio)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbx := &Reader{Reader: br, idx: idx}\n\n\tbx.refs = make(map[string]*sam.Reference)\n\tfor _, r := range br.Header().Refs() {\n\t\tbx.refs[r.Name()] = r\n\t}\n\treturn bx, nil\n}", "func New(data []byte) []*Index {\n\treturn NewWithReader(bytes.NewReader(data))\n}", "func (t *tOps) newIterator(f *tFile, slice *util.Range, ro *opt.ReadOptions) iterator.Iterator {\n\tch, err := t.open(f)\n\tif err != nil {\n\t\treturn iterator.NewEmptyIterator(err)\n\t}\n\titer := ch.Value().(*table.Reader).NewIterator(slice, ro)\n\titer.SetReleaser(ch)\n\treturn iter\n}", "func NewReader(opts ReadOpts, dir string) *Reader {\n\tr := &Reader{\n\t\topts: opts,\n\t}\n\tr.err.Set(validateReadOpts(&r.opts))\n\tif r.err.Err() != nil {\n\t\treturn r\n\t}\n\tr.label = fmt.Sprintf(\"%s:u%s\", filepath.Base(dir), CoordRangePathString(r.opts.Range))\n\tvar err error\n\tif r.indexFiles, err = findIndexFilesInRange(dir, r.opts.Range); err != nil {\n\t\tr.err.Set(err)\n\t\treturn r\n\t}\n\tif len(r.indexFiles) == 0 {\n\t\tr.err.Set(errors.Errorf(\"%v: No pam file found for range %+v\", dir, r.opts))\n\t\treturn r\n\t}\n\tvlog.VI(1).Infof(\"Found index files in range %+v: %+v\", r.opts.Range, r.indexFiles)\n\tr.r = NewShardReader(r.opts.Range, r.opts.DropFields, r.indexFiles[0], &r.err)\n\tr.indexFiles = r.indexFiles[1:]\n\treturn r\n}", "func (this *DatastoreOperations) CreateReader(state *DatastoreState, updatedAfter int64) (reader io.Reader, readSize int64, err error) {\n\t// Use the index to find the offset of the first entry matching the condition\n\toffset := state.Index.FindOffsetOfFirstEntryUpdatedAfter(updatedAfter)\n\n\t// If no such entry was found\n\tif offset == -1 {\n\t\t// Return an empty reader with zero length\n\t\treturn EmptyReader{}, 0, nil\n\t}\n\n\t// Create a reader for the range between the offset and the total\n\t// size of the indexed entries (in most cases, this would be the size of the file)\n\treader = NewRangeReader(state.File, offset, int64(state.Size()))\n\n\t// Calculate the read size as the difference between the total size and the read start offset\n\treadSize = state.Size() - offset\n\n\treturn\n}", "func NewReader(readers []table.Reader) Reader {\n\treturn &tagReader{readers: readers}\n}", "func LoadIndexReader(r io.Reader) (*IndexFile, error) {\n\treturn loadIndex(r)\n}", "func (r *Reference) NewReader(ctx context.Context, path iosrc.URI, readspan nano.Span) (*Reader, error) {\n\tsegspan := r.Span()\n\tspan := segspan.Intersect(readspan)\n\tobjectPath := r.RowObjectPath(path)\n\tif span.Dur == 0 {\n\t\treturn nil, fmt.Errorf(\"segment reader: segment does not intersect provided span: %s chunkspan %v readspan %v\", path, segspan, readspan)\n\t}\n\treader, err := iosrc.NewReader(ctx, objectPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsr := &Reader{\n\t\tReader: reader,\n\t\tCloser: reader,\n\t\tTotalBytes: r.Size,\n\t\tReadBytes: r.Size,\n\t}\n\tif span == segspan {\n\t\treturn sr, nil\n\t}\n\ts, err := seekindex.Open(ctx, r.SeekObjectPath(path))\n\tif err != nil {\n\t\tif zqe.IsNotFound(err) {\n\t\t\treturn sr, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer s.Close()\n\trg, err := s.Lookup(ctx, span)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trg = rg.TrimEnd(sr.TotalBytes)\n\tsr.ReadBytes = rg.Size()\n\tsr.Reader, err = rg.LimitReader(reader)\n\treturn sr, err\n}", "func (x *Index) Read(r io.Reader) error", "func (h *HTTPGetter) IndexReader() (io.ReadCloser, error) {\n\tsavePath := path.Join(h.dst, \"index\")\n\tif err := h.underlying.GetFile(savePath, h.idxURL); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.Open(savePath)\n}", "func newFieldReader(path string, shardRange biopb.CoordRange, requestedRange biopb.CoordRange, f gbam.FieldType, errp *errorreporter.T) (*fieldReader, error) {\n\tfr := &fieldReader{\n\t\tfield: f,\n\t\tlabel: fmt.Sprintf(\"%s:s%s:u%s(%v)\",\n\t\t\tfilepath.Base(path), CoordRangePathString(shardRange), CoordRangePathString(requestedRange), f),\n\t\trequestedRange: requestedRange,\n\t\terr: errp,\n\t}\n\tctx := vcontext.Background()\n\tin, err := file.Open(ctx, FieldDataPath(path, shardRange, f))\n\tif err != nil {\n\t\treturn fr, errors.Wrapf(err, \"%v: Failed to open field data file for %v\", path, f)\n\t}\n\tfr.in = in\n\tfr.rin = fr.in.Reader(ctx)\n\tfr.rio = recordio.NewScanner(fr.rin, recordio.ScannerOpts{})\n\ttrailer := fr.rio.Trailer()\n\tif len(trailer) == 0 {\n\t\treturn fr, errors.Errorf(\"%v: file does not contain an index: %v\", path, fr.rio.Err())\n\t}\n\tif err := fr.index.Unmarshal(trailer); err != nil {\n\t\treturn fr, errors.Wrapf(err, \"%v: Failed to unmarshal field index for %v\", path, f)\n\t}\n\treturn fr, nil\n}", "func New(data []byte) *Index {}", "func NewReader(r io.Reader) io.Reader {\n return reader{r}\n}", "func (x *Index) Read(r io.Reader) error {}", "func NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tMaxObjectsLimit: DefaultMaxObjectsLimit,\n\n\t\tr: &trackingReader{r: r},\n\t\toffsets: make(map[int64]core.Hash, 0),\n\t}\n}", "func NewIndexReader(r backend.ContextReader, pageSizeBytes int, totalRecords int) (common.IndexReader, error) {\n\treturn &indexReader{\n\t\tr: r,\n\t\trecordRW: NewRecordReaderWriter(),\n\n\t\tpageSizeBytes: pageSizeBytes,\n\t\ttotalRecords: totalRecords,\n\n\t\tpageCache: map[int]*page{},\n\t}, nil\n}", "func NewReader() Reader {\n\treturn reader{}\n}", "func New(data []byte) *Index", "func NewIndexed(filepath string) (*ListFile, error) {\n\tfile, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while OpenFile: %s\", err)\n\t}\n\n\tlf := &ListFile{\n\t\tfile: file,\n\t\tmu: &sync.RWMutex{},\n\t\t// Main index for the lines of the file:\n\t\tmainIndex: hashsearch.New(),\n\t\t// Allow to create custom indexes:\n\t\tsecondaryIndexes: make(map[string]*Index),\n\t}\n\n\terr = lf.loadExistingToMainIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loadExistingToMainIndex: %s\", err)\n\t}\n\n\treturn lf, nil\n}", "func (d *DB) newRawIterator(ro *opt.ReadOptions) iterator.Iterator {\n\ts := d.s\n\n\tmem := d.getMem()\n\tv := s.version()\n\tdefer v.release()\n\n\tti := v.getIterators(ro)\n\tii := make([]iterator.Iterator, 0, len(ti)+2)\n\tii = append(ii, mem.cur.NewIterator())\n\tif mem.froze != nil {\n\t\tii = append(ii, mem.froze.NewIterator())\n\t}\n\tii = append(ii, ti...)\n\n\treturn iterator.NewMergedIterator(ii, s.cmp)\n}", "func newTableReader(\n\tflowCtx *FlowCtx, spec *TableReaderSpec, output RowReceiver) (*tableReader, error,\n) {\n\ttr := &tableReader{\n\t\toutput: output,\n\t\thardLimit: spec.HardLimit,\n\t\tsoftLimit: spec.SoftLimit,\n\t}\n\n\tif tr.hardLimit != 0 && tr.hardLimit < tr.softLimit {\n\t\treturn nil, errors.Errorf(\"soft limit %d larger than hard limit %d\", tr.softLimit,\n\t\t\ttr.hardLimit)\n\t}\n\n\terr := tr.readerBase.init(flowCtx, &spec.Table, int(spec.IndexIdx), spec.Filter,\n\t\tspec.OutputColumns, spec.Reverse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttr.ctx = log.WithLogTagInt(tr.flowCtx.Context, \"TableReader\", int(tr.desc.ID))\n\n\ttr.spans = make(sqlbase.Spans, len(spec.Spans))\n\tfor i, s := range spec.Spans {\n\t\ttr.spans[i] = sqlbase.Span{Start: s.Span.Key, End: s.Span.EndKey}\n\t}\n\n\treturn tr, nil\n}", "func newCountHashReader(r io.Reader) *countHashReader {\n\treturn &countHashReader{r: r}\n}", "func NewReader(store EntryStore) Reader {\n\treturn defaultReader{\n\t\tstore: store,\n\t}\n}", "func NewReader(sourceKey, filepath, dbFilename string) *Reader {\n\treturn &Reader{\n\t\tSourceKey: sourceKey,\n\t\tPath: filepath,\n\t\tFilename: dbFilename,\n\t}\n}", "func (e *IndexReaderExecutor) Open() error {\n\tfieldTypes := make([]*types.FieldType, len(e.index.Columns))\n\tfor i, v := range e.index.Columns {\n\t\tfieldTypes[i] = &(e.table.Cols()[v.Offset].FieldType)\n\t}\n\tkvRanges, err := indexRangesToKVRanges(e.ctx.GetSessionVars().StmtCtx, e.tableID, e.index.ID, e.ranges, fieldTypes)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.result, err = distsql.SelectDAG(e.ctx.GetClient(), e.ctx.GoCtx(), e.dagPB, kvRanges, e.ctx.GetSessionVars().DistSQLScanConcurrency, e.keepOrder, e.desc)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.result.Fetch(e.ctx.GoCtx())\n\treturn nil\n}", "func CreateNewIndex(rawItems PointArray, dim, nTree, k int, m Metric) (Index, error) {\n\t// verify that given items have same dimension\n\tl := rawItems.Len()\n\tif l < 2 {\n\t\treturn nil, errNotEnoughItems\n\t}\n\tits := make([]*item, l)\n\t//idToItem := make(map[itemId]*item, l)\n\tfor i:=0; i < l; i++{\n\t\tv := rawItems.At(i)\n\t\tif v.Dimension() != dim {\n\t\t\treturn nil, errDimensionMismatch\n\t\t}\n\t\tit := &item{\n\t\t\tid: itemId(i),\n\t\t\tvector: v,\n\t\t}\n\t\tits[i] = it\n\t\t//idToItem[it.id] = it\n\t}\n\tidx := &index{\n\t\tmetric: m,\n\t\tdim: dim,\n\t\tk: k,\n\t\titemIDToItem: rawItems,\n\t\troots: make([]*node, nTree),\n\t\tnodeIDToNode: map[nodeId]*node{},\n\t\tmux: &sync.Mutex{},\n\t}\n\n\t// build\n\tidx.build(its, nTree)\n\treturn idx, nil\n}", "func newFileJSONReader(logger log.Logger, fn string) (*JSONReader, error) {\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"open file\")\n\t}\n\tdefer runutil.CloseWithLogOnErr(logger, f, \"index cache json close\")\n\n\tvar v indexCache\n\n\tbytes, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"read file\")\n\t}\n\n\tif err = json.Unmarshal(bytes, &v); err != nil {\n\t\treturn nil, errors.Wrap(jsonUnmarshalError, err.Error())\n\t}\n\n\tstrs := map[string]string{}\n\tvar maxSymbolID uint32\n\tfor o := range v.Symbols {\n\t\tif o > maxSymbolID {\n\t\t\tmaxSymbolID = o\n\t\t}\n\t}\n\n\tjr := &JSONReader{\n\t\tindexVersion: v.Version,\n\t\tlvals: make(map[string][]string, len(v.LabelValues)),\n\t\tpostings: make(map[labels.Label]index.Range, len(v.Postings)),\n\t\tsymbols: make([]string, maxSymbolID+1),\n\t}\n\n\t// Most strings we encounter are duplicates. Dedup string objects that we keep\n\t// around after the function returns to reduce total memory usage.\n\t// NOTE(fabxc): it could even make sense to deduplicate globally.\n\tgetStr := func(s string) string {\n\t\tif cs, ok := strs[s]; ok {\n\t\t\treturn cs\n\t\t}\n\t\tstrs[s] = s\n\t\treturn s\n\t}\n\n\tfor o, s := range v.Symbols {\n\t\tjr.symbols[o] = getStr(s)\n\t}\n\tfor ln, vals := range v.LabelValues {\n\t\tfor i := range vals {\n\t\t\tvals[i] = getStr(vals[i])\n\t\t}\n\t\tjr.lvals[getStr(ln)] = vals\n\t}\n\tfor _, e := range v.Postings {\n\t\tl := labels.Label{\n\t\t\tName: getStr(e.Name),\n\t\t\tValue: getStr(e.Value),\n\t\t}\n\t\tjr.postings[l] = index.Range{Start: e.Start, End: e.End}\n\t}\n\treturn jr, nil\n}", "func (s ConsoleIndexStore) GetIndexReader(string) (io.ReadCloser, error) {\n\treturn ioutil.NopCloser(os.Stdin), nil\n}", "func NewDataReader(r backend.ContextReader, encoding backend.Encoding) (common.DataReader, error) {\n\tv2DataReader := &dataReader{\n\t\tcontextReader: r,\n\t\tdataReader: v0.NewDataReader(r),\n\t}\n\n\t// wrap the paged reader in a compressed/v1 reader and return that\n\tv1DataReader, err := v1.NewNestedDataReader(v2DataReader, encoding)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v1DataReader, nil\n}", "func New(ds datastore.TxnDatastore, api API, h P2PHost, lr iplocation.LocationResolver) (*MinerIndex, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\tmi := &MinerIndex{\n\t\tapi: api,\n\t\tds: ds,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\th: h,\n\t\tlr: lr,\n\t\tchMeta: make(chan struct{}, 1),\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}, 2),\n\t}\n\tif err := mi.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo mi.start()\n\tgo mi.metaWorker()\n\treturn mi, nil\n}", "func IndexRead(x *suffixarray.Index, r io.Reader) error", "func New(docs []string) *Index {\n\tm := make(map[string]map[int]bool)\n\n\tfor i := 0; i < len(docs); i++ {\n\t\twords := strings.Fields(docs[i])\n\t\tfor j := 0; j < len(words); j++ {\n\t\t\tif m[words[j]] == nil {\n\t\t\t\tm[words[j]] = make(map[int]bool)\n\t\t\t}\n\t\t\tm[words[j]][i+1] = true\n\t\t}\n\t}\n\treturn &(Index{m})\n}", "func NewReader(r io.Reader, rd int) (*Reader, error) {\n\tbg, err := bgzf.NewReader(r, rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th, _ := sam.NewHeader(nil, nil)\n\tbr := &Reader{\n\t\tr: bg,\n\t\th: h,\n\n\t\treferences: int32(len(h.Refs())),\n\t}\n\terr = br.h.DecodeBinary(br.r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbr.lastChunk.End = br.r.LastChunk().End\n\treturn br, nil\n}", "func NewReader(r io.Reader) *Reader { return &Reader{r: r} }", "func NewReader(r io.ReaderAt, size int64) (*zip.Reader, error)", "func newDbIterator(typeName []byte, it iterator, db *leveldb.DB) (*DbIterator, error) {\n\n\tidx := &DbIterator{typeName: typeName, it: it, db: db}\n\n\treturn idx, nil\n}", "func newReader(r io.Reader) *bufio.Reader {\n\t// TODO(nickng): use sync.Pool to reduce allocation per new connection.\n\treturn bufio.NewReader(r)\n}", "func New(ds datastore.TxnDatastore, api *apistruct.FullNodeStruct) (*Index, error) {\n\tcs := chainsync.New(api)\n\tstore, err := chainstore.New(txndstr.Wrap(ds, \"chainstore\"), cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinitMetrics()\n\tctx, cancel := context.WithCancel(context.Background())\n\ts := &Index{\n\t\tapi: api,\n\t\tstore: store,\n\t\tsignaler: signaler.New(),\n\t\tindex: IndexSnapshot{\n\t\t\tMiners: make(map[string]Slashes),\n\t\t},\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tfinished: make(chan struct{}),\n\t}\n\tif err := s.loadFromDS(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo s.start()\n\treturn s, nil\n}", "func newReader(name string, input io.RuneScanner) *reader {\n\tl := &reader{\n\t\tname: name,\n\t\tinput: input,\n\t\tstate: lexItem,\n\t\titems: make(chan item, 2), // Two items of buffering is sufficient for all state functions\n\t}\n\treturn l\n}", "func (tf tFiles) newIndexIterator(tops *tOps, icmp *iComparer, slice *util.Range, ro *opt.ReadOptions) iterator.IteratorIndexer {\n\tif slice != nil {\n\t\tvar start, limit int\n\t\tif slice.Start != nil {\n\t\t\tstart = tf.searchMax(icmp, internalKey(slice.Start))\n\t\t}\n\t\tif slice.Limit != nil {\n\t\t\tlimit = tf.searchMin(icmp, internalKey(slice.Limit))\n\t\t} else {\n\t\t\tlimit = tf.Len()\n\t\t}\n\t\ttf = tf[start:limit]\n\t}\n\treturn iterator.NewArrayIndexer(&tFilesArrayIndexer{\n\t\ttFiles: tf,\n\t\ttops: tops,\n\t\ticmp: icmp,\n\t\tslice: slice,\n\t\tro: ro,\n\t})\n}", "func NewReader(clients []drive.Client, t *time.Ticker) (*Reader, error) {\n\tc := &Reader{\n\t\tclients: clients,\n\t\tnodes: map[string]Node{\n\t\t\t\"/\": {\n\t\t\t\tFilename: \"/\",\n\t\t\t\tChildren: make(map[string]bool),\n\t\t\t}},\n\t}\n\tif err := c.refresh(); err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing cache: %s\", err)\n\t}\n\tgo c.periodicRefresh(t)\n\treturn c, nil\n}", "func New(indexRegistry *registry.IndexRegistry, options ...func(*Index)) (I *Index, err error) {\n\tI = &Index{\n\t\tindexRegistry: indexRegistry,\n\t}\n\n\tfor _, option := range options {\n\t\toption(I)\n\t}\n\n\treturn\n}", "func NewReader(r io.Reader) *Reader {\n\tsc := bufio.NewScanner(r)\n\treturn &Reader{\n\t\tr: r,\n\t\tsc: sc,\n\n\t\tnextNum: 1,\n\t\tresults: make(map[int]*Report),\n\t}\n}", "func New(ioReader io.Reader) (r KafkalogReader, err error) {\n\tr = &reader{\n\t\tioReader: ioReader,\n\t}\n\treturn\n}", "func NewReader(r io.Reader) *csv.Reader", "func NewIndexer(keys []string, dateLayout string) *Indexer {\n\treturn &Indexer{\n\t\tdateLayout: dateLayout,\n\t\tkeys: keys,\n\t}\n}", "func NewReader(p []byte, _ uint64, readers []io.ReadCloser) (io.ReadCloser, error) {\n\tif len(readers) != 1 {\n\t\treturn nil, errors.New(\"delta: need exactly one reader\")\n\t}\n\n\tif len(p) != 1 {\n\t\treturn nil, errors.New(\"delta: not enough properties\")\n\t}\n\n\treturn &readCloser{\n\t\trc: readers[0],\n\t\tdelta: int(p[0] + 1),\n\t}, nil\n}", "func NewReader(r *io.SectionReader) (Reader, error) {\n\tfor _, f := range formats {\n\t\tif match(r, f.magic, f.offset) {\n\t\t\tfmt.Println(f.name, f.magic)\n\t\t\treturn f.newReader(r), nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Unknown Format\")\n}", "func newTableReader(\n\tflowCtx *execinfra.FlowCtx,\n\tprocessorID int32,\n\tspec *execinfrapb.TableReaderSpec,\n\tpost *execinfrapb.PostProcessSpec,\n\toutput execinfra.RowReceiver,\n) (*tableReader, error) {\n\t// NB: we hit this with a zero NodeID (but !ok) with multi-tenancy.\n\tif nodeID, ok := flowCtx.NodeID.OptionalNodeID(); ok && nodeID == 0 {\n\t\treturn nil, errors.Errorf(\"attempting to create a tableReader with uninitialized NodeID\")\n\t}\n\n\ttr := trPool.Get().(*tableReader)\n\n\ttr.limitHint = execinfra.LimitHint(spec.LimitHint, post)\n\t// Parallelize shouldn't be set when there's a limit hint, but double-check\n\t// just in case.\n\ttr.parallelize = spec.Parallelize && tr.limitHint == 0\n\ttr.maxTimestampAge = time.Duration(spec.MaxTimestampAgeNanos)\n\n\ttableDesc := spec.BuildTableDescriptor()\n\tvirtualColumn := tabledesc.FindVirtualColumn(tableDesc, spec.VirtualColumn)\n\tcols := tableDesc.PublicColumns()\n\tif spec.Visibility == execinfra.ScanVisibilityPublicAndNotPublic {\n\t\tcols = tableDesc.DeletableColumns()\n\t}\n\tcolumnIdxMap := catalog.ColumnIDToOrdinalMap(cols)\n\tresultTypes := catalog.ColumnTypesWithVirtualCol(cols, virtualColumn)\n\n\t// Add all requested system columns to the output.\n\tif spec.HasSystemColumns {\n\t\tfor _, sysCol := range tableDesc.SystemColumns() {\n\t\t\tresultTypes = append(resultTypes, sysCol.GetType())\n\t\t\tcolumnIdxMap.Set(sysCol.GetID(), columnIdxMap.Len())\n\t\t}\n\t}\n\n\ttr.ignoreMisplannedRanges = flowCtx.Local\n\tif err := tr.Init(\n\t\ttr,\n\t\tpost,\n\t\tresultTypes,\n\t\tflowCtx,\n\t\tprocessorID,\n\t\toutput,\n\t\tnil, /* memMonitor */\n\t\texecinfra.ProcStateOpts{\n\t\t\t// We don't pass tr.input as an inputToDrain; tr.input is just an adapter\n\t\t\t// on top of a Fetcher; draining doesn't apply to it. Moreover, Andrei\n\t\t\t// doesn't trust that the adapter will do the right thing on a Next() call\n\t\t\t// after it had previously returned an error.\n\t\t\tInputsToDrain: nil,\n\t\t\tTrailingMetaCallback: tr.generateTrailingMeta,\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tneededColumns := tr.Out.NeededColumns()\n\n\tvar fetcher row.Fetcher\n\tif _, _, err := initRowFetcher(\n\t\tflowCtx,\n\t\t&fetcher,\n\t\ttableDesc,\n\t\tint(spec.IndexIdx),\n\t\tcolumnIdxMap,\n\t\tspec.Reverse,\n\t\tneededColumns,\n\t\tspec.IsCheck,\n\t\tflowCtx.EvalCtx.Mon,\n\t\t&tr.alloc,\n\t\tspec.Visibility,\n\t\tspec.LockingStrength,\n\t\tspec.LockingWaitPolicy,\n\t\tspec.HasSystemColumns,\n\t\tvirtualColumn,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tnSpans := len(spec.Spans)\n\tif cap(tr.spans) >= nSpans {\n\t\ttr.spans = tr.spans[:nSpans]\n\t} else {\n\t\ttr.spans = make(roachpb.Spans, nSpans)\n\t}\n\tfor i, s := range spec.Spans {\n\t\ttr.spans[i] = s.Span\n\t}\n\n\tif execinfra.ShouldCollectStats(flowCtx.EvalCtx.Ctx(), flowCtx) {\n\t\ttr.fetcher = newRowFetcherStatCollector(&fetcher)\n\t\ttr.ExecStatsForTrace = tr.execStatsForTrace\n\t} else {\n\t\ttr.fetcher = &fetcher\n\t}\n\n\treturn tr, nil\n}", "func NewReader(getReaderFunc GetReaderFunc, columnNames set.StringSet) (*Reader, error) {\n\tfileMeta, err := fileMetadata(getReaderFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnameList := []string{}\n\tschemaElements := fileMeta.GetSchema()\n\tfor _, element := range schemaElements {\n\t\tnameList = append(nameList, element.Name)\n\t}\n\n\treturn &Reader{\n\t\tgetReaderFunc: getReaderFunc,\n\t\trowGroups: fileMeta.GetRowGroups(),\n\t\tschemaElements: schemaElements,\n\t\tnameList: nameList,\n\t\tcolumnNames: columnNames,\n\t}, nil\n}", "func (w *Writer) newAccessor(nodes map[node.ID][]byte) *shardAccessor {\n\t// For any node that HStar3 reads, it also writes its sibling. Therefore we\n\t// can pre-allocate this many items for the writes slice.\n\t// TODO(pavelkalinnikov): The actual number of written nodes will be slightly\n\t// bigger by at most the number of written leaves. Try allocating precisely.\n\twrites := make([]Node, 0, len(nodes))\n\treturn &shardAccessor{w: w, reads: nodes, writes: writes}\n}", "func newFileRepositoryIndex(ctxt context.Context, repoName string) (*fileRepositoryIndex, error) {\n\n\tindex := &fileRepositoryIndex{}\n\n\tindex.repoName = repoName\n\n\tindex.repoDir = filepath.Join(file.RepositoriesDirPath(ctxt), repoName)\n\n\tindex.path = filepath.Join(index.repoDir, file.IndexFileName)\n\n\tif !file.DirExists(index.repoDir) {\n\t\treturn nil, errors.NotFound.Newf(\"repository directory at %s does not exist\",\n\t\t\tindex.repoDir)\n\t}\n\n\treturn index, nil\n\n}", "func newSlowReader(r io.ReadCloser) io.ReadCloser {\n\treturn &slowReader{\n\t\trx: r,\n\t\treader: bufio.NewReader(r),\n\t}\n}", "func NewReader(r UnderlyingReader) Reader {\n\treturn Reader{\n\t\trequest: r,\n\t}\n}", "func NewReader(cfg Config, plannerCfg PlannerConfig) (*Reader, error) {\n\tplanner, err := NewPlanner(plannerCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner, err := storage.NewChunkScanner(cfg.StorageType, cfg.StorageConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tid := fmt.Sprintf(\"%d_%d\", plannerCfg.FirstShard, plannerCfg.LastShard)\n\n\t// Default to one worker if none is set\n\tif cfg.NumWorkers < 1 {\n\t\tcfg.NumWorkers = 1\n\t}\n\n\treturn &Reader{\n\t\tcfg: cfg,\n\t\tid: id,\n\t\tplanner: planner,\n\t\tscanner: scanner,\n\t\tscanRequestsChan: make(chan chunk.ScanRequest),\n\t\tquit: make(chan struct{}),\n\t}, nil\n}", "func ReadTree(c *Client, opt ReadTreeOptions, tree Treeish) (*Index, error) {\n\tidx, err := c.GitDir.ReadIndex()\n\tif err != nil {\n\t\tidx = NewIndex()\n\t}\n\torigMap := idx.GetMap()\n\n\tresetremovals, err := checkReadtreePrereqs(c, opt, idx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Convert to a new map before doing anything, so that checkMergeAndUpdate\n\t// can compare the original update after we reset.\n\tif opt.Empty {\n\t\tidx.NumberIndexEntries = 0\n\t\tidx.Objects = make([]*IndexEntry, 0)\n\t\tif err := checkMergeAndUpdate(c, opt, origMap, idx, resetremovals); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn idx, readtreeSaveIndex(c, opt, idx)\n\t}\n\tnewidx := NewIndex()\n\tif err := newidx.ResetIndex(c, tree); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, entry := range newidx.Objects {\n\t\tif opt.Prefix != \"\" {\n\t\t\t// Add it to the original index with the prefix\n\t\t\tentry.PathName = IndexPath(opt.Prefix) + entry.PathName\n\t\t\tif err := idx.AddStage(c, entry.PathName, entry.Mode, entry.Sha1, Stage0, entry.Fsize, entry.Mtime, UpdateIndexOptions{Add: true}); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif opt.Merge {\n\t\t\tif oldentry, ok := origMap[entry.PathName]; ok {\n\t\t\t\tnewsha, _, err := HashFile(\"blob\", string(entry.PathName))\n\t\t\t\tif err != nil && newsha == entry.Sha1 {\n\t\t\t\t\tentry.Ctime, entry.Ctimenano = oldentry.Ctime, oldentry.Ctimenano\n\t\t\t\t\tentry.Mtime = oldentry.Mtime\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif opt.Prefix == \"\" {\n\t\tidx = newidx\n\t}\n\n\tif err := checkMergeAndUpdate(c, opt, origMap, idx, resetremovals); err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, readtreeSaveIndex(c, opt, idx)\n}", "func NewJSONReader(ctx context.Context, logger log.Logger, bkt objstore.InstrumentedBucketReader, dir string, id ulid.ULID) (*JSONReader, error) {\n\tcachefn := filepath.Join(dir, id.String(), block.IndexCacheFilename)\n\tjr, err := newFileJSONReader(logger, cachefn)\n\tif err == nil {\n\t\treturn jr, nil\n\t}\n\n\tif !os.IsNotExist(errors.Cause(err)) && errors.Cause(err) != jsonUnmarshalError {\n\t\treturn nil, errors.Wrap(err, \"read index cache\")\n\t}\n\n\t// Just in case the dir was not created.\n\tif err := os.MkdirAll(filepath.Join(dir, id.String()), os.ModePerm); err != nil {\n\t\treturn nil, errors.Wrap(err, \"create dir\")\n\t}\n\n\t// Try to download index cache file from object store.\n\tif err = objstore.DownloadFile(ctx, logger, bkt.ReaderWithExpectedErrs(bkt.IsObjNotFoundErr), filepath.Join(id.String(), block.IndexCacheFilename), cachefn); err == nil {\n\t\treturn newFileJSONReader(logger, cachefn)\n\t}\n\n\tif !bkt.IsObjNotFoundErr(errors.Cause(err)) && errors.Cause(err) != jsonUnmarshalError {\n\t\treturn nil, errors.Wrap(err, \"download index cache file\")\n\t}\n\n\t// No cache exists on disk yet, build it from the downloaded index and retry.\n\tfn := filepath.Join(dir, id.String(), block.IndexFilename)\n\n\tif err := objstore.DownloadFile(ctx, logger, bkt, filepath.Join(id.String(), block.IndexFilename), fn); err != nil {\n\t\treturn nil, errors.Wrap(err, \"download index file\")\n\t}\n\n\tdefer func() {\n\t\tif rerr := os.Remove(fn); rerr != nil {\n\t\t\tlevel.Error(logger).Log(\"msg\", \"failed to remove temp index file\", \"path\", fn, \"err\", rerr)\n\t\t}\n\t}()\n\n\tif err := WriteJSON(logger, fn, cachefn); err != nil {\n\t\treturn nil, errors.Wrap(err, \"write index cache\")\n\t}\n\n\treturn newFileJSONReader(logger, cachefn)\n}", "func NewReader(\n\tfilePathPrefix string,\n\tdataBufferSize int,\n\tinfoBufferSize int,\n\tbytesPool pool.CheckedBytesPool,\n\tdecodingOpts msgpack.DecodingOptions,\n) FileSetReader {\n\treturn &reader{\n\t\tfilePathPrefix: filePathPrefix,\n\t\tinfoFdWithDigest: digest.NewFdWithDigestReader(infoBufferSize),\n\t\tindexFdWithDigest: digest.NewFdWithDigestReader(dataBufferSize),\n\t\tdataFdWithDigest: digest.NewFdWithDigestReader(dataBufferSize),\n\t\tdigestFdWithDigestContents: digest.NewFdWithDigestContentsReader(infoBufferSize),\n\t\tprologue: make([]byte, markerLen+idxLen),\n\t\tdecoder: msgpack.NewDecoder(decodingOpts),\n\t\tdigestBuf: digest.NewBuffer(),\n\t\tbytesPool: bytesPool,\n\t}\n}", "func New(col *parser.Collection) *Indexer {\n\tindex := make(map[int]map[int]float64)\n\tidfDict := make(map[int]float64)\n\tvocDict := make(map[string]int)\n\tdocDict := make(map[int]*parser.Document)\n\tdocNormDict := make(map[int]float64)\n\treturn &Indexer{col, index, vocDict, idfDict, docDict, docNormDict}\n}", "func NewIndexedParserFromSrc(src IndexedParseSource, numWorkers int) (Parser, error) {\n\tr, err := src.OpenData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\n\tbz := bzip2.NewReader(r)\n\n\td := xml.NewDecoder(bz)\n\t_, err = d.Token()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsi := SiteInfo{}\n\terr = d.Decode(&si)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trv := &multiStreamParser{\n\t\tsiteInfo: si,\n\t\tworkerch: make(chan indexChunk, 1000),\n\t\tentries: make(chan *Page, 1000),\n\t}\n\n\twg := sync.WaitGroup{}\n\twg.Add(numWorkers)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo multiStreamWorker(src, &wg, rv)\n\t}\n\n\tridx, err := src.OpenIndex()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening index: %v\", err)\n\t}\n\n\tgo multiStreamIndexWorker(ridx, rv)\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(rv.entries)\n\t}()\n\n\treturn rv, nil\n}", "func (t *WALTopic) NewReader(index uint64) (Reader, error) {\n\treturn t.newWalReader(index)\n}", "func newBoundedReader(r io.ReaderAt, minOffset, maxOffset int64) io.Reader {\n\treturn &boundedReader{\n\t\treaderAt: r,\n\t\tminOffset: minOffset,\n\t\tmaxOffset: maxOffset,\n\t}\n}", "func (lm *SimpleManager) NewReader(r io.Reader) *Reader {\n\tlr := NewReader(r)\n\tlm.Manage(lr)\n\treturn lr\n}", "func New(r io.ReaderAt) *Cdb {\n\treturn &Cdb{r: r}\n}", "func NewReader(s string) *Reader { return &Reader{s, 0, -1} }", "func NewReader() Reader {\n\treturn &readerImpl{}\n}", "func New(path string) (ip *Indexio, err error) {\n\tvar i Indexio\n\t// Initialize functions map for marshaling and unmarshaling\n\tfm := turtleDB.NewFuncsMap(marshal, unmarshal)\n\t// Create new instance of turtleDB\n\tif i.db, err = turtleDB.New(\"indexio\", path, fm); err != nil {\n\t\treturn\n\t}\n\t// Initialize indexes bucket\n\tif err = i.db.Update(initBucket); err != nil {\n\t\treturn\n\t}\n\t// Assign ip as a pointer to i\n\tip = &i\n\treturn\n}", "func NewIndexed() *Indexed {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn &Indexed{\n\t\tsize: 0,\n\t}\n}", "func NewReadIterator(db *badger.DB, pivot Key, reverse bool) Iterator {\n\tbi := badgerIterator{pivot: pivot, reverse: reverse}\n\tbi.txn = db.NewTransaction(false)\n\topts := badger.DefaultIteratorOptions\n\topts.Reverse = reverse\n\tbi.it = bi.txn.NewIterator(opts)\n\treturn &bi\n}", "func newQueueIndex(dataDir string) (*queueIndex, error) {\n\tindexFile := path.Join(dataDir, cIndexFileName)\n\tindexArena, err := newArena(indexFile, cIndexFileSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueIndex{\n\t\tindexFile: indexFile,\n\t\tindexArena: indexArena,\n\t}, nil\n}", "func NewReader(r *csv.Reader) *Reader {\n\treturn &Reader{\n\t\tTagName: defaultTagName,\n\t\tColumnNamesInFirstRow: true,\n\t\tReader: r,\n\t}\n}", "func NewFromReader(v4 io.Reader, v6 io.Reader) Shortcut {\n\treturn New(readLines(v4), readLines(v6))\n}", "func NewReaderAt(r io.ReaderAt, offset int64) *ReaderAt {\n\treturn &ReaderAt{\n\t\tr: r,\n\t\toffset: offset,\n\t}\n}", "func NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tr: bufio.NewReader(r),\n\t\tcurrentSection: \"default\",\n\t}\n}", "func NewReader(r io.Reader) *Reader {\n\t// Each task in todo.txt starts on a new line.\n\t// We increment our line number (lines start at 1) and set column to 0 so as\n\t// we increment in Read()/ReadAll() it points to the token we read.\n\n\treturn &Reader{\n\t\tComment: '#',\n\t\tline: 1,\n\t\tcolumn: 0,\n\t\tlength: 1,\n\t\tbuffer: bufio.NewReader(r),\n\t\ttasks: TaskList{},\n\t}\n}", "func newReader(filePath string) (*Reader, func(), error) {\n\tf, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfz, err := gzip.NewReader(f)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, nil, err\n\t}\n\n\tcleanup := func() {\n\t\tf.Close()\n\t\tfz.Close()\n\t}\n\treturn &Reader{r: fz}, cleanup, nil\n}", "func (wal *WAL) NewReader(name string, offset Offset, bufferSource func() []byte) (*Reader, error) {\n\tr := &Reader{\n\t\tfilebased: filebased{\n\t\t\tdir: wal.dir,\n\t\t\tfileFlags: os.O_RDONLY,\n\t\t\th: newHash(),\n\t\t\tlog: golog.LoggerFor(\"wal.\" + name),\n\t\t},\n\t\twal: wal,\n\t\tbufferSource: bufferSource,\n\t}\n\tif offset != nil {\n\t\toffsetString := sequenceToFilename(offset.FileSequence())\n\t\tif offsetString[0] != '0' {\n\t\t\twal.log.Debugf(\"Converting legacy offset\")\n\t\t\toffset = NewOffset(offset.FileSequence()/1000, offset.Position())\n\t\t}\n\n\t\tfiles, err := ioutil.ReadDir(wal.dir)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to list existing log files: %v\", err)\n\t\t}\n\n\t\tcutoff := sequenceToFilename(offset.FileSequence())\n\t\tfor i, fileInfo := range files {\n\t\t\tisMostRecent := i == len(files)-1\n\t\t\tif fileInfo.Name() >= cutoff {\n\t\t\t\t// Found existing or more recent WAL file\n\t\t\t\tr.fileSequence = filenameToSequence(fileInfo.Name())\n\t\t\t\tif r.fileSequence == offset.FileSequence() {\n\t\t\t\t\t// Exact match, start at right position\n\t\t\t\t\tr.position = offset.Position()\n\t\t\t\t\tif r.position == fileInfo.Size() && !isMostRecent {\n\t\t\t\t\t\t// At end of file and more recent is available, move to next\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Newer WAL file, start at beginning\n\t\t\t\t\tr.position = 0\n\t\t\t\t}\n\t\t\t\topenErr := r.open()\n\t\t\t\tif openErr != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Unable to open existing log file at %v: %v\", fileInfo.Name(), openErr)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif r.file == nil {\n\t\t// Didn't find WAL file, advance\n\t\terr := r.advance()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to advance initially: %v\", err)\n\t\t}\n\t\twal.log.Debugf(\"Replaying log starting at %v\", r.file.Name())\n\t}\n\treturn r, nil\n}", "func (m *MonkeyWrench) ReadUsingIndex(table, index string, keys []spanner.KeySet, columns []string) ([]*spanner.Row, error) {\n\t// Default to all keys.\n\tvar spannerKeys = spanner.AllKeys()\n\n\t// If we have some specified keys, use those instead.\n\tif len(keys) > 0 {\n\t\tspannerKeys = spanner.KeySets(keys...)\n\t}\n\n\t// Execute the query.\n\titer := m.Client.Single().ReadUsingIndex(m.Context, table, index, spannerKeys, columns)\n\treturn getResultSlice(iter)\n}", "func NewReader(ctx context.Context, client pb.RoutedJournalClient, req pb.ReadRequest) *Reader {\n\tvar r = &Reader{\n\t\tRequest: req,\n\t\tctx: ctx,\n\t\tclient: client,\n\t}\n\treturn r\n}", "func openPackIndex(readerAt io.ReaderAt) (packIndex, error) {\n\th, err := readHeader(readerAt)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid header\")\n\t}\n\treturn &index{hdr: h, readerAt: readerAt}, nil\n}", "func newIndexCache(size uint64) *indexCache {\n\treturn &indexCache{sizecache.New(size), sync.NewCond(&sync.Mutex{}), map[addr]struct{}{}}\n}", "func New(f *os.File, n int64) io.ReadCloser {\n\tr := io.LimitReader(f, n)\n\treturn &headReader{r, f}\n}", "func newReadLogger(log *log.Logger, r io.Reader) io.Reader {\n\treturn &readLogger{log, r}\n}", "func (i *Index) readEntireIndex(ctx context.Context, store Store) (map[string]map[string]struct{}, error) {\n\tkvs, err := consumeBucket(ctx, store, i.indexBucket)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tindex := map[string]map[string]struct{}{}\n\tfor _, kv := range kvs {\n\t\tfk, pk, err := indexKeyParts(kv[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif fkm, ok := index[string(fk)]; ok {\n\t\t\tfkm[string(pk)] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tindex[string(fk)] = map[string]struct{}{string(pk): {}}\n\t}\n\n\treturn index, nil\n}", "func newBlockImporter(db database.DB, r io.ReadSeeker) (*blockImporter, error) {\n\t// Create the transaction and address indexes if needed.\n\t//\n\t// CAUTION: the txindex needs to be first in the indexes array because\n\t// the addrindex uses data from the txindex during catchup. If the\n\t// addrindex is run first, it may not have the transactions from the\n\t// current block indexed.\n\tvar indexes []indexers.Indexer\n\tif cfg.TxIndex || cfg.AddrIndex {\n\t\t// Enable transaction index if address index is enabled since it\n\t\t// requires it.\n\t\tif !cfg.TxIndex {\n\t\t\tlog.Infof(\"Transaction index enabled because it is \" +\n\t\t\t\t\"required by the address index\")\n\t\t\tcfg.TxIndex = true\n\t\t} else {\n\t\t\tlog.Info(\"Transaction index is enabled\")\n\t\t}\n\t\tindexes = append(indexes, indexers.NewTxIndex(db))\n\t}\n\tif cfg.AddrIndex {\n\t\tlog.Info(\"Address index is enabled\")\n\t\tindexes = append(indexes, indexers.NewAddrIndex(db, activeNetParams))\n\t}\n\n\t// Create an index manager if any of the optional indexes are enabled.\n\tvar indexManager blockchain.IndexManager\n\tif len(indexes) > 0 {\n\t\tindexManager = indexers.NewManager(db, indexes)\n\t}\n\n\tchain, err := blockchain.New(&blockchain.Config{\n\t\tDB: db,\n\t\tChainParams: activeNetParams,\n\t\tTimeSource: blockchain.NewMedianTime(),\n\t\tIndexManager: indexManager,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &blockImporter{\n\t\tdb: db,\n\t\tr: r,\n\t\tprocessQueue: make(chan []byte, 2),\n\t\tdoneChan: make(chan bool),\n\t\terrChan: make(chan error),\n\t\tquit: make(chan struct{}),\n\t\tchain: chain,\n\t\tlastLogTime: time.Now(),\n\t}, nil\n}", "func New(path string) (*Index, error) {\n\tkvdb, err := pudge.Open(path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Index{\n\t\tdb: kvdb,\n\t\tpath: path,\n\t}, nil\n}", "func readPosIndex(posIndexFilename string) (*dataIndex, error) {\n index := dataIndex{}\n\n infile, err := os.Open(posIndexFilename)\n defer infile.Close()\n if err != nil {\n return nil, fmt.Errorf(\"can't open %s: %v\", posIndexFilename, err)\n }\n r := bufio.NewReader(infile)\n if (r == nil) {\n return nil, fmt.Errorf(\"can't read %s: %v\" + posIndexFilename, err)\n }\n\n var readerr error = nil\n for ; readerr == nil ; {\n bytebuf, readerr := r.ReadBytes('\\n')\n if readerr != nil && readerr != io.EOF {\n panic(readerr)\n }\n if len(bytebuf) == 0 {\n break;\n }\n line := string(bytebuf)\n if line[0:2] == \" \" {\n // comment line\n continue\n }\n fields := strings.SplitN(strings.TrimSpace(line), \" \", -1)\n lemma := readStoredLemma(fields[0])\n pos_tag := oneCharPosTagToPosId(fields[1])\n synset_cnt, _ := strconv.Atoi(fields[2]) // number of senses of the <lemma, pos> pair\n p_cnt, _ := strconv.Atoi(fields[3]) // number of different pointers that lemma has in all synsets containing it.\n field_index := 4\n relationships := make([]int, p_cnt)\n // consume p_cnt pointer symbols\n for i := 0; i < p_cnt; i++ {\n relationships[i], _ = RELATIONSHIP_POINTER_SYMBOLS[fields[field_index]]\n field_index++\n }\n field_index++ // sense_cnt is redundant with synset_cnt, so skip it\n tagsense_cnt, _ := strconv.Atoi(fields[field_index])\n field_index++\n synsetOffsets := make([]int, synset_cnt)\n for i := 0; i < synset_cnt; i++ {\n synsetOffsets[i], _ = strconv.Atoi(fields[field_index])\n field_index++\n }\n\n _, exists := index[lemma]\n if exists {\n fmt.Printf(\"WARNING: %s already exists. Overwriting.\\n\", lemma)\n }\n index[lemma] = DataIndexEntry {\n PartOfSpeech: pos_tag,\n SynsetCount: synset_cnt,\n Relationships: relationships,\n TagSenseCount: tagsense_cnt,\n SynsetOffsets: synsetOffsets,\n }\n }\n\n return &index, nil\n}", "func NewReader(rd io.Reader) *Reader {\n\treturn &Reader{rd: rd}\n}", "func NewReader(r io.ReaderAt, size int64) (*Reader, error) {\n\tszr := new(Reader)\n\tif err := szr.init(r, size, false); err != nil {\n\t\treturn nil, err\n\t}\n\treturn szr, nil\n}", "func (r *Redis) NewReader(item sdk.CDNItem, format sdk.CDNReaderFormat, from int64, size uint, sort int64) io.ReadCloser {\n\treturn &redis.Reader{\n\t\tStore: r.store,\n\t\tItemID: item.ID,\n\t\tApiRefHash: item.APIRefHash,\n\t\tPrefixKey: redisLruItemCacheKey,\n\t\tSize: size,\n\t\tFrom: from,\n\t\tFormat: format,\n\t\tSort: sort,\n\t}\n}", "func newAccessor(kube common.Kube, resyncPeriod time.Duration, name string, gv schema.GroupVersion,\n\tkind string, listKind string, processor changeProcessorFn) (*accessor, error) {\n\n\tlog.Debugf(\"Creating a new resource accessor for: name='%s', gv:'%v'\", name, gv)\n\n\tvar client dynamic.Interface\n\tclient, err := kube.DynamicInterface(gv, kind, listKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiResource := &metav1.APIResource{\n\t\tName: name,\n\t\tGroup: gv.Group,\n\t\tVersion: gv.Version,\n\t\tNamespaced: true,\n\t\tKind: kind,\n\t}\n\tiface := client.Resource(apiResource, \"\")\n\n\treturn &accessor{\n\t\tresyncPeriod: resyncPeriod,\n\t\tname: name,\n\t\tgv: gv,\n\t\tiface: iface,\n\t\tclient: client,\n\t\tprocessor: processor,\n\t\tapiResource: apiResource,\n\t}, nil\n}", "func NewIndex(addr, name, typ string, md *index.Metadata) (*Index, error) {\n\n\tfmt.Println(\"Get a new index: \", addr, name)\n client := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\t//MaxIdleConnsPerHost: 200,\n\t\t\tMaxIdleConnsPerHost: 2000000,\n\t\t},\n\t\tTimeout: 2500000 * time.Millisecond,\n\t}\n\tconn, err := elastic.NewClient(elastic.SetURL(addr), elastic.SetHttpClient(client))\n\tif err != nil {\n fmt.Println(\"Get error here\");\n\t\treturn nil, err\n\t}\n\tret := &Index{\n\t\tconn: conn,\n\t\tmd: md,\n\t\tname: name,\n\t\ttyp: typ,\n\t}\n fmt.Println(\"get here ======\");\n\n\treturn ret, nil\n\n}", "func openFromConfig(cfg *Config) (*Indexer, error) {\n\tvar err error\n\tres := &Indexer{config: cfg}\n\t// lock file\n\tres.lock, err = lock.New(cfg.LockPath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = res.lock.LockShared()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// internal setup\n\tres.shards = make([]shard.Indexer, cfg.NumShards)\n\tres.dmds, err = dmd.NewAdder(cfg.IndexRoot, cfg.DocFlushRate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = res.readfiles(); err != nil {\n\t\treturn nil, err\n\t}\n\ttokenfn, err := token.FromConfig(&cfg.TokenConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpostChans := make([]chan []post.T, len(res.shards))\n\tfor i := range res.shards {\n\t\tshard := &res.shards[i]\n\t\tbroot := cfg.PostPath(i)\n\t\tif err := shard.InitAppend(uint32(i), broot, uint32(cfg.DocFlushRate)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpostChans[i] = shard.PostChan()\n\t\tgo shard.Serve()\n\t}\n\tres.shatter, err = startShatter(cfg.NumShatters,\n\t\tlen(res.shards), cfg.SeqLen, res.dmds.Last(), tokenfn,\n\t\t&cfg.BlotConfig, postChans)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (dsp *distSQLPlanner) createTableReaders(\n\tplanCtx *planningCtx, n *scanNode, overrideResultColumns []uint32,\n) (physicalPlan, error) {\n\tspec, err := initTableReaderSpec(n)\n\tif err != nil {\n\t\treturn physicalPlan{}, err\n\t}\n\tif overrideResultColumns != nil {\n\t\tspec.OutputColumns = overrideResultColumns\n\t} else {\n\t\tspec.OutputColumns = getOutputColumnsFromScanNode(n)\n\t}\n\tplanToStreamColMap := make([]int, len(n.resultColumns))\n\tfor i := range planToStreamColMap {\n\t\tplanToStreamColMap[i] = -1\n\t}\n\tfor i, col := range spec.OutputColumns {\n\t\tplanToStreamColMap[col] = i\n\t}\n\tordering := dsp.convertOrdering(n.ordering.ordering, planToStreamColMap)\n\n\tspans := n.spans\n\tif len(n.spans) == 0 {\n\t\t// If no spans were specified retrieve all of the keys that start with our\n\t\t// index key prefix.\n\t\tstart := roachpb.Key(sqlbase.MakeIndexKeyPrefix(&n.desc, n.index.ID))\n\t\tspans = roachpb.Spans{{Key: start, EndKey: start.PrefixEnd()}}\n\t}\n\n\tspanPartitions, err := dsp.partitionSpans(planCtx, spans)\n\tif err != nil {\n\t\treturn physicalPlan{}, err\n\t}\n\tvar p physicalPlan\n\tfor _, sp := range spanPartitions {\n\t\tproc := processor{\n\t\t\tnode: sp.node,\n\t\t}\n\n\t\ttr := &distsql.TableReaderSpec{}\n\t\t*tr = spec\n\t\ttr.Spans = make([]distsql.TableReaderSpan, len(sp.spans))\n\t\tfor i := range sp.spans {\n\t\t\ttr.Spans[i].Span = sp.spans[i]\n\t\t}\n\n\t\tproc.spec.Core.SetValue(tr)\n\t\tproc.spec.Output = make([]distsql.OutputRouterSpec, 1)\n\t\tproc.spec.Output[0].Type = distsql.OutputRouterSpec_PASS_THROUGH\n\n\t\tpIdx := p.addProcessor(proc)\n\t\tp.resultRouters = append(p.resultRouters, pIdx)\n\t\tp.planToStreamColMap = planToStreamColMap\n\t\tp.ordering = ordering\n\t}\n\treturn p, nil\n}", "func openReader(\n\tctx context.Context,\n\tdb *sql.DB,\n\tstoreID uint64,\n\taddr gospel.Address,\n\tlimit *rate.Limiter,\n\tlogger twelf.Logger,\n\topts *options.ReaderOptions,\n) (*Reader, error) {\n\t// Note that runCtx is NOT derived from ctx, which is only used for the\n\t// opening of the reader itself.\n\trunCtx, cancel := context.WithCancel(context.Background())\n\n\taccetableLatency := getAcceptableLatency(opts)\n\n\tr := &Reader{\n\t\tlogger: logger,\n\t\tfacts: make(chan gospel.Fact, getReadBufferSize(opts)),\n\t\tend: make(chan struct{}),\n\t\tdone: make(chan error, 1),\n\t\tctx: runCtx,\n\t\tcancel: cancel,\n\t\taddr: addr,\n\t\tglobalLimit: limit,\n\t\tadaptiveLimit: rate.NewLimiter(rate.Every(accetableLatency), 1),\n\t\tacceptableLatency: accetableLatency,\n\t\tstarvationLatency: getStarvationLatency(opts),\n\t\taverageLatency: ewma.NewMovingAverage(averageLatencyAge),\n\t}\n\n\tif logger.IsDebug() {\n\t\tr.debug = &readerDebug{\n\t\t\topts: opts,\n\t\t\taveragePollRate: metrics.NewRateCounter(),\n\t\t\taverageFactRate: metrics.NewRateCounter(),\n\t\t}\n\t}\n\n\tif err := r.prepareStatement(ctx, db, storeID, opts); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.logInitialization()\n\n\tgo r.run()\n\n\treturn r, nil\n}", "func New(r io.Reader) *Reader {\n\treturn &Reader{reader: r}\n}", "func NewIterator(reader *bufio.Reader) (*Iterator, error) {\n\titerator := &Iterator{\n\t\treader: reader,\n\t}\n\n\t// Read the header\n\titerator.err = iterator.readHeader()\n\tif iterator.err != nil {\n\t\treturn nil, iterator.err\n\t}\n\n\treturn iterator, nil\n}", "func NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tbr: bufio.NewReader(r),\n\t\tCRC: crc32.New(crc32.IEEETable),\n\t}\n}", "func (r *baseReader) initReader() error {\n\tif len(r.buf) <= indexFooterSize {\n\t\treturn fmt.Errorf(\"block length short:%d than footer size: %d\", len(r.buf), indexFooterSize)\n\t}\n\t// read footer(4+4+4)\n\tfooterPos := len(r.buf) - indexFooterSize\n\tr.tagValueBitmapAt = int(binary.LittleEndian.Uint32(r.buf[footerPos : footerPos+4]))\n\tr.offsetsAt = int(binary.LittleEndian.Uint32(r.buf[footerPos+4 : footerPos+8]))\n\tr.crc32CheckSum = binary.LittleEndian.Uint32(r.buf[footerPos+8 : footerPos+12])\n\t// validate offsets\n\tif !sort.IntsAreSorted([]int{\n\t\t0, r.tagValueBitmapAt, r.offsetsAt, footerPos}) {\n\t\treturn fmt.Errorf(\"invalid footer format\")\n\t}\n\t// read keys\n\tkeys := roaring.New()\n\tif err := encoding.BitmapUnmarshal(keys, r.buf[r.tagValueBitmapAt:]); err != nil {\n\t\treturn err\n\t}\n\tr.keys = keys\n\t// read high keys offsets\n\tr.offsets = encoding.NewFixedOffsetDecoder()\n\t_, err := r.offsets.Unmarshal(r.buf[r.offsetsAt:])\n\treturn err\n}", "func NewReader(r io.Reader) *Reader {\n\tvar rr Reader\n\trr.Reset(r)\n\treturn &rr\n}" ]
[ "0.66326207", "0.6224663", "0.61640936", "0.6044838", "0.60336226", "0.6008557", "0.5886021", "0.58695596", "0.5833285", "0.5819665", "0.57951456", "0.57921284", "0.5789178", "0.5762485", "0.5724287", "0.5687356", "0.5683812", "0.56731415", "0.5650303", "0.5630273", "0.56190014", "0.56053853", "0.5532266", "0.55218166", "0.5504802", "0.5497693", "0.5465751", "0.54655355", "0.5453289", "0.5446786", "0.5440321", "0.54380757", "0.54302645", "0.542697", "0.540797", "0.53882796", "0.5363596", "0.53534967", "0.5352247", "0.53479695", "0.53296185", "0.53240556", "0.5317455", "0.5309108", "0.52984834", "0.52899146", "0.52881455", "0.52866244", "0.5284861", "0.5270913", "0.52674705", "0.5262717", "0.5257969", "0.5245147", "0.52338374", "0.52273095", "0.5224621", "0.52168816", "0.5188901", "0.5187134", "0.51865816", "0.51841813", "0.51783425", "0.5163345", "0.5162461", "0.5150669", "0.513048", "0.5114116", "0.51106846", "0.51095694", "0.5107911", "0.50902885", "0.5086532", "0.5084133", "0.50833607", "0.5082114", "0.50621736", "0.50492364", "0.50491285", "0.5043782", "0.5032687", "0.5032188", "0.50306803", "0.5021054", "0.5014401", "0.5014367", "0.500804", "0.4993802", "0.4990912", "0.49801388", "0.49783245", "0.49682832", "0.49620104", "0.49613154", "0.49598122", "0.49345368", "0.4929991", "0.49272683", "0.49264213", "0.49260297" ]
0.68607
0
NewResourceOracle creates a new ResourceOracle
func NewResourceOracle(s *stubs.StorageModuleStub) *ResourceOracle { return &ResourceOracle{storage: s} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(name string, params chaincfg.Params, nRpoints int) (*Oracle, error) {\n\tif isMainNet(params) {\n\t\treturn nil, fmt.Errorf(\"mainnet isn't supported yet\")\n\t}\n\n\tmKey, err := randMasterKey(name, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toracle := &Oracle{name: name, nRpoints: nRpoints, masterKey: mKey}\n\treturn oracle, nil\n}", "func NewOracle(args OracleArgs) (*Oracle, error) {\n\tif err := SanityCheckLocalConfig(args.LocalConfig); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"bad local config while creating new oracle\")\n\t}\n\treturn &Oracle{\n\t\toracleArgs: args,\n\t\tstarted: semaphore.NewWeighted(1),\n\t}, nil\n}", "func newOracleClient() *oracleClient {\n\tb, err := crypto.GetRandomBytes(4)\n\tif err != nil {\n\t\tlog.Panic(\"newOracleClient panicked: %v\", err)\n\t}\n\tworld := big.NewInt(0).SetBytes(b).Uint64()\n\treturn newClientWithWorldID(world)\n}", "func newResource(r interface{}) corev2.Resource {\n\treturn reflect.New(reflect.ValueOf(r).Elem().Type()).Interface().(corev2.Resource)\n}", "func newResource() *resource.Resource {\n\tr, _ := resource.Merge(\n\t\tresource.Default(),\n\t\tresource.NewWithAttributes(\n\t\t\tsemconv.SchemaURL,\n\t\t\tsemconv.ServiceNameKey.String(\"opentelemetry-server\"),\n\t\t\tsemconv.ServiceVersionKey.String(\"v0.1.0\"),\n\t\t\tattribute.String(\"environment\", \"demo\"),\n\t\t),\n\t)\n\treturn r\n}", "func (ot *openTelemetryWrapper) newResource(\n\twebEngineName,\n\twebEngineVersion string,\n) (*resource.Resource, error) {\n\treturn resource.Merge(resource.Default(), resource.NewSchemaless(\n\t\tsemconv.WebEngineName(webEngineName),\n\t\tsemconv.WebEngineVersion(webEngineVersion),\n\t))\n}", "func NewResource(name, rtype, state, owner string, t time.Time) Resource {\n\t// If no state defined, mark as Free\n\tif state == \"\" {\n\t\tstate = Free\n\t}\n\treturn Resource{\n\t\tName: name,\n\t\tType: rtype,\n\t\tState: state,\n\t\tOwner: owner,\n\t\tLastUpdate: t,\n\t}\n}", "func newResource(tm unversioned.TypeMetadata) (unversioned.Resource, error) {\n\trh, ok := resourceToType[tm]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unknown resource type (%s) and/or version (%s)\", tm.Kind, tm.APIVersion)\n\t}\n\tlog.Debugf(\"Found resource helper: %s\", rh)\n\n\t// Create new resource and fill in the type metadata.\n\tnew := reflect.New(rh)\n\telem := new.Elem()\n\telem.FieldByName(\"Kind\").SetString(tm.GetTypeMetadata().Kind)\n\telem.FieldByName(\"APIVersion\").SetString(tm.GetTypeMetadata().APIVersion)\n\n\treturn new.Interface().(unversioned.Resource), nil\n}", "func NewOracleParams(\n\tscriptID int64,\n\taskCount,\n\tminCount,\n\tprepareGas,\n\texecuteGas uint64,\n\tfeePayer string,\n\tfeeAmount ...sdk.Coin,\n) OracleParams {\n\treturn OracleParams{\n\t\tScriptID: scriptID,\n\t\tAskCount: askCount,\n\t\tMinCount: minCount,\n\t\tPrepareGas: prepareGas,\n\t\tExecuteGas: executeGas,\n\t\tFeePayer: feePayer,\n\t\tFeeAmount: feeAmount,\n\t}\n}", "func NewResource(parent *xreflect.Types) *Resource {\n\treturn &Resource{_types: xreflect.NewTypes(xreflect.WithRegistry(parent))}\n}", "func NewResource(Params ...interface{}) *Resource {\n\tif len(Params) == 0 {\n\t\treturn nil\n\t}\n\tvar URL = toolbox.AsString(Params[0])\n\tURL = url.Normalize(URL, file.Scheme)\n\n\tvar credential string\n\tif len(Params) > 1 {\n\t\tcredential = toolbox.AsString(Params[1])\n\t}\n\treturn &Resource{\n\t\tURL: URL,\n\t\tCredentials: credential,\n\t}\n}", "func NewResource() Resource {\n\tid, _ := NewID()\n\treturn Resource{ID: id}\n}", "func NewResource(init ...*Resource) *Resource {\n\tvar o *Resource\n\tif len(init) == 1 {\n\t\to = init[0]\n\t} else {\n\t\to = new(Resource)\n\t}\n\treturn o.Init()\n}", "func NewResource() (Resource, error) {\n\t// Get cluster config\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting in cluster config: %s\", err.Error())\n\t\treturn Resource{}, err\n\t}\n\n\t// Setup event source client\n\teventSrcClient, err := eventsrcclientset.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Printf(\"Error building event source client: %s\", err.Error())\n\t\treturn Resource{}, err\n\t}\n\n\t// Setup tektoncd client\n\ttektonClient, err := tektoncdclientset.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Printf(\"Error building tekton clientset: %s\", err.Error())\n\t\treturn Resource{}, err\n\t}\n\n\t// Setup k8s client\n\tk8sClient, err := k8sclientset.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Printf(\"Error building k8s clientset: %s\", err.Error())\n\t\treturn Resource{}, err\n\t}\n\n\tr := Resource{\n\t\tK8sClient: k8sClient,\n\t\tTektonClient: tektonClient,\n\t\tEventSrcClient: eventSrcClient,\n\t}\n\treturn r, nil\n}", "func NewOracleScript(owner sdk.AccAddress, name string, description string, code []byte) OracleScript {\n\treturn OracleScript{\n\t\tOwner: owner,\n\t\tName: name,\n\t\tDescription: description,\n\t\tCode: code,\n\t}\n}", "func (mgr *DlcManager) AddOracle(key [33]byte, name string) (*DlcOracle, error) {\n\tvar err error\n\n\to := new(DlcOracle)\n\to.A = key\n\to.Url = \"\"\n\to.Name = name\n\terr = mgr.SaveOracle(o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, nil\n}", "func (opts resourceOptions) newResource() *resource.Resource {\n\treturn &resource.Resource{\n\t\tGVK: resource.GVK{ // Remove whitespaces to prevent values like \" \" pass validation\n\t\t\tGroup: strings.TrimSpace(opts.Group),\n\t\t\tDomain: strings.TrimSpace(opts.Domain),\n\t\t\tVersion: strings.TrimSpace(opts.Version),\n\t\t\tKind: strings.TrimSpace(opts.Kind),\n\t\t},\n\t\tPlural: resource.RegularPlural(opts.Kind),\n\t\tAPI: &resource.API{},\n\t\tWebhooks: &resource.Webhooks{},\n\t}\n}", "func New(opts ...OptionFunc) (*WorkOracle, error) {\n\toptions := &option{\n\t\tmaxRetries: 10,\n\t\tretryDelay: time.Second,\n\t\tlogger: zap.NewNop(),\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(options); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := options.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tscrypt := options.scrypter\n\tif scrypt == nil {\n\t\tscrypt = &LazyScrypter{init: func() (postrs.Scrypter, error) {\n\t\t\tif options.providerID == nil {\n\t\t\t\treturn nil, errors.New(\"no provider specified\")\n\t\t\t}\n\n\t\t\treturn postrs.NewScrypt(\n\t\t\t\tpostrs.WithProviderID(*options.providerID),\n\t\t\t\tpostrs.WithCommitment(options.commitment),\n\t\t\t\tpostrs.WithScryptN(options.n),\n\t\t\t\tpostrs.WithVRFDifficulty(options.vrfDifficulty),\n\t\t\t\tpostrs.WithLogger(options.logger),\n\t\t\t)\n\t\t}}\n\t}\n\n\treturn &WorkOracle{\n\t\toptions: options,\n\t\tscrypt: scrypt,\n\t}, nil\n}", "func (c *client) createResource(obj interface{}, namespace string, resource schema.GroupVersionResource) error {\n\tresultMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to translate %s to Unstructed (for create operation), with error: %v\", resource.Resource, err)\n\t\tlog.Printf(\"[Error] %s\", msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\tinput := unstructured.Unstructured{}\n\tinput.SetUnstructuredContent(resultMap)\n\tresp, err := c.dynamicClient.Resource(resource).Namespace(namespace).Create(context.Background(), &input, meta_v1.CreateOptions{})\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to create %s, with error: %v\", resource.Resource, err)\n\t\tlog.Printf(\"[Error] %s\", msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\tunstructured := resp.UnstructuredContent()\n\treturn runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, obj)\n}", "func NewResource(name string, port int) *Resource {\n\treturn &Resource{name: name, port: port, host: make(map[string]Host)}\n}", "func (r *ReconcileGrafana) createResource(cr *i8ly.Grafana, resourceName string) error {\n\tresourceHelper := newResourceHelper(cr)\n\tresource, err := resourceHelper.createResource(resourceName)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.deployResource(cr, resource, resourceName)\n}", "func NewResource(typ, name, group, version, kind string, namespaced bool, opts ...Option) (*Resource, error) {\n\tropts := Options{}\n\tfor _, apply := range opts {\n\t\tapply(&ropts)\n\t}\n\n\tuid := ropts.UID\n\tif uid == nil {\n\t\tuid = memuid.New()\n\t}\n\n\ta := ropts.Attrs\n\tif a == nil {\n\t\ta = memattrs.New()\n\t}\n\n\tdotid := ropts.DOTID\n\tif dotid == \"\" {\n\t\tdotid = strings.Join([]string{\n\t\t\tgroup,\n\t\t\tversion,\n\t\t\tkind}, \"/\")\n\t}\n\n\treturn &Resource{\n\t\tuid: uid,\n\t\ttyp: typ,\n\t\tname: name,\n\t\tgroup: group,\n\t\tversion: version,\n\t\tkind: kind,\n\t\tnamespaced: namespaced,\n\t\tdotid: dotid,\n\t\tattrs: a,\n\t}, nil\n}", "func NewLocalOracle() oracle.Oracle {\n\treturn &localOracle{}\n}", "func NewResource(name string) *Resource {\n\tresource := &Resource{Name: name}\n\treturn resource\n}", "func (r *ReconcileApplicationMonitoring) createResource(cr *applicationmonitoringv1alpha1.ApplicationMonitoring, resourceName string) (runtime.Object, error) {\n\ttemplateHelper := newTemplateHelper(cr, r.extraParams)\n\tresourceHelper := newResourceHelper(cr, templateHelper)\n\tresource, err := resourceHelper.createResource(resourceName)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"createResource failed\")\n\t}\n\n\t// Set the CR as the owner of this resource so that when\n\t// the CR is deleted this resource also gets removed\n\terr = controllerutil.SetControllerReference(cr, resource.(metav1.Object), r.scheme)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error setting controller reference\")\n\t}\n\n\terr = r.client.Create(context.TODO(), resource)\n\tif err != nil {\n\t\tif !kerrors.IsAlreadyExists(err) {\n\t\t\treturn nil, errors.Wrap(err, \"error creating resource\")\n\t\t}\n\t}\n\n\treturn resource, nil\n}", "func (c *Controller) CreateResource(w http.ResponseWriter, r *http.Request) {\n\tvar resource Resource\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating resource\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tlog.Fatalln(\"Error creating resource\", err)\n\t}\n\tif err := json.Unmarshal(body, &resource); err != nil {\n\t\tw.WriteHeader(422)\n\t\tif err := json.NewEncoder(w).Encode(err); err != nil {\n\t\t\tlog.Fatalln(\"Error unmarshalling data\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tsuccess := c.Dao.CreateResource(resource)\n\tif !success {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusCreated)\n\treturn\n}", "func (_BridgeRegistry *BridgeRegistryCaller) Oracle(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _BridgeRegistry.contract.Call(opts, &out, \"oracle\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_BridgeRegistry *BridgeRegistryCaller) Oracle(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _BridgeRegistry.contract.Call(opts, out, \"oracle\")\n\treturn *ret0, err\n}", "func NewResource(\n\tconf Config, mgr types.Manager, log log.Modular, stats metrics.Type,\n) (Type, error) {\n\tif err := interop.ProbeInput(context.Background(), mgr, conf.Resource); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Resource{\n\t\tmgr: mgr,\n\t\tname: conf.Resource,\n\t\tlog: log,\n\t\tmErrNotFound: stats.GetCounter(\"error_not_found\"),\n\t}, nil\n}", "func New(name string) *Resource {\n\n\tlastId := (int64)(len(resourceMap))\n\n\treturn &Resource{\n\t\tId: lastId + 1,\n\t\tName: name,\n\t\tStatus: true,\n\t\tCreatedAt: time.Now(),\n\t\tUpdatedAt: time.Now(),\n\t}\n}", "func newResourcePool(config resourcePoolConfig) (*resourcePool, error) {\n\terr := (&config).setup()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trp := &resourcePool{\n\t\tminSize: config.MinSize,\n\t\tmaxSize: config.MaxSize,\n\t\texpiredFn: config.ExpiredFn,\n\t\tcloseFn: config.CloseFn,\n\t\tinitFn: config.InitFn,\n\t\tmaintainInterval: config.MaintainInterval,\n\t}\n\n\treturn rp, nil\n}", "func (d *Dao) NewRepoResource(context data.Map, URI string) (*url.Resource, error) {\n\tvar localResourceURL = fmt.Sprintf(d.localResourceRepo, URI)\n\tvar localResource = url.NewResource(localResourceURL)\n\tvar localService, err = storage.NewServiceForURL(localResourceURL, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif path.Ext(localResource.URL) == \"\" {\n\t\tfor _, ext := range commonResourceExtensions {\n\t\t\tif exists, _ := localService.Exists(localResource.URL + ext); exists {\n\t\t\t\treturn url.NewResource(localResource.URL + ext), nil\n\t\t\t}\n\t\t}\n\t}\n\tif exits, _ := localService.Exists(localResource.URL); exits {\n\t\treturn url.NewResource(localResourceURL), nil\n\t}\n\tvar remoteResourceURL = fmt.Sprintf(d.remoteResourceRepo, URI)\n\tremoteService, err := storage.NewServiceForURL(remoteResourceURL, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = storage.Copy(remoteService, remoteResourceURL, localService, localResourceURL, nil, nil)\n\treturn localResource, err\n}", "func (s *ResourcesService) Create(ctx context.Context, realm, clientID string, resource *Resource) (*Resource, *http.Response, error) {\n\tu := fmt.Sprintf(\"admin/realms/%s/clients/%s/authz/resource-server/resource\", realm, clientID)\n\treq, err := s.keycloak.NewRequest(http.MethodPost, u, resource)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar created Resource\n\tres, err := s.keycloak.Do(ctx, req, &created)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &created, res, nil\n}", "func newOracleDatabaseStateStore(logger logger.Logger, dba dbAccess) *OracleDatabase {\n\treturn &OracleDatabase{\n\t\tfeatures: []state.Feature{\n\t\t\tstate.FeatureETag,\n\t\t\tstate.FeatureTransactional,\n\t\t\tstate.FeatureTTL,\n\t\t},\n\t\tlogger: logger,\n\t\tdbaccess: dba,\n\t}\n}", "func (r *Reconciler) createResource(ctx context.Context, resourceName string, serverClient k8sclient.Client) (runtime.Object, error) {\n\tif r.extraParams == nil {\n\t\tr.extraParams = map[string]string{}\n\t}\n\tr.extraParams[\"MonitoringKey\"] = r.Config.GetLabelSelector()\n\tr.extraParams[\"Namespace\"] = r.Config.GetOperatorNamespace()\n\n\ttemplateHelper := NewTemplateHelper(r.extraParams)\n\tresource, err := templateHelper.CreateResource(resourceName)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"createResource failed: %w\", err)\n\t}\n\n\tmetaObj, err := meta.Accessor(resource)\n\tif err == nil {\n\t\towner.AddIntegreatlyOwnerAnnotations(metaObj, r.installation)\n\t}\n\n\terr = serverClient.Create(ctx, resource)\n\tif err != nil {\n\t\tif !k8serr.IsAlreadyExists(err) {\n\t\t\treturn nil, fmt.Errorf(\"error creating resource: %w\", err)\n\t\t}\n\t}\n\n\treturn resource, nil\n}", "func (_Mcapscontroller *McapscontrollerCaller) Oracle(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _Mcapscontroller.contract.Call(opts, &out, \"oracle\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func NewResourceCreator(createFunc interface{}, receiver interface{}) ResourceCreator {\n\treturn ResourceCreator{\n\t\tObjectCreator: closure.NewObjectCreator(createFunc, receiver),\n\t}\n}", "func newResources(clusterID, clusterVPCID string, publicAccessFW publicAccessFirewall, gclient *godo.Client) *resources {\n\treturn &resources{\n\t\tclusterID: clusterID,\n\t\tclusterVPCID: clusterVPCID,\n\t\tfirewall: publicAccessFW,\n\n\t\tgclient: gclient,\n\t}\n}", "func NewResource(\n\tconf Config, mgr types.Manager, log log.Modular, stats metrics.Type,\n) (Type, error) {\n\t// TODO: V4 Remove this\n\tinputProvider, ok := mgr.(inputProvider)\n\tif !ok {\n\t\treturn nil, errors.New(\"manager does not support input resources\")\n\t}\n\n\tif _, err := inputProvider.GetInput(conf.Resource); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to obtain input resource '%v': %v\", conf.Resource, err)\n\t}\n\treturn &Resource{\n\t\tmgr: inputProvider,\n\t\tname: conf.Resource,\n\t\tlog: log,\n\t\tmErrNotFound: stats.GetCounter(\"error_not_found\"),\n\t}, nil\n}", "func resourceHelmfileReleaseCreate(d *schema.ResourceData, _ interface{}) (finalErr error) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfinalErr = fmt.Errorf(\"unhandled error: %v\\n%s\", err, debug.Stack())\n\t\t}\n\t}()\n\n\trs, err := NewReleaseSetWithSingleRelease(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := CreateReleaseSet(newContext(d), rs, d); err != nil {\n\t\treturn err\n\t}\n\n\td.MarkNewResource()\n\n\t//create random uuid for the id\n\tid := xid.New().String()\n\td.SetId(id)\n\n\treturn nil\n}", "func NewResource(k8s *k8s.Client, res string) (Resource, error) {\n\tvar err error\n\tr := resource{\n\t\tk8s: k8s,\n\t\tNamespace: defaultNamespace,\n\t\tType: TypePod,\n\t}\n\tchunks := strings.Split(res, \"/\")\n\tnbc := len(chunks)\n\tif nbc == 1 {\n\t\t// Z: the pod \"Z\" in namespace \"default\"\n\t\tr.Name = chunks[0]\n\t} else if nbc == 2 {\n\t\t// Y/Z: all the pods of the resource \"Z\" of type \"Y\" in namespace \"default\"\n\t\tr.Type, err = strTypeToConst(chunks[0])\n\t\tr.Name = chunks[1]\n\t} else if nbc == 3 {\n\t\t// X/Y/Z: all the pods of the resource \"Z\" of type \"Y\" in namespace \"X\"\n\t\tr.Namespace = chunks[0]\n\t\tr.Type, err = strTypeToConst(chunks[1])\n\t\tr.Name = chunks[2]\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn types[r.Type](r), nil\n\t// var ret Resource\n\t// switch r.Type {\n\t// case TypePod:\n\t// \tret = &Pod{r}\n\t// case TypeDeploy:\n\t// \tret = &Deployment{r}\n\t// case TypeStatefulSet:\n\t// \tret = &StatefulSet{r}\n\t// }\n\t// return ret, nil\n}", "func NewResourceCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"resource\",\n\t\tShort: \"Resource commands\",\n\t}\n\n\tAddCommands(cmd)\n\n\treturn cmd\n}", "func NewResource(url, path string) *Resource {\n\te := Resource{URL: url, Path: path}\n\treturn &e\n}", "func New(i interface{}) *Resource {\n\tr := &Resource{}\n\tr.geth = mustMakeRpc(i, \"Get\")\n\tr.posth = mustMakeRpc(i, \"Post\")\n\tr.puth = mustMakeRpc(i, \"Put\")\n\tr.deleteh = mustMakeRpc(i, \"Delete\")\n\n\t// println(\"[debug]\", r.geth, r.posth, r.puth, r.deleteh)\n\treturn r\n}", "func NewResource(options ...func(*Resource)) *Resource {\n\tr := &Resource{resources: make([]flare.Resource, 0)}\n\n\tfor _, option := range options {\n\t\toption(r)\n\t}\n\n\tif r.subscriptionRepository == nil {\n\t\tr.subscriptionRepository = NewSubscription()\n\t}\n\n\treturn r\n}", "func NewTerraMsgResource(id int64, chainID string, contractID string) TerraMsgResource {\n\treturn TerraMsgResource{\n\t\tJAID: NewJAIDInt64(id),\n\t\tChainID: chainID,\n\t\tContractID: contractID,\n\t}\n}", "func NewResourceData(t *testing.T, params ResDataParams) *schema.ResourceData {\n\tt.Helper()\n\tif err := params.Validate(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn resourceDataRaw(t,\n\t\tparams.ID, params.Schema, params.State, params.Change,\n\t)\n}", "func newImageResource(name string, width, height int, bitperComponent int, data []byte) *ImageResource {\n\treturn &ImageResource{\n\t\tname: name,\n\t\twidth: width,\n\t\theight: height,\n\t\tcolorSpace: colorSpaceDeviceGray,\n\t\tbitsPerComponent: bitperComponent,\n\t\tdata: data,\n\t}\n}", "func (mgr *DlcManager) ImportOracle(url string, name string) (*DlcOracle, error) {\n\treq, err := http.NewRequest(\"GET\", url+\"/api/pubkey\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response DlcOracleRestPubkeyResponse\n\n\tif err := json.NewDecoder(resp.Body).Decode(&response); err != nil {\n\t\treturn nil, err\n\t}\n\n\to := new(DlcOracle)\n\tA, err := hex.DecodeString(response.AHex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcopy(o.A[:], A[:])\n\to.Url = url\n\to.Name = name\n\terr = mgr.SaveOracle(o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, nil\n}", "func NewBridgeResource(b bridges.BridgeType) *BridgeResource {\n\treturn &BridgeResource{\n\t\t// Uses the name as the id...Should change this to the id\n\t\tJAID: NewJAID(b.Name.String()),\n\t\tName: b.Name.String(),\n\t\tURL: b.URL.String(),\n\t\tConfirmations: b.Confirmations,\n\t\tOutgoingToken: b.OutgoingToken,\n\t\tMinimumContractPayment: b.MinimumContractPayment,\n\t\tCreatedAt: b.CreatedAt,\n\t}\n}", "func (d *DryccCmd) ResourcesCreate(appID, plan string, name string, params []string) error {\n\ts, appID, err := load(d.ConfigFile, appID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Printf(\"Creating %s to %s... \", name, appID)\n\n\tparamsMap, err := parseParams(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tquit := progress(d.WOut)\n\tresource := api.Resource{\n\t\tName: name,\n\t\tPlan: plan,\n\t\tOptions: paramsMap,\n\t}\n\t_, err = resources.Create(s.Client, appID, resource)\n\tquit <- true\n\t<-quit\n\tif d.checkAPICompatibility(s.Client, err) != nil {\n\t\treturn err\n\t}\n\n\td.Println(\"done\")\n\treturn nil\n}", "func createProviderResource(ctx *Context, ref string) (ProviderResource, error) {\n\t// Parse the URN and ID out of the provider reference.\n\tlastSep := strings.LastIndex(ref, \"::\")\n\tif lastSep == -1 {\n\t\treturn nil, errors.Errorf(\"expected '::' in provider reference %s\", ref)\n\t}\n\turn := ref[0:lastSep]\n\tid := ref[lastSep+2:]\n\n\t// Unmarshal the provider resource as a resource reference so we get back\n\t// the intended provider type with its state, if it's been registered.\n\tresource, err := unmarshalResourceReference(ctx, resource.ResourceReference{\n\t\tURN: resource.URN(urn),\n\t\tID: resource.NewStringProperty(id),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resource.(ProviderResource), nil\n}", "func NewTerraNodeResource(node db.Node) TerraNodeResource {\n\treturn TerraNodeResource{\n\t\tJAID: NewJAIDInt32(node.ID),\n\t\tName: node.Name,\n\t\tTerraChainID: node.TerraChainID,\n\t\tTendermintURL: node.TendermintURL,\n\t\tCreatedAt: node.CreatedAt,\n\t\tUpdatedAt: node.UpdatedAt,\n\t}\n}", "func NetworkResourceCreate(w http.ResponseWriter, r *http.Request) {\n\tvar req openapi.NetworkResourceCreateRequest\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\thandleError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tnetwork, err := ctr.CreateNetworkResource(&req)\n\tif err != nil {\n\t\thandleError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\thandleResult(w, http.StatusCreated, network)\n\treturn\n}", "func (router *Router) createResource(w http.ResponseWriter, r *http.Request) {\n\tclusterName := r.URL.Query().Get(\"cluster\")\n\tnamespace := r.URL.Query().Get(\"namespace\")\n\tname := r.URL.Query().Get(\"name\")\n\tresource := r.URL.Query().Get(\"resource\")\n\tsubResource := r.URL.Query().Get(\"subResource\")\n\tpath := r.URL.Query().Get(\"path\")\n\n\tlog.WithFields(logrus.Fields{\"cluster\": clusterName, \"namespace\": namespace, \"name\": name, \"path\": path, \"resource\": resource, \"subResource\": subResource}).Tracef(\"createResource\")\n\n\tcluster := router.clusters.GetCluster(clusterName)\n\tif cluster == nil {\n\t\terrresponse.Render(w, r, nil, http.StatusBadRequest, \"Invalid cluster name\")\n\t\treturn\n\t}\n\n\tif router.isForbidden(resource) {\n\t\terrresponse.Render(w, r, nil, http.StatusForbidden, fmt.Sprintf(\"Access for resource %s is forbidding\", resource))\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terrresponse.Render(w, r, err, http.StatusBadRequest, \"Could not decode request body\")\n\t\treturn\n\t}\n\n\terr = cluster.CreateResource(r.Context(), namespace, name, path, resource, subResource, body)\n\tif err != nil {\n\t\terrresponse.Render(w, r, err, http.StatusBadRequest, \"Could not create resource\")\n\t\treturn\n\t}\n\n\trender.JSON(w, r, nil)\n}", "func NewRespool(\n\tscope tally.Scope,\n\tid string,\n\tparent ResPool,\n\tconfig *respool.ResourcePoolConfig,\n\tpreemptionConfig rc.PreemptionConfig) (ResPool, error) {\n\n\tif config == nil {\n\t\treturn nil, errors.Errorf(\"error creating resource pool %s; \"+\n\t\t\t\"ResourcePoolConfig is nil\", id)\n\t}\n\n\tpq, err := queue.CreateQueue(config.Policy, math.MaxInt64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating resource pool %s\", id)\n\t}\n\n\tcq, err := queue.CreateQueue(config.Policy, math.MaxInt64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating resource pool %s\", id)\n\t}\n\n\tnq, err := queue.CreateQueue(config.Policy, math.MaxInt64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating resource pool %s\", id)\n\t}\n\n\trq, err := queue.CreateQueue(config.Policy, math.MaxInt64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating revocable queue %s\", id)\n\t}\n\n\tpool := &resPool{\n\t\tid: id,\n\t\tchildren: list.New(),\n\t\tparent: parent,\n\t\tresourceConfigs: make(map[string]*respool.ResourceConfig),\n\t\tpoolConfig: config,\n\t\tpendingQueue: pq,\n\t\tcontrollerQueue: cq,\n\t\tnpQueue: nq,\n\t\trevocableQueue: rq,\n\t\tallocation: scalar.NewAllocation(),\n\t\tentitlement: &scalar.Resources{},\n\t\tnonSlackEntitlement: &scalar.Resources{},\n\t\tslackEntitlement: &scalar.Resources{},\n\t\tdemand: &scalar.Resources{},\n\t\tslackDemand: &scalar.Resources{},\n\t\tslackLimit: &scalar.Resources{},\n\t\treservation: &scalar.Resources{},\n\t\tinvalidTasks: make(map[string]bool),\n\t\tpreemptionCfg: preemptionConfig,\n\t}\n\tpool.path = pool.calculatePath()\n\n\t// Initialize metrics\n\tpool.metrics = NewMetrics(scope.Tagged(map[string]string{\n\t\t\"path\": pool.GetPath(),\n\t}))\n\n\t// Initialize resources and limits.\n\tpool.initialize(config)\n\n\treturn pool, nil\n}", "func (a *Client) CreateResourceRequest(ctx context.Context, params *CreateResourceRequestParams) (*CreateResourceRequestCreated, error) {\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateResourceRequest\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/approval_system/resourceRequest\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &CreateResourceRequestReader{formats: a.formats},\n\t\tAuthInfo: a.authInfo,\n\t\tContext: ctx,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*CreateResourceRequestCreated), nil\n\n}", "func (_BridgeRegistry *BridgeRegistrySession) Oracle() (common.Address, error) {\n\treturn _BridgeRegistry.Contract.Oracle(&_BridgeRegistry.CallOpts)\n}", "func (_BridgeRegistry *BridgeRegistrySession) Oracle() (common.Address, error) {\n\treturn _BridgeRegistry.Contract.Oracle(&_BridgeRegistry.CallOpts)\n}", "func (_BridgeRegistry *BridgeRegistryCallerSession) Oracle() (common.Address, error) {\n\treturn _BridgeRegistry.Contract.Oracle(&_BridgeRegistry.CallOpts)\n}", "func (_BridgeRegistry *BridgeRegistryCallerSession) Oracle() (common.Address, error) {\n\treturn _BridgeRegistry.Contract.Oracle(&_BridgeRegistry.CallOpts)\n}", "func (rc *ResourceCommand) Initialize(app *kingpin.Application, config *servicecfg.Config) {\n\trc.CreateHandlers = map[ResourceKind]ResourceCreateHandler{\n\t\ttypes.KindUser: rc.createUser,\n\t\ttypes.KindRole: rc.createRole,\n\t\ttypes.KindTrustedCluster: rc.createTrustedCluster,\n\t\ttypes.KindGithubConnector: rc.createGithubConnector,\n\t\ttypes.KindCertAuthority: rc.createCertAuthority,\n\t\ttypes.KindClusterAuthPreference: rc.createAuthPreference,\n\t\ttypes.KindClusterNetworkingConfig: rc.createClusterNetworkingConfig,\n\t\ttypes.KindClusterMaintenanceConfig: rc.createClusterMaintenanceConfig,\n\t\ttypes.KindSessionRecordingConfig: rc.createSessionRecordingConfig,\n\t\ttypes.KindUIConfig: rc.createUIConfig,\n\t\ttypes.KindLock: rc.createLock,\n\t\ttypes.KindNetworkRestrictions: rc.createNetworkRestrictions,\n\t\ttypes.KindApp: rc.createApp,\n\t\ttypes.KindDatabase: rc.createDatabase,\n\t\ttypes.KindKubernetesCluster: rc.createKubeCluster,\n\t\ttypes.KindToken: rc.createToken,\n\t\ttypes.KindInstaller: rc.createInstaller,\n\t\ttypes.KindNode: rc.createNode,\n\t\ttypes.KindOIDCConnector: rc.createOIDCConnector,\n\t\ttypes.KindSAMLConnector: rc.createSAMLConnector,\n\t\ttypes.KindLoginRule: rc.createLoginRule,\n\t\ttypes.KindSAMLIdPServiceProvider: rc.createSAMLIdPServiceProvider,\n\t\ttypes.KindDevice: rc.createDevice,\n\t\ttypes.KindOktaImportRule: rc.createOktaImportRule,\n\t\ttypes.KindIntegration: rc.createIntegration,\n\t\ttypes.KindWindowsDesktop: rc.createWindowsDesktop,\n\t\ttypes.KindAccessList: rc.createAccessList,\n\t}\n\trc.config = config\n\n\trc.createCmd = app.Command(\"create\", \"Create or update a Teleport resource from a YAML file.\")\n\trc.createCmd.Arg(\"filename\", \"resource definition file, empty for stdin\").StringVar(&rc.filename)\n\trc.createCmd.Flag(\"force\", \"Overwrite the resource if already exists\").Short('f').BoolVar(&rc.force)\n\trc.createCmd.Flag(\"confirm\", \"Confirm an unsafe or temporary resource update\").Hidden().BoolVar(&rc.confirm)\n\n\trc.updateCmd = app.Command(\"update\", \"Update resource fields.\")\n\trc.updateCmd.Arg(\"resource type/resource name\", `Resource to update\n\t<resource type> Type of a resource [for example: rc]\n\t<resource name> Resource name to update\n\n\tExample:\n\t$ tctl update rc/remote`).SetValue(&rc.ref)\n\trc.updateCmd.Flag(\"set-labels\", \"Set labels\").StringVar(&rc.labels)\n\trc.updateCmd.Flag(\"set-ttl\", \"Set TTL\").StringVar(&rc.ttl)\n\n\trc.deleteCmd = app.Command(\"rm\", \"Delete a resource.\").Alias(\"del\")\n\trc.deleteCmd.Arg(\"resource type/resource name\", `Resource to delete\n\t<resource type> Type of a resource [for example: connector,user,cluster,token]\n\t<resource name> Resource name to delete\n\n\tExamples:\n\t$ tctl rm connector/github\n\t$ tctl rm cluster/main`).SetValue(&rc.ref)\n\n\trc.getCmd = app.Command(\"get\", \"Print a YAML declaration of various Teleport resources.\")\n\trc.getCmd.Arg(\"resources\", \"Resource spec: 'type/[name][,...]' or 'all'\").Required().SetValue(&rc.refs)\n\trc.getCmd.Flag(\"format\", \"Output format: 'yaml', 'json' or 'text'\").Default(teleport.YAML).StringVar(&rc.format)\n\trc.getCmd.Flag(\"namespace\", \"Namespace of the resources\").Hidden().Default(apidefaults.Namespace).StringVar(&rc.namespace)\n\trc.getCmd.Flag(\"with-secrets\", \"Include secrets in resources like certificate authorities or OIDC connectors\").Default(\"false\").BoolVar(&rc.withSecrets)\n\trc.getCmd.Flag(\"verbose\", \"Verbose table output, shows full label output\").Short('v').BoolVar(&rc.verbose)\n\n\trc.getCmd.Alias(getHelp)\n\n\tif rc.stdout == nil {\n\t\trc.stdout = os.Stdout\n\t}\n}", "func New(terraformType, id string, provider *provider.TerraformProvider) *Resource {\n\treturn &Resource{\n\t\tterraformType: terraformType,\n\t\tid: id,\n\t\tprovider: provider,\n\t}\n}", "func createResourceLock(cb *ClientBuilder, namespace, name string) (resourcelock.Interface, error) {\n\tclient := cb.KubeClientOrDie(\"leader-election\")\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartLogging(klog.Infof)\n\teventBroadcaster.StartRecordingToSink(&coreclientsetv1.EventSinkImpl{Interface: client.CoreV1().Events(namespace)})\n\n\tid, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating lock: %v\", err)\n\t}\n\n\tuuid, err := uuid.NewRandom()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to generate UUID: %v\", err)\n\t}\n\n\t// add a uniquifier so that two processes on the same host don't accidentally both become active\n\tid = id + \"_\" + uuid.String()\n\n\treturn resourcelock.New(resourcelock.ConfigMapsLeasesResourceLock, namespace, name, client.CoreV1(), client.CoordinationV1(), resourcelock.ResourceLockConfig{\n\t\tIdentity: id,\n\t\tEventRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: namespace}),\n\t})\n}", "func NewResource(\n\tconf Config, mgr types.Manager, log log.Modular, stats metrics.Type,\n) (Type, error) {\n\tif _, err := mgr.GetCondition(conf.Resource); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to obtain condition resource '%v': %v\", conf.Resource, err)\n\t}\n\treturn &Resource{\n\t\tmgr: mgr,\n\t\tname: conf.Resource,\n\t\tlog: log,\n\n\t\tmCount: stats.GetCounter(\"count\"),\n\t\tmTrue: stats.GetCounter(\"true\"),\n\t\tmFalse: stats.GetCounter(\"false\"),\n\t\tmErrNotFound: stats.GetCounter(\"error_not_found\"),\n\t\tmErr: stats.GetCounter(\"error\"),\n\t}, nil\n}", "func (store Storage) GetOracle() Oracle {\n\treturn Oracle{}\n}", "func (_HarmonyBridge *HarmonyBridgeCaller) Oracle(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _HarmonyBridge.contract.Call(opts, out, \"oracle\")\n\treturn *ret0, err\n}", "func (v CustomersResource) New(c buffalo.Context) error {\n\tcustomer := &models.Customer{}\n\n\tcustomer.BirthDate = time.Now().AddDate(-20, 0, 0)\n\n\t// Make customer available inside the html template\n\tc.Set(\"customer\", customer)\n\treturn c.Render(200, r.HTML(\"customers/new.html\"))\n}", "func (c *Client) CreateResource(ctx context.Context, resource models.Resource) ([]*models.Object, error) {\n\tvar out models.WhoisResource\n\tif err := c.transport.Post(ctx, \"/\"+resource.TypeString(), &out, transport.WithJSONRequestBody(resource.RIPEWhoisResource())); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out.Objects.Object, nil\n}", "func bindOracleMgr(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(OracleMgrABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func NewResource[GA any, Alpha any, Beta any](\n\tresourceID *cloud.ResourceID,\n\ttypeTrait TypeTrait[GA, Alpha, Beta],\n) *mutableResource[GA, Alpha, Beta] {\n\tif typeTrait == nil {\n\t\ttypeTrait = &BaseTypeTrait[GA, Alpha, Beta]{}\n\t}\n\n\tobj := &mutableResource[GA, Alpha, Beta]{\n\t\ttypeTrait: typeTrait,\n\t\tresourceID: resourceID,\n\t}\n\n\t// Set .Name from the ResourceID.\n\tsetName := func(v reflect.Value) {\n\t\tif ft, ok := v.Type().FieldByName(\"Name\"); !ok || ft.Type.Kind() != reflect.String {\n\t\t\treturn\n\t\t}\n\t\tf := v.FieldByName(\"Name\")\n\t\tif !f.IsValid() {\n\t\t\tpanic(fmt.Sprintf(\"type does not have .Name (%T)\", v.Type()))\n\t\t}\n\t\tf.Set(reflect.ValueOf(resourceID.Key.Name))\n\t}\n\tsetName(reflect.ValueOf(&obj.ga).Elem())\n\tsetName(reflect.ValueOf(&obj.alpha).Elem())\n\tsetName(reflect.ValueOf(&obj.beta).Elem())\n\n\treturn obj\n}", "func CreateResourceProvider(directory string) (*ResourceProvider, error) {\n\tif directory != \"\" {\n\t\treturn CreateResourceProviderFromPath(directory)\n\t}\n\treturn CreateResourceProviderFromCluster()\n}", "func NewResourceMgr(osrmBackend, finderType, searchEndpoint, apiKey, apiSignature, dataFolderPath string) (*ResourceMgr, error) {\n\t// @todo: need make sure connectivity is on and continues available\n\t// simple request to guarantee server is alive after init\n\tstartTime := time.Now()\n\n\tif len(osrmBackend) == 0 {\n\t\terr := fmt.Errorf(\"empty osrmBackend end point\")\n\t\treturn nil, err\n\t}\n\n\ts2indexer := s2indexer.NewS2Indexer().Load(dataFolderPath)\n\tif s2indexer == nil {\n\t\terr := fmt.Errorf(\"failed to load s2Indexer\")\n\t\treturn nil, err\n\t}\n\n\tstationFinder, err := iterator.CreateIteratorGenerator(finderType, searchEndpoint, apiKey, apiSignature, s2indexer)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to call iterator.CreateIteratorGenerator, met error = %+v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tconnectivityMap := topograph.New(0.0).Load(dataFolderPath)\n\tif connectivityMap == nil {\n\t\terr := fmt.Errorf(\"failed to load MemoryTopoGraph\")\n\t\treturn nil, err\n\t}\n\n\tglog.Infof(\"Initialize OASIS resource manager takes %f seconds.\", time.Since(startTime).Seconds())\n\n\treturn &ResourceMgr{\n\t\tosrmConnector: osrmconnector.NewOSRMConnector(osrmBackend),\n\t\tstationFinder: stationFinder,\n\t\tspatialIndexerFinder: s2indexer,\n\t\tconnectivityMap: connectivityMap,\n\t\tstationLocationQuerier: s2indexer,\n\t}, nil\n}", "func resourceCreateAuthServer(d *schema.ResourceData, m interface{}) error {\n\tnagiosClient := m.(*Client)\n\n\tauthServer := setAuthServerFromSchema(d)\n\n\tbody, err := nagiosClient.newAuthServer(authServer)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, &authServer)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Nagios does some weird stuff with auth servers. When you create one, it returns server_id\n\t// However, when attempting to read, the API wants server_id as an input, but returns id, so we must have both values and keep them\n\t// set to the same value\n\tauthServer.ID = authServer.ServerID\n\n\td.SetId(authServer.ID)\n\n\treturn resourceReadAuthServer(d, m)\n}", "func NewResource(resourceType string) *Resource {\n\treturn &Resource{\n\t\t// Mux is a goji.SubMux, inherits context from parent Mux\n\t\tMux: goji.SubMux(),\n\t\t// Type of the resource, makes no assumptions about plurality\n\t\tType: resourceType,\n\t\tRelationships: map[string]Relationship{},\n\t\t// A list of registered routes, useful for debugging\n\t\tRoutes: []string{},\n\t}\n}", "func createResource(path string, data Generater) (err error) {\n\n\tbuf, err := data.Generate()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.WriteFile(path, buf, 0644)\n\n}", "func NewRIDWithResource(object Class) *RID {\n\trid := &RID{}\n\tvar gdRID C.godot_rid\n\tC.godot_rid_new_with_resource(&gdRID, unsafe.Pointer(object.getOwner()))\n\trid.rid = &gdRID\n\n\treturn rid\n}", "func NewResourceManager() (ResourceManager, error) {\n\tm := &resmgr{Logger: logger.NewLogger(\"resource-manager\")}\n\n\tif err := m.setupCache(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsysfs.SetSysRoot(opt.HostRoot)\n\ttopology.SetSysRoot(opt.HostRoot)\n\n\tswitch {\n\tcase opt.ResetPolicy && opt.ResetConfig:\n\t\tos.Exit(m.resetCachedPolicy() + m.resetCachedConfig())\n\tcase opt.ResetPolicy:\n\t\tos.Exit(m.resetCachedPolicy())\n\tcase opt.ResetConfig:\n\t\tos.Exit(m.resetCachedConfig())\n\t}\n\n\tif err := m.checkOpts(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupAgentInterface(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.loadConfig(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupConfigServer(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupPolicy(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.registerPolicyMetricsCollector(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupRelay(); err != nil {\n\t\tpid, _ := pidfile.OwnerPid()\n\t\tif pid > 0 {\n\t\t\tm.Error(\"looks like we're already running as pid %d...\", pid)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupRequestProcessing(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupEventProcessing(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupControllers(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.setupIntrospection(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}", "func (h *harness) addResource(t *testing.T, resource *test.APIResource) {\n\tt.Helper()\n\n\th.DiscoveryClient.WithAPIResource(resource)\n\trequire.NoError(t, h.discoveryHelper.Refresh())\n\n\tfor _, item := range resource.Items {\n\t\tobj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item)\n\t\trequire.NoError(t, err)\n\n\t\tunstructuredObj := &unstructured.Unstructured{Object: obj}\n\t\tif resource.Namespaced {\n\t\t\t_, err = h.DynamicClient.Resource(resource.GVR()).Namespace(item.GetNamespace()).Create(context.TODO(), unstructuredObj, metav1.CreateOptions{})\n\t\t} else {\n\t\t\t_, err = h.DynamicClient.Resource(resource.GVR()).Create(context.TODO(), unstructuredObj, metav1.CreateOptions{})\n\t\t}\n\t\trequire.NoError(t, err)\n\t}\n}", "func CreateResource(kubedata *krd.GenericKubeResourceData, kubeclient *kubernetes.Clientset) (string, error) {\n\tif kubedata.Namespace == \"\" {\n\t\tkubedata.Namespace = \"default\"\n\t}\n\n\tif _, err := os.Stat(kubedata.YamlFilePath); err != nil {\n\t\treturn \"\", pkgerrors.New(\"File \" + kubedata.YamlFilePath + \" not found\")\n\t}\n\n\tlog.Println(\"Reading deployment YAML\")\n\trawBytes, err := ioutil.ReadFile(kubedata.YamlFilePath)\n\tif err != nil {\n\t\treturn \"\", pkgerrors.Wrap(err, \"Deployment YAML file read error\")\n\t}\n\n\tlog.Println(\"Decoding deployment YAML\")\n\tdecode := scheme.Codecs.UniversalDeserializer().Decode\n\tobj, _, err := decode(rawBytes, nil, nil)\n\tif err != nil {\n\t\treturn \"\", pkgerrors.Wrap(err, \"Deserialize deployment error\")\n\t}\n\n\tswitch o := obj.(type) {\n\tcase *appsV1.Deployment:\n\t\tkubedata.DeploymentData = o\n\tdefault:\n\t\treturn \"\", pkgerrors.New(kubedata.YamlFilePath + \" contains another resource different than Deployment\")\n\t}\n\n\tkubedata.DeploymentData.Namespace = kubedata.Namespace\n\tkubedata.DeploymentData.Name = kubedata.InternalVNFID + \"-\" + kubedata.DeploymentData.Name\n\n\tresult, err := kubeclient.AppsV1().Deployments(kubedata.Namespace).Create(kubedata.DeploymentData)\n\tif err != nil {\n\t\treturn \"\", pkgerrors.Wrap(err, \"Create Deployment error\")\n\t}\n\n\treturn result.GetObjectMeta().GetName(), nil\n}", "func (k *Kube) createServiceObj(s *v1.Service, namespace string, hostname string, internalname string) *v1.Service {\n\ts.Spec.Type = \"ExternalName\"\n\ts.Spec.ExternalName = hostname\n\n\ts.Name = internalname\n\ts.Annotations = map[string]string{\"origin\": \"rds\"}\n\ts.Namespace = namespace\n\treturn s\n}", "func NewTerraChainResource(chain types.DBChain) TerraChainResource {\n\treturn TerraChainResource{chainResource[db.ChainCfg]{\n\t\tJAID: NewJAID(chain.ID),\n\t\tConfig: chain.Cfg,\n\t\tEnabled: chain.Enabled,\n\t\tCreatedAt: chain.CreatedAt,\n\t\tUpdatedAt: chain.UpdatedAt,\n\t}}\n}", "func (k *K8sStore) AddResource(obj interface{}) {\n\tkey, ns, labels := resourceKey(obj)\n\tnewObj := k.resourceCtor(obj, k.ctorConfig)\n\tglog.V(11).Infof(\"%s added: %s\", k.resourceName, key)\n\tk.dataMutex.Lock()\n\tk.data[key] = newObj\n\tk.dataMutex.Unlock()\n\tk.updateLabelMap(ns, labels, 1)\n\n\terr := k.AppendNewObject(newObj)\n\tif err != nil {\n\t\tglog.Warningf(\"Error when appending new object to current state: %v\", err)\n\t}\n}", "func (r *resource) Create(resource meta.ResourceObject) error {\n\tlog := log.With(\"kind\", resource.GetObjectKind().GroupVersionKind().Kind, \"name\", resource.GetName(), \"namespace\", resource.GetNamespace())\n\tlog.Debug(\"Creating\")\n\tif err := r.client.ControlCli.Create(context.TODO(), resource); err != nil {\n\t\tlog.Warn(\"Failed to create object. \", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *PoolNAPTRResource) Create(item Pool) error {\n\tif err := r.c.ModQuery(\"POST\", BasePath+PoolNAPTREndpoint, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewResourceAuth(init ...*ResourceAuth) *ResourceAuth {\n\tvar o *ResourceAuth\n\tif len(init) == 1 {\n\t\to = init[0]\n\t} else {\n\t\to = new(ResourceAuth)\n\t}\n\treturn o\n}", "func NewResourceCommand() cli.Command {\n\tcmd := cli.Command{\n\t\tName: \"resource\",\n\t\tUsage: \"display registered resources\",\n\t\tAction: execResourceCommand,\n\t}\n\n\treturn cmd\n}", "func (a *ResourcepoolApiService) CreateResourcepoolPool(ctx context.Context) ApiCreateResourcepoolPoolRequest {\n\treturn ApiCreateResourcepoolPoolRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func resourceVolterraVirtualNetwork() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceVolterraVirtualNetworkCreate,\n\t\tRead: resourceVolterraVirtualNetworkRead,\n\t\tUpdate: resourceVolterraVirtualNetworkUpdate,\n\t\tDelete: resourceVolterraVirtualNetworkDelete,\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\"global_network\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"legacy_type\": {\n\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"site_local_inside_network\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"site_local_network\": {\n\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"srv6_network\": {\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\"access_network_rtargets\": {\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\"asn2byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"asn4byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"ipv4_addr_rtarget\": {\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\"address\": {\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\"value\": {\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\"anycast_vip\": {\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\"fleet_vip\": {\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\"vip_allocator\": {\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\"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\"interface_ip_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\"enterprise_network_rtargets\": {\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\"asn2byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"asn4byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"ipv4_addr_rtarget\": {\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\"address\": {\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\"value\": {\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\"export_rtargets\": {\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\"asn2byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"asn4byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"ipv4_addr_rtarget\": {\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\"address\": {\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\"value\": {\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\"fleets\": {\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\"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\"internet_rtargets\": {\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\"asn2byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"asn4byte_rtarget\": {\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\"as_number\": {\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\"value\": {\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\n\t\t\t\t\t\t\t\t\t\"ipv4_addr_rtarget\": {\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\"address\": {\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\"value\": {\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_namespace_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\"srv6_network_ns_params\": {\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\"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},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"remote_sid_stats_plen\": {\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\"slice\": {\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\"fleet_snat_pool\": {\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\"snat_pool_allocator\": {\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\"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\"interface_ip_snat_pool\": {\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\"site_snat_pool\": {\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\"node_snat_pool\": {\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\"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\tRequired: 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\"value\": {\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\tRequired: 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_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\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"ipv6_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\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"static_routes\": {\n\n\t\t\t\tType: schema.TypeList,\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\"attrs\": {\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\"ip_prefixes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tRequired: 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\"default_gateway\": {\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\"interface\": {\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\"ip_address\": {\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\"static_v6_routes\": {\n\n\t\t\t\tType: schema.TypeList,\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\"attrs\": {\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\"ip_prefixes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tRequired: 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\"default_gateway\": {\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\"interface\": {\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\"ip_address\": {\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\t\t},\n\t}\n}", "func NewResourceInput(init ...*ResourceInput) *ResourceInput {\n\tvar o *ResourceInput\n\tif len(init) == 1 {\n\t\to = init[0]\n\t} else {\n\t\to = new(ResourceInput)\n\t}\n\treturn o\n}", "func NewResourceNode(networkID string, pubKey crypto.PubKey, ownerAddr sdk.AccAddress,\n\tdescription Description, nodeType string, creationTime time.Time) ResourceNode {\n\treturn ResourceNode{\n\t\tNetworkID: networkID,\n\t\tPubKey: pubKey,\n\t\tSuspend: false,\n\t\tStatus: sdk.Unbonded,\n\t\tTokens: sdk.ZeroInt(),\n\t\tOwnerAddress: ownerAddr,\n\t\tDescription: description,\n\t\tNodeType: nodeType,\n\t\tCreationTime: creationTime,\n\t}\n}", "func NewOracleMgr(address common.Address, backend bind.ContractBackend) (*OracleMgr, error) {\n\tcontract, err := bindOracleMgr(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &OracleMgr{OracleMgrCaller: OracleMgrCaller{contract: contract}, OracleMgrTransactor: OracleMgrTransactor{contract: contract}, OracleMgrFilterer: OracleMgrFilterer{contract: contract}}, nil\n}", "func DlcOracleFromBytes(b []byte) (*DlcOracle, error) {\n\tbuf := bytes.NewBuffer(b)\n\to := new(DlcOracle)\n\n\tcopy(o.A[:], buf.Next(33))\n\n\tvar nameLen uint32\n\terr := binary.Read(buf, binary.BigEndian, &nameLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to.Name = string(buf.Next(int(nameLen)))\n\n\tvar urlLen uint32\n\terr = binary.Read(buf, binary.BigEndian, &urlLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\to.Url = string(buf.Next(int(urlLen)))\n\n\treturn o, nil\n}", "func ManualLoadOracle() {\n\tif _, ok := internal.SchemaLoaders[\"godror\"]; !ok {\n\t\tinternal.SchemaLoaders[\"godror\"] = internal.TypeLoader{\n\t\t\tParamN: func(i int) string { return fmt.Sprintf(\":%d\", i+1) },\n\t\t\tMaskFunc: func() string { return \":%d\" },\n\t\t\tProcessRelkind: OrRelkind,\n\t\t\tSchema: OrSchema,\n\t\t\tParseType: OrParseType,\n\t\t\t//EnumList: models.OrEnums,\n\t\t\t//EnumValueList: OrEnumValues,\n\t\t\t//ProcList: models.OrProcs,\n\t\t\t//ProcParamList: models.OrProcParams,\n\t\t\tTableList: models.OrTables,\n\t\t\tColumnList: OrTableColumns,\n\t\t\tForeignKeyList: OrTableForeignKeys,\n\t\t\tIndexList: OrTableIndexes,\n\t\t\tIndexColumnList: OrIndexColumns,\n\t\t\tQueryColumnList: OrQueryColumns,\n\t\t}\n\t}\n}", "func makeResource(mod string, res string) tokens.Type {\n\tfn := string(unicode.ToLower(rune(res[0]))) + res[1:]\n\treturn makeType(mod+\"/\"+fn, res)\n}", "func NewCTROracle() *CTROracle {\n\trand.Seed(time.Now().UnixNano())\n\tkey := make([]byte, 16)\n\trand.Read(key)\n\n\tnonce := rand.Intn(1 << 31)\n\n\treturn &CTROracle{Key: key, Nonce: uint64(nonce)}\n}", "func NewDNSSECOracle(backend bind.ContractBackend, domain string) (*DNSSECOracle, error) {\n\tregistrar, err := NewDNSRegistrar(backend, domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddress, err := registrar.Contract.Oracle(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontract, err := dnssecoracle.NewContract(address, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DNSSECOracle{\n\t\tbackend: backend,\n\t\tdomain: domain,\n\t\tContract: contract,\n\t\tContractAddr: address,\n\t}, nil\n}", "func NewResourceKey(o metav1.Object, t metav1.Type) ResourceKey {\n\treturn ResourceKey(fmt.Sprintf(\"%s/%s=%s,Kind=%s\", o.GetNamespace(), o.GetName(), t.GetAPIVersion(), t.GetKind()))\n}", "func (m *GormResourceRepository) Create(ctx context.Context, resource *Resource) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"resource\", \"create\"}, time.Now())\n\n\t// If no identifier has been specified for the new resource, then generate one\n\tif resource.ResourceID == \"\" {\n\t\tresource.ResourceID = uuid.NewV4().String()\n\t}\n\n\tif resource.ResourceTypeID.String() == \"\" {\n\t\tresourceType, err := m.resourceTypeRepo.Lookup(ctx, resource.ResourceType.Name)\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\t\"resource_type\": resource.ResourceType.Name,\n\t\t\t\t\"err\": err,\n\t\t\t}, \"unable to find the resource type\")\n\t\t\treturn errs.WithStack(err)\n\t\t}\n\t\tresource.ResourceTypeID = resourceType.ResourceTypeID\n\t}\n\n\terr := m.db.Create(resource).Error\n\tif err != nil {\n\t\t// Organization names must be unique\n\t\tif gormsupport.IsUniqueViolation(err, \"unique_organization_names\") {\n\t\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\t\"err\": err,\n\t\t\t\t\"name\": resource.Name,\n\t\t\t}, \"unable to create organization resource as an organization with the same name already exists\")\n\t\t\treturn errors.NewDataConflictError(fmt.Sprintf(\"organization with same name already exists, '%s'\", resource.Name))\n\t\t}\n\t\tif gormsupport.IsUniqueViolation(err, \"resource_pkey\") {\n\t\t\treturn errors.NewDataConflictError(fmt.Sprintf(\"resource with ID %s already exists\", resource.ResourceID))\n\t\t}\n\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"resource_id\": resource.ResourceID,\n\t\t\t\"err\": err,\n\t\t}, \"unable to create the resource\")\n\t\treturn errs.WithStack(err)\n\t}\n\n\tlog.Info(ctx, map[string]interface{}{\n\t\t\"resource_id\": resource.ResourceID,\n\t}, \"Resource created!\")\n\treturn nil\n}", "func (_Mcapscontroller *McapscontrollerSession) Oracle() (common.Address, error) {\n\treturn _Mcapscontroller.Contract.Oracle(&_Mcapscontroller.CallOpts)\n}" ]
[ "0.65095305", "0.6407476", "0.63443345", "0.62293494", "0.6156265", "0.6054818", "0.60185814", "0.5885527", "0.5867745", "0.57778424", "0.5640023", "0.5636545", "0.56110036", "0.55784786", "0.55699235", "0.5534356", "0.5521", "0.5510197", "0.5499911", "0.5495446", "0.5469426", "0.54661834", "0.5463511", "0.5414163", "0.5405944", "0.5365296", "0.5330432", "0.5330188", "0.5311868", "0.5300773", "0.52704614", "0.52600676", "0.525202", "0.52232814", "0.5204882", "0.5191593", "0.5179034", "0.5178792", "0.51753324", "0.51631933", "0.5139027", "0.51165986", "0.5115492", "0.5099707", "0.50912863", "0.5083819", "0.50587595", "0.5057318", "0.5046975", "0.50421464", "0.50374454", "0.5035723", "0.50226635", "0.50085217", "0.49982867", "0.49818835", "0.4940203", "0.4933184", "0.4933184", "0.49284184", "0.49284184", "0.4926781", "0.49087602", "0.49085373", "0.49085265", "0.49077317", "0.49015626", "0.4875455", "0.48662677", "0.48652515", "0.4860243", "0.4851044", "0.48484483", "0.48437178", "0.48435378", "0.48429838", "0.4832343", "0.4832037", "0.48096335", "0.48073402", "0.48066556", "0.48018008", "0.4799017", "0.47928008", "0.4790682", "0.4781262", "0.47778067", "0.4767233", "0.4758284", "0.4755256", "0.4753384", "0.4744917", "0.47433674", "0.4741598", "0.47331926", "0.47281542", "0.47277632", "0.4727353", "0.4720428", "0.47183734" ]
0.7561354
0
Total returns the total amount of resource units of the node
func (r *ResourceOracle) Total() (c gridtypes.Capacity, err error) { c.CRU, err = r.cru() if err != nil { return c, err } c.MRU, err = r.mru() if err != nil { return c, err } c.SRU, err = r.sru() if err != nil { return c, err } c.HRU, err = r.hru() if err != nil { return c, err } return c, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *MultipleNode) GetTotal() int64 {\n\tif o == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\n\treturn o.Total\n}", "func (s *CPUStat) Total() float64 {\n\treturn float64(len(s.cpus))\n}", "func (o *ClusterMetricsNodes) GetTotal() float64 {\n\tif o == nil || o.Total == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func (r *BreakdownResolver) Total() int32 {\n\treturn int32(r.breakdown.Total)\n}", "func (s *Module) Total(kind pkg.DeviceType) (uint64, error) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\n\tswitch kind {\n\tcase zos.SSDDevice:\n\t\treturn s.totalSSD, nil\n\tcase zos.HDDDevice:\n\t\treturn s.totalHDD, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"kind %+v unknown\", kind)\n\t}\n}", "func (gt *myGoTickle) Total() uint32 {\n\treturn gt.total\n}", "func (r *Reservoir) GetTotal() uint64 {\n\treturn r.total\n}", "func (m *Memory) Total() uint64 {\r\n\ttotal := uint64(0)\r\n\tfor _, val := range m.memory {\r\n\t\ttotal += val\r\n\t}\r\n\treturn total\r\n}", "func (b *ClusterNodesBuilder) Total(value int) *ClusterNodesBuilder {\n\tb.total = &value\n\treturn b\n}", "func Total() uint64 {\n\treturn totalGrains\n}", "func Total() uint64 {\n\treturn totalGrains\n}", "func (ms MVCCStats) Total() int64 {\n\treturn ms.KeyBytes + ms.ValBytes\n}", "func (or Order) Total() float64 {\n\t//implement total here\n\treturn 0.0\n}", "func (b *Plain) MetricTotal() string {\n\treturn totalBucket + \".\" + b.section\n}", "func (o *MultipleDevice) GetTotal() int64 {\n\tif o == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\n\treturn o.Total\n}", "func (pot *SidePot) Total() float64 {\n\tsum := 0.\n\tfor _, amount := range pot.Members {\n\t\tsum += amount\n\t}\n\n\treturn sum\n}", "func Total() uint64 {\n\treturn (uint64)((1 << 64) - 1)\n}", "func (p *Properties) TotalNodes() int {\n\tvar totalNodes int\n\tfor _, pool := range p.AgentPoolProfiles {\n\t\ttotalNodes = totalNodes + pool.Count\n\t}\n\treturn totalNodes\n}", "func Total() uint64 {\n\treturn 1<<64 - 1\n}", "func Total() uint64 {\n\treturn 1<<64 - 1\n}", "func Total() uint64 {\n\treturn 1<<64 - 1\n}", "func Total() uint64 {\n\treturn 1<<64 - 1\n}", "func Total() uint64 {\n\treturn 1<<64 - 1\n}", "func Total() uint64 {\n\treturn math.MaxUint64\n}", "func Total() uint64 {\n\treturn (1 << 64) - 1\n}", "func (m *Memory2) Total() uint64 {\r\n\ttotal := uint64(0)\r\n\tfor _, val := range m.memory {\r\n\t\ttotal += val\r\n\t}\r\n\treturn total\r\n}", "func (s *State) Total() int64 {\n\treturn s.total\n}", "func (r *MachinePoolsListServerResponse) Total(value int) *MachinePoolsListServerResponse {\n\tr.total = &value\n\treturn r\n}", "func Total() uint64 {\n\treturn 18446744073709551615\n}", "func (d *Die) Total(ctx context.Context) (float64, error) {\n\tif d == nil {\n\t\treturn 0.0, ErrNilDie\n\t}\n\tif d.Result == nil {\n\t\treturn 0.0, ErrUnrolled\n\t}\n\treturn d.Result.Total(ctx)\n}", "func (m *Blueprint) TotalEnergy() (float64, error) {\n\treturn 0, api.ErrNotAvailable\n}", "func (c *Contribution) Total() int {\n\treturn c.total\n}", "func getTotalAllocatableMemory(f *framework.Framework) *resource.Quantity {\n\tselector := labels.Set{\"beta.kubernetes.io/os\": \"windows\"}.AsSelector()\n\tnodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{\n\t\tLabelSelector: selector.String(),\n\t})\n\tframework.ExpectNoError(err)\n\n\tginkgo.By(\"Summing allocatable memory across all agent nodes\")\n\n\ttotalAllocatable := resource.NewQuantity(0, resource.BinarySI)\n\n\tfor _, node := range nodeList.Items {\n\t\tstatus := node.Status\n\n\t\ttotalAllocatable.Add(status.Allocatable[v1.ResourceMemory])\n\t}\n\n\treturn totalAllocatable\n}", "func (c *CCU) TotalEnergy() (float64, error) {\n\tif c.usage == \"grid\" {\n\t\treturn c.conn.GridTotalEnergy()\n\t}\n\treturn c.conn.TotalEnergy()\n}", "func (o *StorageBaseCapacity) GetTotal() int64 {\n\tif o == nil || o.Total == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func (f Fortune) Total() decimal.Decimal { return f.active.Add(f.saving) }", "func (m *MultiInstances) Total() int {\n\ttotal := 0\n\tfor _, instances := range m.m {\n\t\ttotal += len(instances)\n\t}\n\treturn total\n}", "func (pb *Bar) Total() int64 {\n\treturn atomic.LoadInt64(&pb.total)\n}", "func (r *MachinePoolsListResponse) Total() int {\n\tif r != nil && r.total != nil {\n\t\treturn *r.total\n\t}\n\treturn 0\n}", "func Total() uint64 {\n\treturn conv(math.Pow(2, 64))\n}", "func (nc NvmeController) Total() (tb uint64) {\n\tfor _, d := range nc.SmdDevices {\n\t\ttb += d.TotalBytes\n\t}\n\treturn\n}", "func DiskTotal() (uint64, error) {\n\tusage, err := Disk()\n\t// for i := 0; i < len(usage); i++ {\n\tif len(usage) > 0 {\n\t\ttotalDisk := usage[0].Total\n\t\treturn totalDisk, err\n\t}\n\n\treturn 0, err\n}", "func Total() (grains uint64) {\n\treturn 1<<64 - 1\n}", "func (c *CountResult) Total() int {\n\tvar t int\n\tfor k := range c.m {\n\t\tt += c.m[k]\n\t}\n\treturn t\n}", "func (z *Zzz) Total() int64 { //nolint:dupl false positive\n\trows := z.Adapter.CallBoxSpace(z.SpaceName() + `:count`, A.X{})\n\tif len(rows) > 0 && len(rows[0]) > 0 {\n\t\treturn X.ToI(rows[0][0])\n\t}\n\treturn 0\n}", "func totalResourceLimits(args ...interface{}) (interface{}, error) {\n\trr, err := TotalResourceLimits(args[0].(map[string]interface{}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resourceQuantity(rr, args[1])\n}", "func (s NodeService) GetTotalCapacity(ctx context.Context, deviceGroup string, topology *csi.Topology) (int64, error) {\n\tnl, err := s.getNodes(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tcapacity := int64(0)\n\tfor _, node := range nl.Items {\n\t\t// topology selector\n\t\tif topology != nil {\n\t\t\tselector := labels.SelectorFromSet(topology.GetSegments())\n\t\t\tif !selector.Matches(labels.Set(node.Labels)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tfor key, v := range node.Status.Capacity {\n\n\t\t\tif deviceGroup == \"\" && strings.HasPrefix(string(key), utils.DeviceCapacityKeyPrefix) {\n\t\t\t\tcapacity += v.Value()\n\t\t\t} else if string(key) == deviceGroup || string(key) == utils.DeviceCapacityKeyPrefix+deviceGroup {\n\t\t\t\tcapacity += v.Value()\n\t\t\t}\n\t\t}\n\t}\n\treturn capacity, nil\n}", "func (dt *DirTracker) Total() int64 {\n\treturn atomic.LoadInt64(&dt.directoryCountTotal)\n}", "func (a *ResourceAllocator) TotalAllocated() int64 {\n\treturn atomic.LoadInt64(&a.totalAllocated)\n}", "func (o *MultipleNode) GetTotalOk() (*int64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Total, true\n}", "func (m MilestonesStats) Total() int64 {\n\treturn m.OpenCount + m.ClosedCount\n}", "func (c *Connection) TotalEnergy() (float64, error) {\n\tres, err := c.meterCache.Get()\n\treturn res.FloatValue(\"ENERGY_COUNTER\") / 1e3, err\n}", "func (c *FritzDECT) TotalEnergy() (float64, error) {\n\treturn c.conn.TotalEnergy()\n}", "func Total() uint64 {\n\treturn 1<<uint64(max) - 1\n}", "func (o *FileProjectUsage) GetTotal() int32 {\n\tif o == nil || o.Total == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func (r *SubscriptionsListServerResponse) Total(value int) *SubscriptionsListServerResponse {\n\tr.total = &value\n\treturn r\n}", "func (sw *SW) Total() int {\n\tsw.mtx.Lock()\n\n\tif sw.elems == nil || len(sw.elems) == 0 {\n\t\tsw.mtx.Unlock()\n\t\treturn 0\n\t}\n\n\tvar total int\n\tfor _, elem := range sw.elems {\n\t\ttotal += elem.weight\n\t}\n\n\tsw.mtx.Unlock()\n\treturn total\n}", "func (t table) Total() int {\n\treturn t.total\n}", "func (s SwapCost) Total() btcutil.Amount {\n\treturn s.Server + s.Onchain + s.Offchain\n}", "func (r *SubscriptionsListServerRequest) Total() int {\n\tif r != nil && r.total != nil {\n\t\treturn *r.total\n\t}\n\treturn 0\n}", "func (r *Report) TotalCost() float64 {\n\ttotal := 0.0\n\tfor i := range r.Items {\n\t\ttotal += r.Items[i].Cost\n\t}\n\treturn total\n}", "func cpuTotal(t *cpu.TimesStat) float64 {\n\treturn t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal +\n\t\tt.Guest + t.GuestNice + t.Idle\n}", "func (wb *Alfen) TotalEnergy() (float64, error) {\n\tb, err := wb.conn.ReadHoldingRegisters(alfenRegEnergy, 4)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn math.Float64frombits(binary.BigEndian.Uint64(b)) / 1e3, err\n}", "func (c *Easee) TotalEnergy() (float64, error) {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\n\treturn c.totalEnergy, nil\n}", "func (q *quartileIndex) Total() int {\n\treturn q.bits.Total()\n}", "func (c Count) Total() (x int) {\n\tfor _, i := range c {\n\t\tx += i\n\t}\n\treturn\n}", "func (mp MassPayment) Total() float64 {\n\ttotal := 0.0\n\tfor _, item := range mp.Items {\n\t\ttotal += item.Amount\n\t}\n\n\treturn total\n}", "func (r Receipt) Total() float64 {\n\tvar total float64\n\tfor _, li := range r.LineItems {\n\t\ttotal += li.Subtotal()\n\t\tfmt.Println(li)\n\t}\n\treturn total\n}", "func (o *MultipleNode) SetTotal(v int64) {\n\to.Total = v\n}", "func (t *BalanceTable) Total() (abi.TokenAmount, error) {\n\ttotal := big.Zero()\n\tvar cur abi.TokenAmount\n\terr := (*Map)(t).ForEach(&cur, func(key string) error {\n\t\ttotal = big.Add(total, cur)\n\t\treturn nil\n\t})\n\treturn total, err\n}", "func Total() uint64 {\n\t// equivalent to 2**64-1\n\treturn 1<<64 - 1\n}", "func (u updates) Total(l UpdateLabels) prometheus.Counter {\n\treturn u.total.WithLabelValues(l.Values()...)\n}", "func (k Keeper) TotalTokens(ctx sdk.Ctx) sdk.BigInt {\n\treturn k.AccountKeeper.GetSupply(ctx).GetTotal().AmountOf(k.StakeDenom(ctx))\n}", "func (h *Histogram) Total() (total int64) {\n\treturn h.total.Load()\n}", "func (eta *ETA) GetTotal() int64 {\n\treturn eta.total\n}", "func Total() uint64 {\n\tsum := uint64(0)\n\tfor i := 1; i < 65; i++ {\n\t\tn, _ := Square(i)\n\t\tsum += n\n\t}\n\treturn sum\n}", "func Total() uint64 {\n\tvar total uint64\n\t// first square has 1 grain of sand\n\t// grainsMap := make(map[int]uint64, 64)\n\t// grainsMap[1] = 1\n\t// for i := 2; i <= 64; i++ {\n\t// \tgrainsMap[i] = grainsMap[i-1] * 2\n\t// }\n\t// for _, grains := range grainsMap {\n\t// \ttotal += grains\n\t// }\n\t// return total\n\treturn 64 << 1\n}", "func (ps Passengers) Total() int {\n\treturn len(ps)\n}", "func (o TagOutput) TotalResourceCount() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Tag) pulumi.IntOutput { return v.TotalResourceCount }).(pulumi.IntOutput)\n}", "func (c CPUMap) Total() int {\n\tvar count int\n\tfor _, value := range c {\n\t\tcount += value\n\t}\n\treturn count\n}", "func (m *JobManager) Total() (int64, error) {\n\treturn m.table.Count()\n}", "func TestGetTotal(t *testing.T) {\n\tpncounter = pncounter.SetCount(\"testNode1\", 1, 1)\n\tpncounter = pncounter.SetCount(\"testNode2\", 3, 1)\n\tpncounter = pncounter.SetCount(\"testNode3\", 5, 3)\n\n\texpectedCount := 4\n\tactualCount := pncounter.GetTotal()\n\n\tassert.Equal(t, expectedCount, actualCount)\n\n\tpncounter = pncounter.Clear(testNode)\n}", "func (s *State) Total() int {\n\treturn len(s.groups)\n}", "func (o *Bundles) GetTotal() int32 {\n\tif o == nil || o.Total == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func (e *lockedLastMinuteLatency) total() AccElem {\n\te.Lock()\n\tdefer e.Unlock()\n\treturn e.lastMinuteLatency.getTotal()\n}", "func (r *MachinePoolsListResponse) GetTotal() (value int, ok bool) {\n\tok = r != nil && r.total != nil\n\tif ok {\n\t\tvalue = *r.total\n\t}\n\treturn\n}", "func Total() uint64 {\n\tvar sum uint64\n\tfor x := 1; x <= 64; x++ {\n\t\tsum += uint64(math.Pow(2, float64(x-1)))\n\t}\n\treturn uint64(sum)\n}", "func (group *networkGroup) getTotalStaked(c *gin.Context) {\n\ttotalStakedData, err := group.facade.GetTotalStaked()\n\tif err != nil {\n\t\tshared.RespondWith(c, http.StatusInternalServerError, nil, err.Error(), data.ReturnCodeInternalError)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, totalStakedData)\n}", "func (o *ClusterMetricsNodes) GetTotalOk() (*float64, bool) {\n\tif o == nil || o.Total == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Total, true\n}", "func Total() uint64 {\n\t// Total() is the sum of all powers of 2 with exponents 0 to 63.\n\t// That sum is a 64 bit integer with all bits set to 1.\n\treturn ^uint64(0)\n}", "func (c *KebaUdp) totalEnergy() (float64, error) {\n\tvar kr keba.Report3\n\terr := c.roundtrip(\"report\", 3, &kr)\n\n\t// mW to W\n\treturn float64(kr.ETotal) / 1e4, err\n}", "func (n *resPool) CalculateTotalAllocatedResources() *scalar.Resources {\n\tn.Lock()\n\tdefer n.Unlock()\n\treturn n.calculateAllocation().GetByType(scalar.TotalAllocation)\n}", "func (o *PrivilegeUsersResponse) GetTotal() int32 {\n\tif o == nil || o.Total == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Total\n}", "func GetTotalGPUMemory(node *v1.Node) int {\n\tval, ok := node.Status.Capacity[ResourceName]\n\n\tif !ok {\n\t\treturn 0\n\t}\n\n\treturn int(val.Value())\n}", "func TotalSupply(k Keeper) sdk.Invariant {\n\treturn func(ctx sdk.Context) (string, bool) {\n\t\treturn sdk.FormatInvariant(types.ModuleName, \"total supply\",\n\t\t\tfmt.Sprintf(\"\\tsum of accounts coins: %v\\n\"+\n\t\t\t\t\"\\tsupply.Total: %v\\n\",\n\t\t\t\t100, 100)), true\n\t}\n}", "func TotalSupply() int {\n\treturn token.GetSupply(ctx)\n}", "func sumPodResource(p *core_v1.Pod, kind core_v1.ResourceName) int64 {\n\ttotal := int64(0)\n\tfor _, c := range p.Spec.Containers {\n\t\tres, ok := c.Resources.Requests[kind]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif kind == core_v1.ResourceMemory {\n\t\t\ttotal = total + (&res).Value()\n\t\t} else if kind == ResourceGPU {\n\t\t\ttotal = total + (&res).Value()\n\t\t} else {\n\t\t\ttotal = total + (&res).MilliValue()\n\t\t}\n\t}\n\n\treturn total\n}", "func (_MonsterOwnership *MonsterOwnershipCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _MonsterOwnership.contract.Call(opts, out, \"totalSupply\")\n\treturn *ret0, err\n}", "func (wb *CfosPowerBrain) TotalEnergy() (float64, error) {\n\tb, err := wb.conn.ReadHoldingRegisters(cfosRegEnergy, 4)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn float64(binary.BigEndian.Uint64(b)) / 1e3, err\n}", "func (counts ProcessCounts) Total() int {\n\tvar total int64\n\tdesiredValue := reflect.ValueOf(counts)\n\tfor _, index := range processClassIndices {\n\t\tdesired := desiredValue.Field(index).Int()\n\t\tif desired > 0 {\n\t\t\ttotal += desired\n\t\t}\n\t}\n\n\treturn int(total)\n}" ]
[ "0.718967", "0.6913241", "0.6882275", "0.6867854", "0.6856648", "0.6792636", "0.6743216", "0.670683", "0.6677151", "0.6633152", "0.6633152", "0.66038734", "0.65789604", "0.6560127", "0.65569973", "0.65532714", "0.6549836", "0.65277636", "0.65214187", "0.65214187", "0.65214187", "0.65214187", "0.65214187", "0.6509298", "0.6471701", "0.6468471", "0.6465865", "0.64496696", "0.6442437", "0.6433866", "0.642487", "0.6409487", "0.6403723", "0.6390923", "0.6390074", "0.638966", "0.63501185", "0.63488626", "0.63461494", "0.6333559", "0.63289136", "0.63272816", "0.63216555", "0.6320455", "0.6312939", "0.63121563", "0.62866193", "0.6265948", "0.62635225", "0.6261943", "0.6255509", "0.62271595", "0.62015766", "0.6194485", "0.61928606", "0.6178153", "0.616993", "0.6163854", "0.6156509", "0.61400366", "0.61399144", "0.6138799", "0.6125532", "0.6123781", "0.61177367", "0.6084299", "0.6079063", "0.6070855", "0.60664773", "0.6041274", "0.6038212", "0.60382044", "0.60363984", "0.60359263", "0.6032369", "0.60102063", "0.60079867", "0.6002696", "0.5982488", "0.5975498", "0.59704375", "0.5954238", "0.5950055", "0.5947906", "0.594202", "0.59407806", "0.5934848", "0.59320784", "0.59254134", "0.59213805", "0.59177274", "0.5910116", "0.59097654", "0.59070736", "0.5905478", "0.5905322", "0.5884229", "0.58762205", "0.5875392", "0.587223" ]
0.6880509
3
DMI run and parse dmidecode commands
func (r *ResourceOracle) DMI() (*dmi.DMI, error) { return dmi.Decode() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getManufacturer(){\n manufacturer, err := exec.Command(\"/bin/bash\", \"-c\", \"dmidecode --type 3 | awk '/Manufacturer/ {print $2}'\").Output()\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(\"%s\", manufacturer)\n}", "func (p *Program) Disassemble(w io.Writer) (int, error) {\n\tvar buf bytes.Buffer\n\tvar total int\n\n\tflush := func() error {\n\t\tn, err := w.Write(buf.Bytes())\n\t\ttotal += n\n\t\tbuf.Reset()\n\t\treturn err\n\t}\n\n\tfor _, literal := range p.Literals {\n\t\tbuf.WriteString(\"%literal \")\n\t\tif utf8.Valid(literal) {\n\t\t\tfmt.Fprintf(&buf, \"%q\", literal)\n\t\t} else {\n\t\t\tfirst := true\n\t\t\tfor _, b := range literal {\n\t\t\t\tif !first {\n\t\t\t\t\tbuf.WriteByte(',')\n\t\t\t\t\tbuf.WriteByte(' ')\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(&buf, \"0x%02x\", b)\n\t\t\t\tfirst = false\n\t\t\t}\n\t\t}\n\t\tbuf.WriteByte('\\n')\n\t\tif err := flush(); err != nil {\n\t\t\treturn total, err\n\t\t}\n\t}\n\n\tfor _, matcher := range p.ByteSets {\n\t\tbuf.WriteString(\"%matcher \")\n\t\tbuf.WriteString(matcher.String())\n\t\tbuf.WriteByte('\\n')\n\t\tif err := flush(); err != nil {\n\t\t\treturn total, err\n\t\t}\n\t}\n\n\tfmt.Fprintf(&buf, \"%%captures %d\\n\", len(p.Captures))\n\tif err := flush(); err != nil {\n\t\treturn total, err\n\t}\n\tfor i, capture := range p.Captures {\n\t\tif capture.Name != \"\" {\n\t\t\tfmt.Fprintf(&buf, \"%%namedcapture %d %q\\n\", i, capture.Name)\n\t\t\tif err := flush(); err != nil {\n\t\t\t\treturn total, err\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf.WriteByte('\\n')\n\tif err := flush(); err != nil {\n\t\treturn total, err\n\t}\n\n\tvar op Op\n\tvar xp uint64\n\n\t// First pass: identify code offsets that need labels\n\tvar labelNeeded = make(map[uint64]struct{})\n\tfor {\n\t\terr := op.Decode(p.Bytes, xp)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn total, err\n\t\t}\n\n\t\tmeta := op.Meta\n\t\tif meta == nil {\n\t\t\tmeta = op.Code.Meta()\n\t\t}\n\n\t\txp += uint64(op.Len)\n\t\tif meta.Imm0.Type == ImmCodeOffset {\n\t\t\ttarget := addOffset(xp, u2s(op.Imm0))\n\t\t\tlabelNeeded[target] = struct{}{}\n\t\t}\n\t\tif meta.Imm1.Type == ImmCodeOffset {\n\t\t\ttarget := addOffset(xp, u2s(op.Imm1))\n\t\t\tlabelNeeded[target] = struct{}{}\n\t\t}\n\t\tif meta.Imm2.Type == ImmCodeOffset {\n\t\t\ttarget := addOffset(xp, u2s(op.Imm2))\n\t\t\tlabelNeeded[target] = struct{}{}\n\t\t}\n\t}\n\n\t// Second pass: generate actual disassembly listing\n\txp = 0\n\tfor {\n\t\terr := op.Decode(p.Bytes, xp)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn total, err\n\t\t}\n\n\t\tif _, yes := labelNeeded[xp]; yes {\n\t\t\tlabel := p.FindLabel(xp)\n\t\t\tif label != nil {\n\t\t\t\tbuf.WriteString(label.Name)\n\t\t\t\tbuf.WriteByte(':')\n\t\t\t\tbuf.WriteByte('\\n')\n\t\t\t\tif err := flush(); err != nil {\n\t\t\t\t\treturn total, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\txp += uint64(op.Len)\n\t\tbuf.WriteByte('\\t')\n\t\tp.writeOp(&buf, &op, xp)\n\t\tbuf.WriteByte('\\n')\n\t\tif err := flush(); err != nil {\n\t\t\treturn total, err\n\t\t}\n\t}\n\treturn total, nil\n}", "func Disassemble(m *go6502.Memory, addr go6502.Address) (line string, next go6502.Address) {\n\topcode := m.ReadByte(addr)\n\tidata := &go6502.Instructions[opcode]\n\toperand := m.ReadBytes(addr+1, int(idata.Length)-1)\n\tfmtString := \"%s \" + modeFormat[idata.Mode]\n\tline = fmt.Sprintf(fmtString, idata.Name, hexString(operand))\n\tnext = addr + go6502.Address(idata.Length)\n\treturn\n}", "func Disassembler(pe *pefile.PEFile) {\n\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"......Let's find some bad stuff............................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Println(\" ,_---~~~~~----._ \")\n\tfmt.Println(\" _,,_,*^____ _____``*g*\\\\*, \")\n\tfmt.Println(\" \\\\ __\\\\ \\\\' ^. \\\\ \\\\ ^@q f \")\n\tfmt.Println(\" [ @f | @)) | | @)) l 0 _\\\\ \")\n\tfmt.Println(\" \\\\`\\\\ \\\\~____\\\\ __\\\\____\\\\ \\\\ \")\n\tfmt.Println(\" | _l__l_ I \")\n\tfmt.Println(\" } [______] I \")\n\tfmt.Println(\" ] | | | | \")\n\tfmt.Println(\" ] ~ ~ | \")\n\tfmt.Println(\" | | \")\n\tfmt.Println(\" | \t\t\t\t\t\t\t |\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\tfmt.Print(\"...........................................................\\n\")\n\n\tfmt.Println(`[+] We are going \\n\n\t\t\t\t\t\t\t\t [+] to start printing out \\n\n\t\t\t\t\t\t\t\t [+] the DosHeader String `)\n\tfmt.Println(pe.DosHeader.String())\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t [+] the DosHeader Size `)\n\tfmt.Println(pe.DosHeader.Size)\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t [+] the NTHeader String `)\n\tfmt.Println(pe.NTHeader.String())\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t[+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t[+] the COFFFileHeader String `)\n\tfmt.Println(pe.COFFFileHeader.String())\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t [+] the Optional Headers `)\n\n\tfmt.Println(pe.OptionalHeader)\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t [+] the Optional Headers Data Directories `)\n\tfor key, val := range pe.OptionalHeader.DataDirs {\n\t\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t\t [+] Key: `)\n\t\tfmt.Println(key)\n\t\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t\t [+] Value: `)\n\t\tfmt.Println(val)\n\t}\n\n\tfor key, val := range pe.OptionalHeader.Flags {\n\t\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t\t [+] Key: `)\n\t\tfmt.Println(key)\n\t\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t\t\t [+] Value: `)\n\t\tfmt.Println(val)\n\t}\n\n\tfmt.Println(`[+] Moving on to the next portion of the File \\n\n\t\t\t\t\t\t\t [+] Now to start printing out \\n\n\t\t\t\t\t\t\t [+] the range of the Portable Executable Sections `)\n\n\t// Print out the Sections inside the file in question\n\tfor _, s := range pe.Sections {\n\t\tfmt.Println(\"[+] Portable Executable Sectiong String: %s\", s.String())\n\t}\n\n\t// Print ouf the ImportDescriptors\n\n\t// for _, val := range pe.ImportDescriptors {\n\t// fmt.Println(val)\n\t// for _, val2 := range val.Imports {\n\t// \tfmt.Println(val2)\n\t// }\n\t// }\n\n\tfmt.Println(\"\\nDirectory_Entry_IMPORT\")\n\tfor _, entry := range pe.ImportDescriptors {\n\t\tfmt.Println(string(entry.Dll))\n\t\tfor _, imp := range entry.Imports {\n\t\t\tvar funcname string\n\t\t\tif len(imp.Name) == 0 {\n\t\t\t\tfuncname = fmt.Sprintf(\"ordinal+%d\", imp.Ordinal)\n\t\t\t} else {\n\t\t\t\tfuncname = string(imp.Name)\n\t\t\t}\n\t\t\tfmt.Println(\"\\t\", funcname)\n\t\t}\n\t}\n\n\tif pe.ExportDirectory != nil {\n\t\tfmt.Println(\"\\nDirectory_Entry_IMPORT\")\n\t\tfmt.Println(pe.ExportDirectory)\n\t\tfor _, entry := range pe.ExportDirectory.Exports {\n\t\t\tfmt.Printf(\"%d: %s:0x%x, forward: %s\\n\", entry.Ordinal, string(entry.Name), entry.Address, entry.Forwarder)\n\t\t}\n\t}\n\n}", "func MalwareExecuteScanCommand() *cobra.Command {\n\tconst STEP_NAME = \"malwareExecuteScan\"\n\n\tmetadata := malwareExecuteScanMetadata()\n\tvar stepConfig malwareExecuteScanOptions\n\tvar startTime time.Time\n\tvar reports malwareExecuteScanReports\n\tvar logCollector *log.CollectorHook\n\tvar splunkClient *splunk.Splunk\n\ttelemetryClient := &telemetry.Telemetry{}\n\n\tvar createMalwareExecuteScanCmd = &cobra.Command{\n\t\tUse: STEP_NAME,\n\t\tShort: \"Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).\",\n\t\tLong: `Performs a malware scan using the [SAP Malware Scanning Service](https://help.sap.com/viewer/b416237f818c4e2e827f6118640079f8/LATEST/en-US/b7c9b86fe724458086a502df3160f380.html).`,\n\t\tPreRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tstartTime = time.Now()\n\t\t\tlog.SetStepName(STEP_NAME)\n\t\t\tlog.SetVerbose(GeneralConfig.Verbose)\n\n\t\t\tGeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)\n\n\t\t\tpath, _ := os.Getwd()\n\t\t\tfatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}\n\t\t\tlog.RegisterHook(fatalHook)\n\n\t\t\terr := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.SetErrorCategory(log.ErrorConfiguration)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.RegisterSecret(stepConfig.DockerConfigJSON)\n\t\t\tlog.RegisterSecret(stepConfig.ContainerRegistryPassword)\n\t\t\tlog.RegisterSecret(stepConfig.ContainerRegistryUser)\n\t\t\tlog.RegisterSecret(stepConfig.Username)\n\t\t\tlog.RegisterSecret(stepConfig.Password)\n\n\t\t\tif len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {\n\t\t\t\tsentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)\n\t\t\t\tlog.RegisterHook(&sentryHook)\n\t\t\t}\n\n\t\t\tif len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {\n\t\t\t\tsplunkClient = &splunk.Splunk{}\n\t\t\t\tlogCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}\n\t\t\t\tlog.RegisterHook(logCollector)\n\t\t\t}\n\n\t\t\tif err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {\n\t\t\t\tlog.Entry().WithError(err).Warn(\"failed to set up SAP Alert Notification Service log hook\")\n\t\t\t}\n\n\t\t\tvalidation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = validation.ValidateStruct(stepConfig); err != nil {\n\t\t\t\tlog.SetErrorCategory(log.ErrorConfiguration)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\tRun: func(_ *cobra.Command, _ []string) {\n\t\t\tstepTelemetryData := telemetry.CustomData{}\n\t\t\tstepTelemetryData.ErrorCode = \"1\"\n\t\t\thandler := func() {\n\t\t\t\treports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)\n\t\t\t\tconfig.RemoveVaultSecretFiles()\n\t\t\t\tstepTelemetryData.Duration = fmt.Sprintf(\"%v\", time.Since(startTime).Milliseconds())\n\t\t\t\tstepTelemetryData.ErrorCategory = log.GetErrorCategory().String()\n\t\t\t\tstepTelemetryData.PiperCommitHash = GitCommit\n\t\t\t\ttelemetryClient.SetData(&stepTelemetryData)\n\t\t\t\ttelemetryClient.Send()\n\t\t\t\tif len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {\n\t\t\t\t\tsplunkClient.Initialize(GeneralConfig.CorrelationID,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.Dsn,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.Token,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.Index,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.SendLogs)\n\t\t\t\t\tsplunkClient.Send(telemetryClient.GetData(), logCollector)\n\t\t\t\t}\n\t\t\t\tif len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {\n\t\t\t\t\tsplunkClient.Initialize(GeneralConfig.CorrelationID,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,\n\t\t\t\t\t\tGeneralConfig.HookConfig.SplunkConfig.SendLogs)\n\t\t\t\t\tsplunkClient.Send(telemetryClient.GetData(), logCollector)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.DeferExitHandler(handler)\n\t\t\tdefer handler()\n\t\t\ttelemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)\n\t\t\tmalwareExecuteScan(stepConfig, &stepTelemetryData)\n\t\t\tstepTelemetryData.ErrorCode = \"0\"\n\t\t\tlog.Entry().Info(\"SUCCESS\")\n\t\t},\n\t}\n\n\taddMalwareExecuteScanFlags(createMalwareExecuteScanCmd, &stepConfig)\n\treturn createMalwareExecuteScanCmd\n}", "func (d *daemon) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {\n\tid, err := d.text.Cmd(format, args...)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\td.text.StartResponse(id)\n\tdefer d.text.EndResponse(id)\n\tcode, msg, err := d.text.ReadResponse(expectCode)\n\treturn code, msg, err\n}", "func (r *frontendRequest) processCmd(matches [][]string, isMiCmd bool) {\n\tr.token = matches[0][1]\n\tcmdLine := matches[0][2]\n\tcmdElts := strings.Split(cmdLine, \" \")\n\tr.gdbCmd = &gdbCmd{cmd: cmdElts[0], frontendRequest: r, isMiCmd: isMiCmd}\n\tif len(cmdElts) > 1 {\n\t\tr.gdbCmd.args = cmdElts[1:]\n\t\tr.gdbCmd.argsStr = strings.Join(r.gdbCmd.args, \" \")\n\t}\n\tr.gdbCmd.process()\n}", "func execmWordDecoderDecode(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret, ret1 := args[0].(*mime.WordDecoder).Decode(args[1].(string))\n\tp.Ret(2, ret, ret1)\n}", "func parseCode(ctx *Context, sourceFile string, sourceLine int, cmd string) (Elem, error) {\n\tcmd = strings.TrimSpace(cmd)\n\torigCmd := cmd\n\n\t// Pull off the HL, if any, from the end of the input line.\n\thighlight := \"\"\n\tif hl := highlightRE.FindStringSubmatchIndex(cmd); len(hl) == 4 {\n\t\tif hl[2] < 0 || hl[3] < 0 {\n\t\t\treturn nil, fmt.Errorf(\"%s:%d invalid highlight syntax\", sourceFile, sourceLine)\n\t\t}\n\t\thighlight = cmd[hl[2]:hl[3]]\n\t\tcmd = cmd[:hl[2]-2]\n\t}\n\n\t// Parse the remaining command line.\n\t// Arguments:\n\t// args[0]: whole match\n\t// args[1]: .code/.play\n\t// args[2]: flags (\"-edit -numbers\")\n\t// args[3]: file name\n\t// args[4]: optional address\n\targs := codeRE.FindStringSubmatch(cmd)\n\tif len(args) != 5 {\n\t\treturn nil, fmt.Errorf(\"%s:%d: syntax error for .code/.play invocation\", sourceFile, sourceLine)\n\t}\n\tcommand, flags, file, addr := args[1], args[2], args[3], strings.TrimSpace(args[4])\n\tplay := command == \"play\" && PlayEnabled\n\n\t// Read in code file and (optionally) match address.\n\tfilename := filepath.Join(filepath.Dir(sourceFile), file)\n\ttextBytes, err := ctx.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s:%d: %v\", sourceFile, sourceLine, err)\n\t}\n\tlo, hi, err := addrToByteRange(addr, 0, textBytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s:%d: %v\", sourceFile, sourceLine, err)\n\t}\n\tif lo > hi {\n\t\t// The search in addrToByteRange can wrap around so we might\n\t\t// end up with the range ending before its starting point\n\t\thi, lo = lo, hi\n\t}\n\n\t// Acme pattern matches can stop mid-line,\n\t// so run to end of line in both directions if not at line start/end.\n\tfor lo > 0 && textBytes[lo-1] != '\\n' {\n\t\tlo--\n\t}\n\tif hi > 0 {\n\t\tfor hi < len(textBytes) && textBytes[hi-1] != '\\n' {\n\t\t\thi++\n\t\t}\n\t}\n\n\tlines := codeLines(textBytes, lo, hi)\n\n\tdata := &codeTemplateData{\n\t\tLines: formatLines(lines, highlight),\n\t\tEdit: strings.Contains(flags, \"-edit\"),\n\t\tNumbers: strings.Contains(flags, \"-numbers\"),\n\t}\n\n\t// Include before and after in a hidden span for playground code.\n\tif play {\n\t\tdata.Prefix = textBytes[:lo]\n\t\tdata.Suffix = textBytes[hi:]\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := codeTemplate.Execute(&buf, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn Code{\n\t\tCmd: origCmd,\n\t\tText: template.HTML(buf.String()),\n\t\tPlay: play,\n\t\tEdit: data.Edit,\n\t\tFileName: filepath.Base(filename),\n\t\tExt: filepath.Ext(filename),\n\t\tRaw: rawCode(lines),\n\t}, nil\n}", "func (cpu *Mos6502) Disassemble(addressStart uint16, addressStop uint16) map[uint16]string {\n\taddress := addressStart\n\tassemblyLines := make(map[uint16]string)\n\tfor address < addressStop {\n\t\tlineAddress := address\n\n\t\topcode := cpu.bus.ReadByteOnly(address)\n\t\tinstruction := cpu.lookup[opcode]\n\t\taddress++\n\n\t\tvar instructionString string\n\t\tswitch instruction.addressMode {\n\t\tcase imp:\n\t\t\tinstructionString = impAssemblyString\n\t\tcase imm:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(immAssemblyFmt, value)\n\t\tcase zp0:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(zp0AssemblyFmt, value)\n\t\tcase zpx:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(zpxAssemblyFmt, value)\n\t\tcase zpy:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(zpyAssemblyFmt, value)\n\t\tcase izx:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(izxAssemblyFmt, value)\n\t\tcase izy:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(izyAssemblyFmt, value)\n\t\tcase abs:\n\t\t\tlowByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\thighByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tvalue := (uint16(highByte) << 8) | uint16(lowByte)\n\t\t\tinstructionString = fmt.Sprintf(absAssemblyFmt, value)\n\t\tcase abx:\n\t\t\tlowByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\thighByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tvalue := (uint16(highByte) << 8) | uint16(lowByte)\n\t\t\tinstructionString = fmt.Sprintf(abxAssemblyFmt, value)\n\t\tcase aby:\n\t\t\tlowByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\thighByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tvalue := (uint16(highByte) << 8) | uint16(lowByte)\n\t\t\tinstructionString = fmt.Sprintf(abyAssemblyFmt, value)\n\t\tcase ind:\n\t\t\tlowByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\thighByte := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tvalue := (uint16(highByte) << 8) | uint16(lowByte)\n\t\t\tinstructionString = fmt.Sprintf(indAssemblyFmt, value)\n\t\tcase rel:\n\t\t\tvalue := cpu.bus.ReadByteOnly(address)\n\t\t\taddress++\n\t\t\tinstructionString = fmt.Sprintf(relAssemblyFmt, value, address+uint16(value))\n\t\tdefault:\n\t\t\tinstructionString = \"ERROR\"\n\t\t}\n\n\t\tassemblyString := fmt.Sprintf(assemblyInstructionFmt, lineAddress, instruction.operation, instructionString)\n\t\tassemblyLines[lineAddress] = assemblyString\n\t}\n\n\treturn assemblyLines\n}", "func Cmd(args []string) {\n\tdb, err := bolt.Open(\"/tmp/test.db\", 0666, &bolt.Options{ReadOnly: true})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer db.Close()\n\tif len(args) == 0 {\n\t\tfmt.Println(\"Available architectures:\")\n\t}\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"arch\"))\n\t\tc := b.Cursor()\n\t\tfor k, _ := c.First(); k != nil; k, _ = c.Next() {\n\t\t\ta, err := machine.ReadArch(tx, k)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(args) > 0 {\n\t\t\t\tif a.Name == args[0] {\n\t\t\t\t\tprintArch(a, true)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprintArch(a, false)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func UnmarshalCommand(data []byte) (Command, error) {\n\tvar cmd Command\n\n\t// 2 unknown bytes preceding, ignoring right now\n\tslug := string(data[2:6])\n\tswitch slug {\n\tcase \"InCm\":\n\t\tcmd = new(cmds.IncmCmd)\n\tcase \"_ver\":\n\t\tcmd = new(cmds.VerCmd)\n\tcase \"_pin\":\n\t\tcmd = new(cmds.PinCmd)\n\tcase \"Warn\":\n\t\tcmd = new(cmds.WarnCmd)\n\tcase \"_top\":\n\t\tcmd = new(cmds.TopCmd)\n\tcase \"_MeC\":\n\t\tcmd = new(cmds.MecCmd)\n\tcase \"_mpl\":\n\t\tcmd = new(cmds.MplCmd)\n\tcase \"_MvC\":\n\t\tcmd = new(cmds.MvcCmd)\n\tcase \"_SSC\":\n\t\tcmd = new(cmds.SscCmd)\n\tcase \"_TlC\":\n\t\tcmd = new(cmds.TlcCmd)\n\tcase \"_MAC\":\n\t\tcmd = new(cmds.MacCmd)\n\tcase \"Powr\":\n\t\tcmd = new(cmds.PowrCmd)\n\tcase \"VidM\":\n\t\tcmd = new(cmds.VidmCmd)\n\tcase \"InPr\":\n\t\tcmd = new(cmds.InprCmd)\n\tcase \"PrgI\":\n\t\tcmd = new(cmds.PrgiCmd)\n\tcase \"PrvI\":\n\t\tcmd = new(cmds.PrviCmd)\n\tcase \"AuxS\":\n\t\tcmd = new(cmds.AuxsCmd)\n\tcase \"MPCE\":\n\t\tcmd = new(cmds.MpceCmd)\n\tcase \"MPfe\":\n\t\tcmd = new(cmds.MpfeCmd)\n\tcase \"TlIn\":\n\t\tcmd = make(cmds.TlinCmd)\n\tcase \"TlSr\":\n\t\tcmd = make(cmds.TlsrCmd)\n\tcase \"Time\":\n\t\tcmd = new(cmds.TimeCmd)\n\tdefault:\n\t\t// unknown command (yet)\n\t\tcmd = cmds.NewUnknownCommand(slug)\n\t}\n\n\treturn cmd, cmd.UnmarshalBinary(data[6:])\n}", "func addPKDCmd() {\n\tif interactive {\n\t\tDPKICmd := &ishell.Cmd{\n\t\t\tName: \"dpki\",\n\t\t\tHelp: \"decentralized public key infrastructure commands\",\n\t\t\tFunc: func(c *ishell.Context) {\n\t\t\t\tc.Println(c.Cmd.HelpText())\n\t\t\t},\n\t\t}\n\t\tshell.AddCmd(DPKICmd)\n\n\t\taddVerifierRegisterCmdByShell(DPKICmd)\n\t\taddVerifierUnRegisterCmdByShell(DPKICmd)\n\t\taddPublishCmdByShell(DPKICmd)\n\t\taddUnPublishCmdByShell(DPKICmd)\n\t\taddOraclePublishCmdByShell(DPKICmd)\n\t\taddDpkiRewardInfoCmdByShell(DPKICmd)\n\t\taddDpkiRewardCmdByShell(DPKICmd)\n\t\taddDpkiGetVerifierStateListCmdByShell(DPKICmd)\n\t\taddDpkiGetPublishInfoCmdByShell(DPKICmd)\n\t\taddVerifierHeartCmdByShell(DPKICmd)\n\t} else {\n\t\tvar DPKICmd = &cobra.Command{\n\t\t\tUse: \"dpki\",\n\t\t\tShort: \"decentralized public key infrastructure commands\",\n\t\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t},\n\t\t}\n\t\trootCmd.AddCommand(DPKICmd)\n\t}\n}", "func (isa *ISA) daInstruction(pc uint, ins uint) string {\n\tim := isa.lookup(ins)\n\tif im != nil {\n\t\treturn im.defn.da(im.name, pc, ins)\n\t}\n\treturn \"illegal\"\n}", "func (cm *Cmd) parseInternalCmd() {\n\n\targ := string(os.Args[1])\n\tcmd := strings.Trim(arg, InternalCmdPrefix)\n\n\tswitch cmd {\n\tcase InternalCmdHelp:\n\t\tcm.printHelpMessage()\n\t\tbreak\n\tcase InternalCmdEnv:\n\t\tfmt.Println(\"External plug-in path : \" + cm.plugHandle.dir)\n\t\tbreak\n\tcase InternalCmdList:\n\t\tcm.plugHandle.PrintList()\n\t\tbreak\n\tcase InternalCmdVer:\n\t\tfmt.Println(cxt.Version)\n\t\tbreak\n\tcase InternalDevice:\n\t\tcm.printDevice()\n\t\tbreak\n\t}\n\tos.Exit(1)\n}", "func handleShellcode(hexcode string) {\n\tsc, err := hex.DecodeString(hexcode)\n\n\tif err != nil {\n\t\tfmt.Println(\"Problem decoding hex\")\n\t} else {\n\t\tc2agent.InjectShellcode(sc)\n\t}\n}", "func (r *Routine) runCmd() (string, error) {\n\tcmd := exec.Command(\"amixer\", \"get\", r.control)\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(out), nil\n}", "func Execute() {\n\tif err := MICmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func DecodeCommand(cell []byte) OnionCommand {\n\tswitch cell[0] {\n\tcase byte(0):\n\t\treturn CREATE\n\tcase byte(1):\n\t\treturn CREATED\n\tcase byte(2):\n\t\treturn DESTROY\n\tcase byte(3):\n\t\treturn EXTEND\n\tcase byte(4):\n\t\treturn EXTENDED\n\tcase byte(5):\n\t\treturn TRUNCATE\n\tcase byte(6):\n\t\treturn TRUNCATED\n\tcase byte(7):\n\t\treturn BEGIN\n\tcase byte(8):\n\t\treturn CONNECTED\n\tcase byte(9):\n\t\treturn DATA\n\tcase byte(10):\n\t\treturn RESPONSE\n\tcase byte(11):\n\t\treturn END\n\tcase byte(12):\n\t\treturn TEARDOWN\n\tdefault:\n\t\treturn UNKNOWN\n\t}\n}", "func (i ios) Run(ctx context.Context, command string) (string, error) {\n\toutput, err := i.RunUntil(ctx, command, i.basePrompt())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput = strings.ReplaceAll(output, \"\\r\\n\", \"\\n\")\n\tlines := strings.Split(output, \"\\n\")\n\tresult := \"\"\n\n\tfor i := 1; i < len(lines)-1; i++ {\n\t\tresult += lines[i] + \"\\n\"\n\t}\n\n\treturn result, nil\n}", "func (isa *ISA) Disassemble(m *mem.Memory, adr uint) *Disassembly {\n\tvar da Disassembly\n\t// symbol\n\ts := m.SymbolByAddress(adr)\n\tif s != nil {\n\t\tda.Symbol = s.Name\n\t}\n\t// instruction\n\tins, _ := m.RdIns(adr)\n\tpcStr := m.AddrStr(adr)\n\tif ins&3 == 3 {\n\t\tda.Dump = fmt.Sprintf(\"%s: %08x\", pcStr, uint32(ins))\n\t\tda.Assembly = isa.daInstruction(adr, ins)\n\t\tda.Length = 4\n\t} else {\n\t\tda.Dump = fmt.Sprintf(\"%s: %04x \", pcStr, uint16(ins))\n\t\tda.Assembly = isa.daInstruction(adr, ins)\n\t\tda.Length = 2\n\t}\n\treturn &da\n}", "func Disassemble(m cpu.Memory, addr uint16) (line string, next uint16) {\n\topcode := m.LoadByte(addr)\n\tset := cpu.GetInstructionSet(cpu.CMOS)\n\tinst := set.Lookup(opcode)\n\n\tvar buf [2]byte\n\toperand := buf[:inst.Length-1]\n\tm.LoadBytes(addr+1, operand)\n\n\tif inst.Mode == cpu.REL {\n\t\t// Convert relative offset to absolute address.\n\t\toperand = buf[:]\n\t\tbraddr := int(addr) + int(inst.Length) + byteToInt(operand[0])\n\t\toperand[0] = byte(braddr)\n\t\toperand[1] = byte(braddr >> 8)\n\t}\n\tformat := \"%s \" + modeFormat[inst.Mode]\n\tline = fmt.Sprintf(format, inst.Name, hexString(operand))\n\tnext = addr + uint16(inst.Length)\n\treturn line, next\n}", "func processCmdline() map[string]interface{} {\n\targs, _ := docopt.ParseDoc(USAGE)\n\t//fmt.Println(args)\n\n\tdsn = args[\"<dsn>\"].(string)\n\tnumOfEntries, _ = strconv.Atoi(args[\"-n\"].(string))\n\tpauseForCache = args[\"--pause\"].(bool)\n\n\tverbose := args[\"--verbose\"].(bool)\n\tif verbose {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\treturn args\n}", "func Cmd(logger *zap.Logger, config *lib.Config, args []string) error {\n\n\treturn nil\n\t// var e error\n\n\t// if _, e = os.Stat(\"./dvc.toml\"); os.IsNotExist(e) {\n\n\t// \treader := bufio.NewReader(os.Stdin)\n\n\t// \t// https://tutorialedge.net/golang/reading-console-input-golang/\n\t// \t// BasePackage\n\t// \tfmt.Print(\"> Base Package:\")\n\t// \tbasePackage, _ := reader.ReadString('\\n')\n\t// \tbasePackage = strings.Replace(basePackage, \"\\n\", \"\", -1)\n\n\t// \tfmt.Print(\"> Base directory (leave blank for current):\")\n\t// \tbaseDir, _ := reader.ReadString('\\n')\n\t// \tbaseDir = strings.Replace(baseDir, \"\\n\", \"\", -1)\n\n\t// \t// Host\n\t// \tfmt.Print(\"> Database Host:\")\n\t// \thost, _ := reader.ReadString('\\n')\n\t// \thost = strings.Replace(host, \"\\n\", \"\", -1)\n\n\t// \t// databaseName\n\t// \tfmt.Print(\"> Database Name:\")\n\t// \tdatabaseName, _ := reader.ReadString('\\n')\n\t// \tdatabaseName = strings.Replace(databaseName, \"\\n\", \"\", -1)\n\n\t// \t// databaseUser\n\t// \tfmt.Print(\"> Database User:\")\n\t// \tdatabaseUser, _ := reader.ReadString('\\n')\n\t// \tdatabaseUser = strings.Replace(databaseUser, \"\\n\", \"\", -1)\n\n\t// \t// databasePass\n\t// \tfmt.Print(\"> Database Password:\")\n\t// \tdatabasePass, _ := reader.ReadString('\\n')\n\t// \tdatabasePass = strings.Replace(databasePass, \"\\n\", \"\", -1)\n\n\t// \tcontent := \"databaseType = \\\"mysql\\\"\\nbasePackage = \\\"\" + basePackage + \"\\\"\\n\\nenums = []\\n\\n\"\n\t// \tcontent += \"[connection]\\nhost = \\\"\" + host + \"\\\"\\ndatabaseName = \\\"\" + databaseName + \"\\\"\\nusername = \\\"\" + databaseUser + \"\\\"\\npassword = \\\"\" + databasePass + \"\\\"\\n\\n\"\n\n\t// \tpackages := []string{\n\t// \t\t\"repos\",\n\t// \t\t\"models\",\n\t// \t\t\"typescript\",\n\t// \t\t\"services\",\n\t// \t\t\"dal\",\n\t// \t\t\"definitions\",\n\t// \t}\n\n\t// \tcontent += \"[packages]\\n\"\n\t// \tfor _, p := range packages {\n\t// \t\tif p == \"typescript\" {\n\t// \t\t\tcontinue\n\t// \t\t}\n\n\t// \t\tcontent += fmt.Sprintf(\"%s = \\\"%s\\\"\\n\", p, path.Join(basePackage, p))\n\t// \t}\n\n\t// \t// content += \"[packages]\\ncache = \\\"myPackage/cache\\\"\\nmodels = \\\"myPackage/models\\\"\\nschema = \\\"myPackage/schema\\\"\\nrepos = \\\"myPackage/repos\\\"\\n\\n\"\n\n\t// \tcontent += \"[dirs]\\n\"\n\n\t// \tfor _, p := range packages {\n\n\t// \t\tif baseDir != \"\" {\n\t// \t\t\tcontent += fmt.Sprintf(\"%s = \\\"%s\\\"\\n\", p, path.Join(baseDir, p))\n\t// \t\t} else {\n\t// \t\t\tcontent += fmt.Sprintf(\"%s = \\\"%s\\\"\\n\", p, p)\n\t// \t\t}\n\t// \t}\n\n\t// \t// content += \"[dirs]\\nrepos = \\\"repos\\\"\\ncache = \\\"cache\\\"\\nmodels = \\\"models\\\"\\nschema = \\\"schema\\\"\\ntypescript = \\\"ts\\\"\"\n\n\t// \tioutil.WriteFile(\"./dvc.toml\", []byte(content), 0644)\n\n\t// } else {\n\t// \tfmt.Println(\"dvc.toml already exists in this directory\")\n\t// }\n}", "func (a *AGI) Command(cmd ...string) (resp *Response) {\n\tresp = &Response{}\n\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tcmdString := strings.Join(cmd, \" \") + \"\\n\"\n\t_, err := a.w.Write([]byte(cmdString))\n\tif err != nil {\n\t\tresp.Error = errors.Wrap(err, \"failed to send command\")\n\t\treturn\n\t}\n\n\ts := bufio.NewScanner(a.r)\n\tfor s.Scan() {\n\t\traw := s.Text()\n\t\tif raw == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\t// Parse and store the result code\n\t\tpieces := responseRegex.FindStringSubmatch(raw)\n\t\tif pieces == nil {\n\t\t\tresp.Error = fmt.Errorf(\"failed to parse result: %s\", raw)\n\t\t\treturn\n\t\t}\n\n\t\t// Status code is the first substring\n\t\tresp.Status, err = strconv.Atoi(pieces[1])\n\t\tif err != nil {\n\t\t\tresp.Error = errors.Wrap(err, \"failed to get status code\")\n\t\t\treturn\n\t\t}\n\n\t\t// Result code is the second substring\n\t\tresp.ResultString = pieces[2]\n\t\t// FIXME: DTMF result maybe has \"#\"(35), \"*\" or \"\"(GetData #). But not perfect to just judge by contains string.\n\t\tif resp.ResultString != \"\" && !strings.Contains(resp.ResultString, \"35\") && !strings.Contains(resp.ResultString, \"*\") {\n\t\t\tresp.Result, err = strconv.Atoi(pieces[2])\n\t\t\tif err != nil {\n\t\t\t\tresp.Error = errors.Wrap(err, \"failed to parse status code as an integer\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\n\t\t// Value is the third (and optional) substring\n\t\twrappedVal := strings.TrimSpace(pieces[3])\n\t\tresp.Value = strings.TrimSuffix(strings.TrimPrefix(wrappedVal, \"(\"), \")\")\n\n\t\t// FIXME: handle multiple line return values\n\t\tbreak // nolint\n\t}\n\n\t// If the Status code is not 200, return an error\n\tif resp.Status != 200 {\n\t\tresp.Error = fmt.Errorf(\"Non-200 status code\")\n\t}\n\treturn\n}", "func GetCommand(processNodePtr *nd.Node) {\n\tATA := &(*(*processNodePtr).ATAPtr)\n\tlogger := (*processNodePtr).Logger\n\tloggerByte := (*processNodePtr).LoggerByte\n\tloggerPerSec := (*processNodePtr).LoggerPerSec\n\tdestPortNum := (*processNodePtr).DestPortNum\n\tvmNumStr := (*processNodePtr).VmNumStr\n\tmyService := (*processNodePtr).MyService\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tbyteSent := 0\n\tfor {\n\t\tscanner.Scan()\n\t\tcommand := scanner.Text()\n\n\t\tif command == \"gossip\" {\n\t\t\tfmt.Println(\"Changing to Gossip\")\n\t\t\tloggerPerSec.Println(\"Changing to Gossip\")\n\t\t\tlogger.Println(\"Changing to Gossip\")\n\t\t\t*ATA = false\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"gossip\", destPortNum)\n\t\t\tloggerByte.Println(\"Command(Gossip) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"ata\" {\n\t\t\tfmt.Println(\"Changing to ATA\")\n\t\t\t*ATA = true\n\t\t\tbyteSent = PingMsg(*processNodePtr, (*processNodePtr).MsList, \"ata\", destPortNum)\n\t\t\tloggerPerSec.Println(\"Changing to ATA\")\n\t\t\tlogger.Println(\"Changing to ATA\")\n\n\t\t\tloggerByte.Println(\"Command(ATA) Ping ByteSent:\" + strconv.Itoa(byteSent) + \"bytes\")\n\n\t\t} else if command == \"leave\" {\n\t\t\tfmt.Println(\"(Leave)Terminating vm_\", vmNumStr)\n\t\t\tloggerPerSec.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tlogger.Println(\"(Leave)Terminating vm_\" + vmNumStr)\n\t\t\tos.Exit(1)\n\t\t} else if command == \"memberlist\" {\n\t\t\tfmt.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tloggerPerSec.Println(\"\\nMembership List: \\n\" + (*processNodePtr).MsList.PrintLog())\n\t\t\tlogger.Println(\"\\nMembership List: \\n\" + (*processNodePtr).PrintLog())\n\t\t} else if command == \"id\" {\n\t\t\tfmt.Println(\"Current IP and port:\", myService)\n\t\t\tloggerPerSec.Println(\"\\nCurrent IP and port: \" + myService + \"\\n\")\n\t\t\tlogger.Println(\"\\nCurrent IP and port:: \" + myService + \"\\n\")\n\t\t} else if command == \"-h\" {\n\t\t\tfmt.Println(\"gossip\t\t\t\t:\tchange the system into a gossip heartbeating\")\n\t\t\tfmt.Println(\"ata\t\t\t\t:\tchange the system into a All-to-All heartbeating\")\n\t\t\tfmt.Println(\"leave\t\t\t\t: \tvoluntarily leave the system. (halt)\")\n\t\t\tfmt.Println(\"memberlist\t\t\t: \tprint VM's memberlist to the terminal\")\n\t\t\tfmt.Println(\"id\t\t\t\t\t:\tprint current IP address and assigned Port number\")\n\t\t\tfmt.Println(\"heartbeat\t\t\t:\tprint the current heartbeat type\")\n\t\t\tfmt.Println(\"put <filename>\t\t: put a <filename> to the distributed system\")\n\t\t\tfmt.Println(\"pull <filename>\t: pull a <filename> from the distributed system and store in the the local folder\")\n\t\t\tfmt.Println(\"ls -l\t\t\t\t:\tprint the list of distributed files and its size in the current process\")\n\t\t\tfmt.Println(\"ls \t\t\t\t:\tprint the list of sdfsfile's in the system\")\n\t\t\tfmt.Println(\"ls <filename>\t\t:\tprint the list of IDs having a file <filename>\")\n\t\t\tfmt.Println(\"store\t\t\t\t:\tprint the list of distributed's in the process\")\n\t\t\tfmt.Println(\"remove <filename>\t:\tremove the <filename> from the system\")\n\t\t} else if command == \"heartbeat\" {\n\t\t\tif *ATA == true {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: ATA\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Current Heartbeating for this processor: Gossip\")\n\t\t\t}\n\t\t} else if len(command) > 3 && command[:3] == \"put\" {\n\t\t\tfilename := command[4:]\n\t\t\tfs.Put(processNodePtr, filename, 1)\n\n\t\t} else if len(command) > 4 && command[:4] == \"pull\" {\n\t\t\tfilename := command[5:]\n\t\t\tfs.Pull(processNodePtr, filename, 1)\n\n\t\t} else if command == \"ls -l\" { // list file names and its size of the files stored in the distributed folder\n\t\t\tfiles, err := ioutil.ReadDir(processNodePtr.DistributedPath)\n\t\t\tCheckError(err)\n\n\t\t\tfor i, file := range files {\n\t\t\t\tfmt.Println(strconv.Itoa(i)+\". \"+file.Name()+\":\", file.Size(), \"bytes\")\n\t\t\t}\n\t\t} else if command[0:2] == \"ls\" {\n\t\t\tFilenames := fs.GetFileList(processNodePtr)\n\n\t\t\tif len(command) > 2 { // list all machine (VM) addresses where this file is currently being stored\n\t\t\t\tfilename := command[3:]\n\n\t\t\t\t_, exist := Filenames[filename]\n\n\t\t\t\tif !exist {\n\t\t\t\t\tfmt.Println(\"no such file exist in DFS\")\n\t\t\t\t} else {\n\t\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\t\tif filename == file {\n\t\t\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\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} else { // list all file info\n\t\t\t\tfor file, IPAddressList := range Filenames {\n\t\t\t\t\tfmt.Println(\"File \", file, \"is stored in the following Addresses:\")\n\t\t\t\t\tfor i, ID := range IPAddressList {\n\t\t\t\t\t\tfmt.Println(\"\t\", i, \":\", ID.IPAddress)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if command == \"store\" { //list all files currently being stored at this machine\n\t\t\tfmt.Println(\"Files currently stored at this machine:\")\n\t\t\tfor _, file := range *processNodePtr.DistributedFilesPtr {\n\t\t\t\tfmt.Println(file)\n\t\t\t}\n\n\t\t} else if len(command) > 6 && command[:6] == \"remove\" { // remove the file\n\t\t\tfilename := command[7:]\n\t\t\tfs.RemoveFile(processNodePtr, filename)\n\n\t\t} else {\n\t\t\tfmt.Println(\"Invalid Command\")\n\t\t}\n\t}\n}", "func main() {\n\tfmt.Println(getCommandsFromFile(\"resources/not_enough_lines\"))\n\tfmt.Println(getCommandsFromFile(\"resources/version_not_a_number\"))\n\tfmt.Println(getCommandsFromFile(\"resources/invalid_json\"))\n\tfmt.Println(getCommandsFromFile(\"resources/incorrect_version\"))\n\tfmt.Println(getCommandsFromFile(\"resources/incorrect_mode\"))\n\tfmt.Println(getCommandsFromFile(\"resources/valid\"))\n}", "func Command(commandtext string) (CommandDetails, error) {\n\n\tvar parsedCommand CommandDetails\n\n\tparsedCommand.Original = commandtext\n\n\t// Let's tokenise this using the delimiters, that'll make this parsing easier.\n\t// super fragile parsing up ahead!\n\toverlaySlice := strings.Split(commandtext, \"|\")\n\n\tif len(overlaySlice) > 1 {\n\t\tparsedCommand.OverlayText = strings.Join(overlaySlice[1:], \"\\n\")\n\t\tcommandtext = overlaySlice[0]\n\t}\n\n\tgifSlice := strings.Split(commandtext, \"/\")\n\n\tif len(gifSlice) > 1 {\n\t\tgifDetails := strings.Split(strings.TrimSpace(gifSlice[1]), \" \")\n\t\tif len(gifDetails) > 1 {\n\t\t\tparsedCommand.GifOffset = gifDetails[1]\n\n\t\t}\n\t\tparsedCommand.GifLength = gifDetails[0]\n\t\tcommandtext = gifSlice[0]\n\t}\n\n\tparsedCommand.Quote = commandtext\n\n\tif !strings.Contains(parsedCommand.GifLength, \"s\") {\n\t\tparsedCommand.GifLength += \"s\"\n\t}\n\n\tif !strings.Contains(parsedCommand.GifOffset, \"s\") {\n\t\tparsedCommand.GifOffset += \"s\"\n\t}\n\n\t// fmt.Printf(\"%+v\", result)\n\n\treturn parsedCommand, nil\n}", "func (l *Libvirt) Run(dom string, cmd []byte) ([]byte, error) {\n\td, err := l.lookup(dom)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpayload := struct {\n\t\tDomain Domain\n\t\tCommand []byte\n\t\tFlags uint32\n\t}{\n\t\tDomain: d,\n\t\tCommand: cmd,\n\t\tFlags: 0,\n\t}\n\n\tbuf, err := encode(&payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := l.request(constants.QEMUDomainMonitor, constants.ProgramQEMU, &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := <-resp\n\t// check for libvirt errors\n\tif res.Status != StatusOK {\n\t\treturn nil, decodeError(res.Payload)\n\t}\n\n\t// check for QEMU process errors\n\tif err = getQEMUError(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := bytes.NewReader(res.Payload)\n\tdec := xdr.NewDecoder(r)\n\tdata, _, err := dec.DecodeFixedOpaque(int32(r.Len()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// drop QMP control characters from start of line, and drop\n\t// any trailing NULL characters from the end\n\treturn bytes.TrimRight(data[4:], \"\\x00\"), nil\n}", "func parseCommand(commandMap stringmap.StringMap, registry *feature.Registry, m *discordgo.MessageCreate) (*model.Command, error) {\n\tcontent := m.Content\n\tif !strings.HasPrefix(content, \"?\") {\n\t\treturn &model.Command{\n\t\t\tType: model.CommandTypeNone,\n\t\t}, nil\n\t}\n\tsplitContent := strings.Split(content, \" \")\n\n\t// Parse builtins.\n\tif parser := registry.GetParserByName(splitContent[0]); parser != nil {\n\t\tcommand, err := parser.Parse(splitContent, m)\n\t\tcommand.OriginalName = splitContent[0]\n\t\treturn command, err\n\t}\n\n\t// See if it's a custom command.\n\thas, err := commandMap.Has(splitContent[0][1:])\n\tif err != nil {\n\t\tlog.Info(\"Error doing custom parsing\", err)\n\t\treturn nil, err\n\t}\n\tif has {\n\t\treturn registry.FallbackParser.Parse(splitContent, m)\n\t}\n\n\t// No such command!\n\treturn &model.Command{\n\t\tType: model.CommandTypeUnrecognized,\n\t}, nil\n}", "func NewDisassembler(arch bin.Arch) (Disassembler, error) {\n\tfor _, format := range formats {\n\t\tif format.arch == arch {\n\t\t\treturn &format, nil\n\t\t}\n\t}\n\treturn nil, errors.Errorf(\"unknown machine architecture format %v;\\n\\ttip: remember to register a disassembler (e.g. import _ \\\".../disasm/x86\\\")\", arch)\n}", "func (s *Spike) runCmd(cmd string) (err error) {\n\tdefer func() {\n\t\tif err != nil && !IsExit(err) && !IsECall(err) && !IsTrap(err) {\n\t\t\terr = fmt.Errorf(\"can't run cmd %q: %v\", cmd, err)\n\t\t}\n\t}()\n\n\tgot, err := s.sendCmd(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Read PC\n\tif m := pcRe.FindStringSubmatch(got); len(m) == 3 {\n\t\tif s.PC, err = strconv.ParseUint(m[1], 0, 64); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.Instr = m[2]\n\t}\n\tvar trap bool\n\tif m := trapRe.FindStringSubmatch(got); len(m) == 2 {\n\t\ttrap = true\n\t\tif s.PC, err = strconv.ParseUint(m[1], 0, 64); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tecall := strings.Contains(got, \"trap_user_ecall\")\n\n\t// Read regs\n\tgot, err = s.sendCmd(\"reg 0\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read register state: %v\", err)\n\t}\n\tfs := strings.FieldsFunc(got, func(r rune) bool {\n\t\treturn r == '\\n' || r == ' ' || r == ':'\n\t})\n\tif len(fs)%2 == 1 {\n\t\treturn fmt.Errorf(\"got odd number of results for reg-value: %q\", got)\n\t}\n\tfor i := 0; i < len(fs); i += 2 {\n\t\tv, err := strconv.ParseUint(fs[i+1], 0, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"can't parse regs value: %v in %q\", err, got)\n\t\t}\n\t\tn, ok := regNums[fs[i]]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unrecognized reg %q in %q\", fs[i], got)\n\t\t}\n\t\ts.Reg[n] = v\n\t}\n\n\tif ecall {\n\t\tif s.Reg[regNums[\"a7\"]] == 0x5d { // SYS_exit\n\t\t\treturn exitErr\n\t\t}\n\t\treturn ecallErr\n\t}\n\tif trap {\n\t\treturn trapErr\n\t}\n\treturn nil\n}", "func main() {\n\tapp := &CLIApp{GetOutboundIP().String(), 10002}\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Printf(\"Welcome to kademlia network!\\nAvailable commands:\\nput <string> (stores data on k closest nodes to hash)\t\\nget <hash> (fetches data object with this hash if it is stored in the network)\t\\nexit (terminates this node)\\n\")\n\n\tfor {\n\t\tfmt.Printf(\"\\nEnter command: \")\n\t\ttext, _ := reader.ReadString('\\n') //read from terminal\n\t\ttext = strings.TrimRight(text, \"\\n\")\n\n\t\tsplitStr := strings.SplitN(text, \" \", 2) //Split string at first space\n\n\t\terr := app.parser(splitStr)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t}\n\t}\n}", "func Run(filepath string) (int, error) {\n\n\tf := common.OpenFile(filepath)\n\tdefer common.CloseFile(f)\n\n\ts := bufio.NewScanner(f)\n\ts.Scan()\n\n\tparts := strings.Split(s.Text(), \",\")\n\terr := s.Err()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tseq := make([]int, 0)\n\tfor _, elt := range parts {\n\t\tcode, err := strconv.Atoi(elt)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tseq = append(seq, code)\n\t}\n\n\t// create a program instance to get the map and compute commands from it\n\tcreateProgram := intcode.ProgramCreator(seq)\n\tp := createProgram()\n\tout := make(chan int)\n\tquit := make(chan int)\n\tgo p.Run(nil, out, quit)\n\n\tspacemap := SpaceMap{}\n\tspacemap.PopulateFrom(out)\n\t<-quit\n\n\t// prepare functions A B C\n\tcds := spacemap.robotCommands()\n\tfmt.Printf(\"Commands(%v):\\n %v\\n\", len(cds.String()), cds)\n\tres := splitCommands(cds)\n\tfmt.Printf(\"Splitted:\\nA:%v\\nB:%v\\nC:%v\\nRoutine:%v\\n\", res.A, res.B, res.C, res.mainRoutine)\n\n\t// now create the real instance to send\n\tmanual := createProgram()\n\t// override movement logic\n\tmanual.SetMemory(0, 2)\n\n\tin2 := make(chan int)\n\tout2 := make(chan int)\n\tquit2 := make(chan int)\n\tgo manual.Run(in2, out2, quit2)\n\n\t// stack commands to send to the program\n\tgo send([]string{\n\t\t// Main:\n\t\tstrings.Join(res.mainRoutine, \",\"),\n\t\t// Function A:\n\t\tres.A.String(),\n\t\t// Function B:\n\t\tres.B.String(),\n\t\t// Function C:\n\t\tres.C.String(),\n\t\t// Continuous video feed?\n\t\t\"n\",\n\t}, in2)\n\n\t// output everything the program send to us\n\tgo output(out2)\n\t// make the main goroutine wait for termination of second program to stop\n\t<-quit2\n\n\treturn 0, nil\n}", "func processCommand(command string) error {\n\tcommandDelimited := strings.Split(command, \" \")\n\tlengthOfCommand := len(commandDelimited)\n\n\tvar err error\n\targuments := []string{}\n\tif lengthOfCommand < 1 {\n\t\terr := errors.New(UNSUPPORTED_COMMAND)\n\t\tfmt.Println(err.Error())\n\t\treturn err\n\t} else if lengthOfCommand == 1 {\n\t\tcommand = commandDelimited[0]\n\t} else {\n\t\tcommand = commandDelimited[0]\n\t\targuments = commandDelimited[1:]\n\t}\n\n\t// check if command is one of the allowed commands\n\tif numberOfArguments, exists := allowedCommands[command]; exists {\n\n\t\tif len(arguments) != numberOfArguments && numberOfArguments != 99 {\n\t\t\tfmt.Println(argumentsErrors[command].Error())\n\t\t\treturn argumentsErrors[command]\n\t\t}\n\n\t\tw := &ErrWrapper{}\n\n\n\t\t// after validation of number of arguments per command, perform the necessary command\n\t\tswitch command {\n\t\tcase \"login\":\n\t\t\tw.do(func() error {\n\t\t\t\tvar err error\n\t\t\t\tsessionId, err = user.Login(user.User{\n\t\t\t\t\tId: arguments[0],\n\t\t\t\t\tPassword: arguments[1],\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Println(\"Login Successfully\")\n\t\t\t\treturn nil\n\t\t\t})\n\t\tcase \"signup\":\n\t\t\treturn w.do(func () error {\n\t\t\t\terr := user.SignUp(user.UserSignUP{\n\t\t\t\t\tName: arguments[0],\n\t\t\t\t\tPassword: arguments[2],\n\t\t\t\t\tEmail: arguments[1],\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Println(\"Signup successfully\")\n\t\t\t\treturn nil\n\t\t\t})\t\t\n\t\tcase \"listjournal\":\n\t\t\treturn w.do(func() error {\n\t\t\t\tif jr == nil {\n\t\t\t\t\tif sessionId != nil {\n\t\t\t\t\t\tjr, err = journal.GetInstace(*(sessionId))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn argumentsErrors[\"loginfirst\"]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tenteries, err := jr.ListEntries()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor index, eachEntry := range enteries {\n\t\t\t\t\tfmt.Printf(\"%d %s %s \\n\", index, eachEntry.Time, eachEntry.ToRemeber)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\tcase \"createjournal\":\n\t\t\treturn w.do(func() error {\n\t\t\t\tif jr == nil {\n\t\t\t\t\tif sessionId != nil {\n\t\t\t\t\t\tjr, err = journal.GetInstace(*(sessionId))\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn argumentsErrors[\"loginfirst\"]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar input string\n\t\t\t\tfor _, eachData := range arguments {\n\t\t\t\t\tinput = input + \" \" + eachData\n\t\t\t\t}\n\t\t\t\terr = jr.InputEntry(input)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\tcase \"removeuser\":\n\t\t\treturn w.do(func ()error{\n\t\t\t\treturn user.RemoveUser(arguments[0])\n\t\t\t})\n\t\t}\n\t} else {\n\t\terr := errors.New(UNSUPPORTED_COMMAND)\n\t\tfmt.Println(err.Error())\n\n\t\treturn err\n\t}\n\treturn errors.New(\"Not Reachable Code\")\n}", "func runAnalyse(cmd *cobra.Command, args []string) {\n\tif !viper.IsSet(\"crda_key\") {\n\t\tfmt.Fprintln(os.Stdout,\n\t\t\tcolor.RedString(\"\\u2718 \"),\n\t\t\t\"Please run `crda auth` command first.\",\n\t\t)\n\t\tos.Exit(1)\n\t}\n\tmanifestPath := getAbsPath(args[0])\n\trequestParams := driver.RequestType{\n\t\tUserID: viper.GetString(\"crda_key\"),\n\t\tThreeScaleToken: viper.GetString(\"auth_token\"),\n\t\tHost: viper.GetString(\"host\"),\n\t\tRawManifestFile: manifestPath,\n\t}\n\tif !jsonOut {\n\t\tfmt.Fprintln(os.Stdout, \"Analysing your Dependency Stack! Please wait...\")\n\t}\n\thasVul := sa.StackAnalyses(requestParams, jsonOut, verboseOut)\n\tif hasVul {\n\t\t// Stack has vulnerability, exit with 2 code\n\t\tos.Exit(2)\n\t}\n}", "func (dbg *Debug) dmiOps(ops []dmiOp) ([]uint32, error) {\n\tdata := []uint32{}\n\n\t// select dmi\n\terr := dbg.wrIR(irDmi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tread := false\n\tfor i := 0; i < len(ops); i++ {\n\t\top := ops[i]\n\t\t// run the operation\n\t\ttdo, err := dbg.dev.RdWrDR(bitstr.FromUint(uint(op), dbg.drDmiLength), dbg.idle)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tx := tdo.Split([]int{dbg.drDmiLength})[0]\n\t\t// check the result\n\t\tresult := x & opMask\n\t\tif result != opOk {\n\t\t\t// clear error condition\n\t\t\tdbg.wrDtmcs(dmireset)\n\t\t\t// re-select dmi\n\t\t\tdbg.wrIR(irDmi)\n\t\t\tif result == opBusy {\n\t\t\t\t// auto-adjust timing\n\t\t\t\tlog.Info.Printf(\"increment idle timing %d->%d cycles\", dbg.idle, dbg.idle+1)\n\t\t\t\tdbg.idle++\n\t\t\t\tif dbg.idle > jtag.MaxIdle {\n\t\t\t\t\treturn nil, fmt.Errorf(\"dmi operation error %d\", result)\n\t\t\t\t}\n\t\t\t\t// redo the operation\n\t\t\t\ti--\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"dmi operation error %d\", result)\n\t\t\t}\n\t\t}\n\t\t// get the read data\n\t\tif read {\n\t\t\tdata = append(data, uint32((x>>2)&util.Mask32))\n\t\t}\n\t\t// setup the next read\n\t\tread = op.isRead()\n\t}\n\treturn data, nil\n}", "func (o *RootOptions) RunDiagnose(cmd *cobra.Command) (err error) {\n\tif !o.Doctor {\n\t\treturn\n\t}\n\tpath := getCmdPath(cmd)\n\tlogger.Debug(\"start to run diagnose\", zap.String(\"path\", path))\n\n\tfor k, v := range healthCheckRegister.Member {\n\t\tif ok, _ := regexp.MatchString(k, path); ok {\n\t\t\terr = v.Check()\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn\n}", "func processCommand(data []string) int {\n\n\tdataType := strings.ToLower(data[0])\n\tswitch dataType {\n\tcase createAParkingLot:\n\t\tnumberOfParkingLots, _ := strconv.Atoi(data[1])\n\t\tcreateParkingLot(numberOfParkingLots)\n\tcase parkVehicle:\n\t\tparkingSlots = parkAVehicle(parkingSlots, data[1:], totalNumberOfParkingLots)\n\tcase freeSlot:\n\t\tslotNumber, _ := strconv.Atoi(data[1])\n\t\tfreeAParkingSlot(parkingSlots, totalNumberOfParkingLots, slotNumber)\n\tcase statusOfParkingSlots:\n\t\tlistAllSlotDetails(parkingSlots)\n\tcase regNumbersWithColor:\n\t\tfindRegOrSlotByColor(parkingSlots, data[1], true)\n\tcase slotNumbersWithColor:\n\t\tfindRegOrSlotByColor(parkingSlots, data[1], false)\n\tcase slotNumberWithReg:\n\t\tfindSlotNumberByRegNum(parkingSlots, data[1])\n\tdefault:\n\t\tfmt.Println(\"Not a valid command\")\n\t\treturn -1\n\t}\n\n\treturn 1\n}", "func ExecuteDevfileDebugAction(client ExecClient, exec common.Exec, commandName string, compInfo adaptersCommon.ComponentInfo, show bool, machineEventLogger machineoutput.MachineEventLoggingClient) error {\n\tvar s *log.Status\n\n\t// Exec the supervisord ctl stop and start for the debugRun program\n\ttype debugRunExecutable struct {\n\t\tcommand []string\n\t}\n\tdebugRunExecs := []debugRunExecutable{\n\t\t{\n\t\t\tcommand: []string{adaptersCommon.SupervisordBinaryPath, adaptersCommon.SupervisordCtlSubCommand, \"stop\", \"all\"},\n\t\t},\n\t\t{\n\t\t\tcommand: []string{adaptersCommon.SupervisordBinaryPath, adaptersCommon.SupervisordCtlSubCommand, \"start\", string(adaptersCommon.DefaultDevfileDebugCommand)},\n\t\t},\n\t}\n\n\ts = log.Spinnerf(\"Executing %s command %q\", commandName, exec.CommandLine)\n\tdefer s.End(false)\n\n\tfor _, debugRunExec := range debugRunExecs {\n\n\t\t// Emit DevFileCommandExecutionBegin JSON event (if machine output logging is enabled)\n\t\tmachineEventLogger.DevFileCommandExecutionBegin(exec.Id, exec.Component, exec.CommandLine, convertGroupKindToString(exec), machineoutput.TimestampNow())\n\n\t\t// Capture container text and log to the screen as JSON events (machine output only)\n\t\tstdoutWriter, stdoutChannel, stderrWriter, stderrChannel := machineEventLogger.CreateContainerOutputWriter()\n\n\t\terr := ExecuteCommand(client, compInfo, debugRunExec.command, show, stdoutWriter, stderrWriter)\n\n\t\t// Close the writers and wait for an acknowledgement that the reader loop has exited (to ensure we get ALL container output)\n\t\tcloseWriterAndWaitForAck(stdoutWriter, stdoutChannel, stderrWriter, stderrChannel)\n\n\t\t// Emit close event\n\t\tmachineEventLogger.DevFileCommandExecutionComplete(exec.Id, exec.Component, exec.CommandLine, convertGroupKindToString(exec), machineoutput.TimestampNow(), err)\n\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"unable to execute the run command\")\n\t\t}\n\t}\n\n\ts.End(true)\n\n\treturn nil\n}", "func parseModCommand(dpack DataPackage) {\n\tdebug(\"Parsing inbound mod command: \" + dpack.Message)\n}", "func main() {\n\n\tvar dwarfData\t\t\t*dwarf.Data;\n\tvar theFile\t\t\t\t*macho.File;\n\tvar theErr\t\t\t\tos.Error;\n\tvar relativeAddress\t\tuint64;\n\tvar runtimeAddress\t\tuint64;\n\tvar loadAddress\t\t\tuint64;\n\tvar segmentAddress\t\tuint64;\n\tvar pathMacho\t\t\tstring;\n\tvar pathDsym\t\t\tstring;\n\n\n\n\t// Parse our arguments\n\tflag.Uint64Var(&runtimeAddress, \"raddr\", 0, \"\");\n\tflag.Uint64Var(&loadAddress, \"laddr\", 0, \"\");\n\tflag.StringVar(&pathMacho, \"macho\", \"\", \"\");\n\tflag.StringVar(&pathDsym, \"dsym\", \"\", \"\");\n\tflag.Parse();\n\n\tif (runtimeAddress == 0 || loadAddress == 0 || pathMacho == \"\" || pathDsym == \"\") {\n\t\tprintHelp();\n\t}\n\n\n\n\t// Find the text segment address\n\ttheFile, theErr = macho.Open(pathMacho);\n\tif (theErr != nil) {\n\t\tfatalError(\"Can't open Mach-O file: \" + theErr.String());\n\t}\n\n\tsegmentAddress = theFile.Segment(\"__TEXT\").Addr;\n\n\ttheFile.Close();\n\n\n\n\t// Calculate the target address\n\trelativeAddress = runtimeAddress - loadAddress;\n\tgTargetAddress = segmentAddress + relativeAddress;\n\n\n\n\t// Find the target\n\ttheFile, theErr = macho.Open(pathDsym);\n\tif (theErr != nil) {\n\t\tfatalError(\"Can't open .dsym file: \" + theErr.String());\n\t}\n\n\tdwarfData, theErr = theFile.DWARF();\n\tif (theErr != nil) {\n\t\tfatalError(\"Can't find DWARF info: \" + theErr.String());\n\t}\n\n\tprocessChildren(dwarfData.Reader(), 0, false);\n\n\ttheFile.Close();\n}", "func doAnalyzeCmd(cmd *cobra.Command, args []string) {\n\tdefer utils.Cleanup()\n\tif len(args) == 0 {\n\t\tprintVersionFlag, err := cmd.PersistentFlags().GetBool(\"version\")\n\t\tif err == nil && printVersionFlag {\n\t\t\tprintVersion(cmd, args)\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Println(\"No image argument given\")\n\t\tcmd.Help()\n\t\tutils.Exit(1)\n\t}\n\n\tuserImage := args[0]\n\tif userImage == \"\" {\n\t\tfmt.Println(\"No image argument given\")\n\t\tcmd.Help()\n\t\tutils.Exit(1)\n\t}\n\n\trun(userImage)\n}", "func disassemble(f *Funcode) string {\n\tout := new(bytes.Buffer)\n\tcode := f.Code\n\tfor pc := 0; pc < len(code); {\n\t\top := Opcode(code[pc])\n\t\tpc++\n\t\t// TODO(adonovan): factor in common with interpreter.\n\t\tvar arg uint32\n\t\tif op >= OpcodeArgMin {\n\t\t\tfor s := uint(0); ; s += 7 {\n\t\t\t\tb := code[pc]\n\t\t\t\tpc++\n\t\t\t\targ |= uint32(b&0x7f) << s\n\t\t\t\tif b < 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif out.Len() > 0 {\n\t\t\tout.WriteString(\"; \")\n\t\t}\n\t\tfmt.Fprintf(out, \"%s\", op)\n\t\tif op >= OpcodeArgMin {\n\t\t\tswitch op {\n\t\t\tcase CONSTANT:\n\t\t\t\tswitch x := f.Prog.Constants[arg].(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tfmt.Fprintf(out, \" %q\", x)\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Fprintf(out, \" %v\", x)\n\t\t\t\t}\n\t\t\tcase LOCAL:\n\t\t\t\tfmt.Fprintf(out, \" %s\", f.Locals[arg].Name)\n\t\t\tcase PREDECLARED:\n\t\t\t\tfmt.Fprintf(out, \" %s\", f.Prog.Names[arg])\n\t\t\tdefault:\n\t\t\t\tfmt.Fprintf(out, \"<%d>\", arg)\n\t\t\t}\n\t\t}\n\t}\n\treturn out.String()\n}", "func ParseCmd(l []byte, lenght int) (string, int) {\n\tline := string(l[:lenght])\n\tline = strings.ToLower(line)\n\tline = strings.TrimSpace(line)\n\tcmds := strings.Split(line, \" \")\n\n\tfmt.Println(cmds)\n\n\tif len(cmds) == 0 {\n\t\tfmt.Println(\"Qui0...\" + cmds[0])\n\t\treturn StrInvalidCommand, InvalidCommand\n\t}\n\n\tcommand, ok := Table[strings.TrimSpace(cmds[0])]\n\tif !ok {\n\t\tfmt.Println(\"Qui...\" + cmds[0])\n\t\treturn StrCommandNotFound, CommandNotFound\n\t}\n\n\treturn command(cmds[1:])\n}", "func DaemonizedCommands() map[string]Executor {\n return available.daemonized\n}", "func Execute(dd Directive, buffer *bytes.Buffer) error {\n\tdc := &DecodeContext{}\n\treturn dd.Execute(buffer, dc)\n}", "func cmdInfo() {\n\tif err := vbm(\"showvminfo\", B2D.VM); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func parseAdminCommand(dpack DataPackage) {\n\tdebug(\"Parsing inbound admin command: \" + dpack.Message)\n\tif strings.HasPrefix(dpack.Message, \"list\") {\n\t\tdebug(\"Getting available commands\")\n\t\treq := strings.TrimPrefix(dpack.Message, \"list \")\n\t\tresponse = \"This is the list of current \" + req + \": \" + getCommandsString()\n\t\tif req == \"commands\" {\n\t\t\tdpack.Response = \"This is the list of current \" + req + \": \" + getCommandsString()\n\t\t\tsendResponse(dpack)\n\t\t\treturn\n\t\t} else if req == \"keywords\" {\n\t\t\tdpack.Response = \"This is the list of current \" + req + \": \" + getKeywordsString()\n\t\t\tsendResponse(dpack)\n\t\t\treturn\n\t\t} else {\n\t\t\tdpack.Response = \"There was no match for \" + req + \" options\"\n\t\t\tsendResponse(dpack)\n\t\t\treturn\n\t\t}\n\t}\n}", "func main() {\n\n\tif len(os.Args) != 2 {\n\t\tfmt.Println(\"Wrong params. Usage\")\n\t\t// Show list of snippets suitable for coping in command ba\n\t\tvar cmds bytes.Buffer\n\t\tfor k, _ := range Snippets {\n\t\t\tcmds.WriteString(fmt.Sprintf(\"'sn %s', \", k))\n\t\t}\n\t\tfmt.Println(cmds.String())\n\t\tos.Exit(2)\n\t}\n\tvar snippet string\n\tcommand := os.Args[1]\n\tif val, ok := Snippets[command]; ok == false {\n\t\tfmt.Println(\"Snippet not found\")\n\t\tos.Exit(1)\n\t} else {\n\t\tsnippet = val\n\t}\n\n\tid, _ := strconv.Atoi(os.Getenv(\"winid\"))\n\twfile, err := acme.Open(id, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Frist read is buggeous\n\t_, _, _ = wfile.ReadAddr()\n\n\terr = wfile.Ctl(\"addr=dot\\n\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Read current cursor position\n\tq0, q1, _ := wfile.ReadAddr()\n\n\tvar a, b int\n\n\t// get user selection\n\tvar selection string\n\tif q0 == q1 {\n\t\tselection = \"\"\n\t} else {\n\t\t\n\t\tdata, err := wfile.ReadAll(\"body\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ta = q0\t\n\t\t// to locate second byte offset must check for\n\t\t// runes inside string\n\t\tb = runeOffset2ByteOffset(data, q1)\n\t\ta = runeOffset2ByteOffset(data, q0)\n\t\t\n\t\tselection = string(data[a:b])\n\t\t\n\t\t// restore address after read.\n\t\terr = wfile.Addr(\"#%d,#%d\", q0, q1)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tresult := fmt.Sprintf(snippet, selection)\n\t_, err = wfile.Write(\"data\", []byte(result))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Try to put cursor on middle snippet\n\t// if empty selection\n\tif selection == \"\" {\n\t\tc := q0 + len(result)/2\n\t\terr = wfile.Addr(\"#%d,#%d\", c, c)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_ = wfile.Ctl(\"dot=addr\\n\")\n\n\t}\n\n}", "func extractCommand(body []byte) (cmd Command, args string) {\n\tcmdPos := bytes.Index(append([]byte{'\\n'}, body...), []byte(\"\\n\"+commandPrefix))\n\tif cmdPos == -1 {\n\t\tcmd = CmdNone\n\t\treturn\n\t}\n\tcmdPos += len(commandPrefix)\n\tfor cmdPos < len(body) && body[cmdPos] == ' ' {\n\t\tcmdPos++\n\t}\n\tcmdEnd := bytes.IndexByte(body[cmdPos:], '\\n')\n\tif cmdEnd == -1 {\n\t\tcmdEnd = len(body) - cmdPos\n\t}\n\tif cmdEnd1 := bytes.IndexByte(body[cmdPos:], '\\r'); cmdEnd1 != -1 && cmdEnd1 < cmdEnd {\n\t\tcmdEnd = cmdEnd1\n\t}\n\tif cmdEnd1 := bytes.IndexByte(body[cmdPos:], ' '); cmdEnd1 != -1 && cmdEnd1 < cmdEnd {\n\t\tcmdEnd = cmdEnd1\n\t}\n\tswitch string(body[cmdPos : cmdPos+cmdEnd]) {\n\tdefault:\n\t\tcmd = CmdUnknown\n\tcase \"\":\n\t\tcmd = CmdNone\n\tcase \"upstream\":\n\t\tcmd = CmdUpstream\n\tcase \"fix\", \"fix:\":\n\t\tcmd = CmdFix\n\tcase \"dup\", \"dup:\":\n\t\tcmd = CmdDup\n\tcase \"undup\":\n\t\tcmd = CmdUnDup\n\tcase \"test\", \"test:\":\n\t\tcmd = CmdTest\n\tcase \"invalid\":\n\t\tcmd = CmdInvalid\n\tcase \"uncc\", \"uncc:\":\n\t\tcmd = CmdUnCC\n\tcase \"test_5_arg_cmd\":\n\t\tcmd = cmdTest5\n\t}\n\t// Some email clients split text emails at 80 columns are the transformation is irrevesible.\n\t// We try hard to restore what was there before.\n\t// For \"test:\" command we know that there must be 2 tokens without spaces.\n\t// For \"fix:\"/\"dup:\" we need a whole non-empty line of text.\n\tswitch cmd {\n\tcase CmdTest:\n\t\targs = extractArgsTokens(body[cmdPos+cmdEnd:], 2)\n\tcase cmdTest5:\n\t\targs = extractArgsTokens(body[cmdPos+cmdEnd:], 5)\n\tcase CmdFix, CmdDup:\n\t\targs = extractArgsLine(body[cmdPos+cmdEnd:])\n\tcase CmdUnknown:\n\t\targs = extractArgsLine(body[cmdPos:])\n\t}\n\treturn\n}", "func decodeCommands(s *scope, obj pyObject) (string, map[string]string) {\n\tif obj == nil || obj == None {\n\t\treturn \"\", nil\n\t} else if cmd, ok := obj.(pyString); ok {\n\t\treturn strings.TrimSpace(string(cmd)), nil\n\t}\n\tcmds, ok := asDict(obj)\n\ts.Assert(ok, \"Unknown type for command [%s]\", obj.Type())\n\t// Have to convert all the keys too\n\tm := make(map[string]string, len(cmds))\n\tfor k, v := range cmds {\n\t\tif v != None {\n\t\t\tsv, ok := v.(pyString)\n\t\t\ts.Assert(ok, \"Unknown type for command\")\n\t\t\tm[k] = strings.TrimSpace(string(sv))\n\t\t}\n\t}\n\treturn \"\", m\n}", "func executeCommand(commandline string) bool {\n\n\t// Trim prefix and split string by white spaces\n\tcommandFields := strings.Fields(commandline)\n\n\t// Check for empty string without prefix\n\tif len(commandFields) > 0 {\n\n\t\t// Switch according to the first word and call appropriate function with the rest as arguments\n\t\tswitch commandFields[0] {\n\n\t\tcase \"node\":\n\t\t\tnodeInfo(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"bootstrap\":\n\t\t\tlistBootstrap(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"join\":\n\t\t\tjoinBootstrap(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"rendezvous\":\n\t\t\trendezvous(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"setrendezvous\":\n\t\t\tsetRendezvous(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"advertise\":\n\t\t\tadvertise(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Cid\n\t\tcase \"provide\":\n\t\t\tkDhtProvide(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Cid\n\t\tcase \"providekey\":\n\t\t\tkDhtProvideKey(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Cid\n\t\tcase \"kdfindproviders\":\n\t\t\tkDhtFindProviders(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Cid\n\t\tcase \"kdfindprovidersasync\":\n\t\t\tkDhtFindProvidersAsync(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Peer\n\t\tcase \"kdfindpeer\":\n\t\t\tkDhtFindPeer(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Peer\n\t\tcase \"kdfindlocal\":\n\t\t\tkDhtFindLocal(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Peer\n\t\tcase \"kdupdate\":\n\t\t\tkDhtUpdate(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Value\n\t\tcase \"putvalue\":\n\t\t\tkDhtPutValue(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"putkeyvalue\":\n\t\t\tkDhtPutKeyValue(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Value\n\t\tcase \"getvalue\":\n\t\t\tkDhtGetValue(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"getkeyvalue\":\n\t\t\tkDhtGetKeyValue(commandFields[1:])\n\t\t\treturn true\n\n\t\t// Value\n\t\tcase \"getvalues\":\n\t\t\tkDhtGetValues(commandFields[1:])\n\t\t\treturn true\n\n\t\t// RoutingTable\n\t\tcase \"routingtable\":\n\t\t\tkDhtRoutingTable(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"close\":\n\t\t\tkDhtClose(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"debug\":\n\t\t\tkDhtDebug(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"quit\":\n\t\t\tquitCmdTool(commandFields[1:])\n\t\t\treturn true\n\n\t\tcase \"play\":\n\t\t\tplay(commandFields[1:])\n\t\t\treturn true\n\n\t\tdefault:\n\t\t\tusage()\n\t\t\treturn false\n\t\t}\n\n\t\t/* ******** PACKAGE API ********\n\n\t\t\tfunc New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, error)\n\t\t\tfunc NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT\n\t\t\tfunc NewDHTClient(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT\n\n\t\t\tfunc (dht *IpfsDHT) Bootstrap(ctx context.Context) error\n\t\t\tfunc (dht *IpfsDHT) Context() context.Context\n\t\t\tfunc (dht *IpfsDHT) Process() goprocess.Process\n\t\t\tfunc (dht *IpfsDHT) BootstrapWithConfig(cfg BootstrapConfig) (goprocess.Process, error)\n\t\t\tfunc (dht *IpfsDHT) BootstrapOnSignal(cfg BootstrapConfig, signal <-chan time.Time) (goprocess.Process, error)\n\n\n\n\t\t\tfunc (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo\n\t\t\tfunc (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ pstore.PeerInfo, err error)\n\t\t\tfunc (dht *IpfsDHT) Update(ctx context.Context, p peer.ID)\n\t\t!\tfunc (dht *IpfsDHT) GetPublicKey(ctx context.Context, p peer.ID) (ci.PubKey, error)\n\n\t\t!\tfunc (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *pstore.PeerInfo, error)\n\n\n\n\t\t\t//func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error)\n\t\t\t//func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]pstore.PeerInfo, error)\n\n\t\t\tfunc (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan pstore.PeerInfo\n\n\n\n\t\t\tfunc (dht *IpfsDHT) PutValue(ctx context.Context, key string, value []byte, opts ...ropts.Option) (err error)\n\t\t\tfunc (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...ropts.Option) (_ []byte, err error)\n\t\t\tfunc (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error)\n\n\t\t\tfunc (dht *IpfsDHT) SearchValue(ctx context.Context, key string, opts ...ropts.Option) (<-chan []byte, error)\n\t\t\tfunc (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan peer.ID, error)\n\n\n\n\t\t\tfunc (dht *IpfsDHT) Close() error\n\t\t*/\n\n\t}\n\treturn false\n}", "func parseInput(input string) (program, error) {\n lines := strings.Split(input, \"\\n\")\n retval := NewProgram()\n hasDataRegex := regexp.MustCompile(\"[^[:space:]]\")\n lineRegex := regexp.MustCompile(\"(nop|acc|jmp)[[:space:]]+((?:\\\\+|-)?[[:digit:]]+)\")\n for _, line := range lines {\n if hasDataRegex.MatchString(line) {\n lineMatch := lineRegex.FindStringSubmatch(line)\n if len(lineMatch) != 3 {\n return retval, fmt.Errorf(\"Could not parse line [%s].\", line)\n }\n err := retval.addInstruction(lineMatch[1], lineMatch[2])\n if err != nil {\n return retval, err\n }\n }\n }\n return retval, nil\n}", "func processCommand(cmd string) {\n\targs := strings.Split(strings.Trim(cmd, \"\\r\\n\"), \" \")\n\n\t//Compute distance to the customer\n\tif args[0] == \"PEERADDR\" {\n\t\tpeerAddr := args[1]\n\t\twords := strings.Split(peerAddr, \":\")\n\t\tgo dialPeer(peerAddr)\n\t\tgo dialHeart(words[0] + \":\" + nextNextPort(words[1]))\n\t}\n}", "func main() {\n\tInitVars()\n\ttfmBins := InitTfmBins(&OsPath)\n\tverConstraints, err := ParseTfmConfigs(\"./\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"[ERROR] %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\ttfmBinFile := SelectTfmBin(verConstraints, tfmBins)\n\tmyDebug(\"Calling: %s\", tfmBinFile)\n\tif tfmBinFile == \"\" {\n\t\tfmt.Println(\"[ERROR] there is no file to execute\")\n\t\tos.Exit(1)\n\t}\n\tout, err := exec.Command(tfmBinFile, os.Args[1:]...).CombinedOutput()\n\tfmt.Println(string(out[:]))\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func calculateDownCommands(configuration *Configuration) ([]string, error) {\n\tswitch configuration.Data[down] {\n\tcase dhcp:\n\t\tif configuration.Version < latest {\n\t\t\treturn nil, errors.New(\"DHCP not supported\")\n\t\t}\n\t\treturn []string{\n\t\t\t\"pkill dhclient\",\n\t\t\t\"ifdown eth0\",\n\t\t}, nil\n\tcase static:\n\t\treturn []string{\n\t\t\t\"ifdown eth0\",\n\t\t}, nil\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported configuration mode\")\n\t}\n}", "func execDecode(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := png.Decode(args[0].(io.Reader))\n\tp.Ret(1, ret, ret1)\n}", "func DecodeCommand(rawCommand []byte) (command *Command, err error) {\n\tcommand = new(Command)\n\terr = plist.Unmarshal(rawCommand, command)\n\tif err != nil {\n\t\treturn\n\t}\n\tcommand.Raw = rawCommand\n\tif command.CommandUUID == \"\" || command.Command.RequestType == \"\" {\n\t\terr = ErrInvalidCommand\n\t}\n\treturn\n}", "func (d *Debugger) DisassembleAt(addr uint64, count uint64) ([]Disassembly, error) {\n\tvar code []byte\n\tvar ret []Disassembly\n\tvar err error\n\tvar disasm *cs.Engine // Capstone disassembly engine (via capstr)\n\tvar regs []Register\n\n\t// If we run outside the bounds of mapped region, keep reducing the\n\t// data length until we succeed\n\tfor len := count * uint64(d.arch.maxInstructionSize()); len > 0; len-- {\n\t\tcode, err = d.ReadMem(addr, len)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tregs, err = d.ReadRegAll()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t// TODO: Don't create (and destory) a new disassembly engine every time\n\t//\t\t we're called. Push this into the Architecture to provide us the handle.\n\t//\t\t Under the hood we can create disassembler for each valid mode and return\n\t//\t\t the one pertaining to the current mode.\n\tdisasm, err = cs.New(d.arch.id().cs, d.arch.currentMode(regs).cs)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif err = disasm.Option(cs.OPT_TYPE_SKIPDATA, cs.OPT_ON); err != nil {\n\t\tdisasm.Close()\n\t\treturn ret, err\n\t}\n\n\tinstrs, err := disasm.Dis(code, addr, count)\n\tif err != nil {\n\t\tdisasm.Close()\n\t\treturn ret, err\n\t}\n\n\tfor _, instr := range instrs {\n\t\tvar entry Disassembly\n\t\tentry.AddressU64 = instr.Addr()\n\t\tentry.Address = fmt.Sprintf(\"%08x\", instr.Addr())\n\t\tentry.Opcode = hex.EncodeToString(instr.Bytes())\n\t\tentry.Mnemonic = instr.Mnemonic()\n\t\tentry.Operands = instr.OpStr()\n\t\tret = append(ret, entry)\n\t}\n\n\tdisasm.Close()\n\treturn ret, nil\n}", "func processMandalaPid(pid string) (string, string, string, error) {\n\t// valid forms:\n\t// shanti-image-1234567\n\t// shanti-image-dev-1234567\n\tre := regexp.MustCompile(`^shanti-image-(|dev-)\\d+$`)\n\n\tif !re.MatchString(pid) {\n\t\tlogger.Printf(\"%s is NOT Mandala\", pid)\n\t\treturn \"\", \"\", \"\", errors.New(\"PID is not Mandala\")\n\t}\n\n\tpos := strings.LastIndex(pid, \"-\")\n\tpidId := pid[pos+1:]\n\n\tdirPrefix := config.mandalaDirCosmeticPrefix.value\n\tif dirPrefix == \"\" {\n\t\tdirPrefix = config.mandalaDirPrefix.value\n\t}\n\n\tderivativeFile := dirPrefix + buildSubPath(pidId) + \"/\" + pid + \".jp2\"\n\tserviceUrl := config.mandalaServiceUrlTemplate.value\n\taccessUrl := config.mandalaAccessUrlTemplate.value\n\n\treturn derivativeFile, serviceUrl, accessUrl, nil\n}", "func installUpdates(){\n updates, err := exec.Command(\"/bin/bash\", \"-c\", \"apt-get -qq update && apt-get install dmidecode dnsutils\").Output()\n if err != nil {\n log.Fatal(err)\n fmt.Println(\"Failure to update packages.\")\n fmt.Printf(\"%s\", err)\n os.Exit(1)\n }\n fmt.Printf(\"%s\", updates)\n}", "func transformCmd(execCmd *exec.Cmd) icmd.Cmd {\n\treturn icmd.Cmd{\n\t\tCommand: execCmd.Args,\n\t\tEnv: execCmd.Env,\n\t\tDir: execCmd.Dir,\n\t\tStdin: execCmd.Stdin,\n\t\tStdout: execCmd.Stdout,\n\t}\n}", "func IdentifyCommand(cmds map[string]bool, args []string) string {\n\tcommandIndex := 0\n\tcommandSeen := false\n\n\tfor _, arg := range args {\n\t\tif commandSeen {\n\t\t\tbreak\n\t\t}\n\n\t\tif strings.HasPrefix(arg, \"-\") == true {\n\t\t\tcommandIndex++\n\t\t\tcontinue\n\t\t}\n\n\t\tfor cmd := range cmds {\n\t\t\tif arg == cmd {\n\t\t\t\tcommandSeen = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !commandSeen {\n\t\t\tcommandIndex++\n\t\t}\n\t}\n\n\tif !commandSeen {\n\t\treturn \"\"\n\t}\n\n\treturn args[commandIndex]\n}", "func (p *Process) CmdGetID(pac teoapi.Packet) (err error) {\n\tdata := pac.RemoveTrailingZero(pac.Data())\n\trequest := cdb.KeyValue{Cmd: pac.Cmd()}\n\tif err = request.UnmarshalText(data); err != nil {\n\t\treturn\n\t}\n\t// Return only Value for text requests and all fields for json\n\tresponce := request\n\tif responce.Value, err = p.tcdb.GetID(request.Key); err != nil {\n\t\treturn\n\t} else if !request.RequestInJSON {\n\t\t_, err = p.tcdb.con.SendAnswer(pac, pac.Cmd(), responce.Value)\n\t} else if retdata, err := responce.MarshalText(); err == nil {\n\t\t_, err = p.tcdb.con.SendAnswer(pac, pac.Cmd(), retdata)\n\t}\n\treturn\n}", "func CommandsByDeviceName(name string, dic *di.Container) (deviceCoreCommand dtos.DeviceCoreCommand, err errors.EdgeX) {\n\tif name == \"\" {\n\t\treturn deviceCoreCommand, errors.NewCommonEdgeX(errors.KindContractInvalid, \"device name is empty\", nil)\n\t}\n\n\t// retrieve device information through Metadata DeviceClient\n\tdc := V2Container.MetadataDeviceClientFrom(dic.Get)\n\tif dc == nil {\n\t\treturn deviceCoreCommand, errors.NewCommonEdgeX(errors.KindClientError, \"nil MetadataDeviceClient returned\", nil)\n\t}\n\tdeviceResponse, err := dc.DeviceByName(context.Background(), name)\n\tif err != nil {\n\t\treturn deviceCoreCommand, errors.NewCommonEdgeXWrapper(err)\n\t}\n\n\t// retrieve device profile information through Metadata DeviceProfileClient\n\tdpc := V2Container.MetadataDeviceProfileClientFrom(dic.Get)\n\tif dpc == nil {\n\t\treturn deviceCoreCommand, errors.NewCommonEdgeX(errors.KindClientError, \"nil MetadataDeviceProfileClient returned\", nil)\n\t}\n\tdeviceProfileResponse, err := dpc.DeviceProfileByName(context.Background(), deviceResponse.Device.ProfileName)\n\tif err != nil {\n\t\treturn deviceCoreCommand, errors.NewCommonEdgeXWrapper(err)\n\t}\n\n\t// Prepare the url for command\n\tconfiguration := commandContainer.ConfigurationFrom(dic.Get)\n\tserviceUrl := configuration.Service.Url()\n\n\tcommands := make([]dtos.CoreCommand, len(deviceProfileResponse.Profile.CoreCommands))\n\tfor i, c := range deviceProfileResponse.Profile.CoreCommands {\n\t\tcommands[i] = dtos.CoreCommand{\n\t\t\tName: c.Name,\n\t\t\tGet: c.Get,\n\t\t\tSet: c.Set,\n\t\t\tUrl: serviceUrl,\n\t\t\tPath: fmt.Sprintf(\"%s/%s/%s/%s/%s\", V2Routes.ApiDeviceRoute, V2Routes.Name, deviceResponse.Device.Name, V2Routes.Command, c.Name),\n\t\t}\n\t}\n\tdeviceCoreCommand = dtos.DeviceCoreCommand{\n\t\tDeviceName: deviceResponse.Device.Name,\n\t\tProfileName: deviceResponse.Device.ProfileName,\n\t\tCoreCommands: commands,\n\t}\n\treturn deviceCoreCommand, nil\n}", "func (info *Info) Run(c Cursor) {\n\tp := c.P()\n\tif !info.HeadLess {\n\t\tp.Printf(\"info %v {\", info.Domain)\n\t\tp.ShiftIn()\n\t\tdefer p.ShiftOut(\"}\")\n\t}\n\n\tips := info.run(c)\n\tif c.E() != nil {\n\t\treturn\n\t}\n\n\tif !info.HideResult {\n\t\tips.PrintResult(c)\n\n\t\tif len(info.NameServers) > 0 {\n\t\t\tp.Print()\n\t\t\tfor _, ns := range info.NameServers {\n\t\t\t\tp.Printf(\"// %v\", ns)\n\t\t\t}\n\t\t}\n\n\t\tif len(info.Records) > 0 {\n\t\t\tp.Print()\n\t\t\tfor _, rr := range info.Records {\n\t\t\t\tp.Printf(\"// %s\", rr.Digest())\n\t\t\t}\n\t\t}\n\t}\n}", "func (dm *DotnetModule) runCmd() error {\n\tcmd, err := dm.createCmd()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// To prevent NuGet prompting for credentials\n\terr = os.Setenv(\"NUGET_EXE_NO_PROMPT\", \"true\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = io.RunCmd(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (em *Vi) HandleExCommand() {\n\t/*\n\t * could scan the exBuffer continuously and adjust the buffer, e.g. highlight matches. But for now,\n\t * just handle commands such as:\n\t *\n\t * :q :q!\n\t * :w :w!\n\t * :x <- wq!\n\t * :<linenumber>\n\t */\n\n\tcmd := strings.TrimSpace(em.ex.input.ToString())\n\n\tif cmd == \"\" {\n\t\treturn\n\t}\n\n\tif number, err := strconv.Atoi(cmd); err == nil {\n\t\tif number <= 0 {\n\t\t\tnumber = 1\n\t\t}\n\t\tif number > em.Editor.Buffer.Length() {\n\t\t\tnumber = em.Editor.Buffer.Length()\n\t\t}\n\t\tfirst := em.Editor.Cursors[0]\n\t\tfirst.Line = number - 1\n\t\treturn\n\t}\n\n\tparts := strings.Split(cmd, \" \")\n\tp := parts[0]\n\tl := len(parts)\n\t// may contain filename?\n\tswitch p {\n\tcase \"$\": // last line of file\n\t\t// Error if any additional arguments\n\t\tif l > 1 {\n\t\t\tem.c <- &novi.ErrorEvent{Message: \"Extra characters after command\"}\n\t\t\treturn\n\t\t}\n\t\tem.JumpTopBottom(0, false)\n\tcase \"w\", \"wq\", \"w!\", \"wq!\", \"x\", \"x!\":\n\t\tif l > 2 {\n\t\t\tem.c <- &novi.ErrorEvent{Message: \"Extra characters after command\"}\n\t\t\treturn\n\t\t}\n\t\tforce := strings.ContainsRune(p, '!')\n\t\tquit := strings.ContainsRune(p, 'q')\n\t\tfname := \"\"\n\t\tif l > 1 {\n\t\t\tfname = parts[1]\n\t\t}\n\t\tem.c <- &novi.SaveEvent{Name: fname, Force: force}\n\t\tif quit {\n\t\t\tem.c <- &novi.QuitEvent{Force: force}\n\t\t}\n\tcase \"q\", \"q!\":\n\t\tif l > 1 {\n\t\t\tem.c <- &novi.ErrorEvent{Message: \"Extra characters after command\"}\n\t\t\treturn\n\t\t}\n\t\tforce := strings.ContainsRune(p, '!')\n\t\tem.c <- &novi.QuitEvent{Force: force}\n\t}\n}", "func (sa *SeaweedAdmin) ProcessCommands(cmds string) error {\n\tfor _, c := range strings.Split(cmds, \";\") {\n\t\tif err := sa.ProcessCommand(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func run(cmd string, v interface{}, extraArgs ...string) error {\n\tvar args []string\n\tcmdUseNsenter := fmt.Sprintf(\"%s %s\", localtype.NsenterCmd, cmd)\n\targs = append(args, cmdUseNsenter)\n\tif v != nil {\n\t\targs = append(args, \"--reportformat=json\")\n\t\targs = append(args, \"--units=b\")\n\t\targs = append(args, \"--nosuffix\")\n\t}\n\targs = append(args, extraArgs...)\n\tc := exec.Command(\"sh\", \"-c\", strings.Join(args[:], \" \"))\n\t// log.Infof(\"Executing: %s\", c.String())\n\tstdout, stderr := new(bytes.Buffer), new(bytes.Buffer)\n\tc.Stdout = stdout\n\tc.Stderr = stderr\n\tif err := c.Run(); err != nil {\n\t\terrstr := ignoreWarnings(stderr.String())\n\t\t// log.Infof(\"stdout: \" + stdout.String())\n\t\t// log.Infof(\"stderr: \" + errstr)\n\t\tlog.Debugf(\"[debug run]: command %s\", c.String())\n\t\tlog.Debugf(\"[debug run]: error %s\", err.Error())\n\t\treturn errors.New(errstr)\n\t}\n\tstdoutbuf := stdout.Bytes()\n\t// stderrbuf := stderr.Bytes()\n\t// errstr := ignoreWarnings(string(stderrbuf))\n\t// log.Infof(\"stdout: \" + string(stdoutbuf))\n\t// log.Infof(\"stderr: \" + errstr)\n\tif v != nil {\n\t\tif err := json.Unmarshal(stdoutbuf, v); err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshal error: %s\", err.Error())\n\t\t}\n\t}\n\treturn nil\n}", "func (d *Diagnosis) cmdlineHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\")\n\tfmt.Fprintf(w, strings.Join(os.Args, \"\\x00\"))\n}", "func main() {\n\tif err := cmd.Cmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}", "func decodeInstruction(p *program, i modules.Instruction) (instruction, error) {\n\tswitch i.Specifier {\n\tcase modules.SpecifierAppend:\n\t\treturn p.staticDecodeAppendInstruction(i)\n\tcase modules.SpecifierDropSectors:\n\t\treturn p.staticDecodeDropSectorsInstruction(i)\n\tcase modules.SpecifierHasSector:\n\t\treturn p.staticDecodeHasSectorInstruction(i)\n\tcase modules.SpecifierReadSector:\n\t\treturn p.staticDecodeReadSectorInstruction(i)\n\tcase modules.SpecifierReadOffset:\n\t\treturn p.staticDecodeReadOffsetInstruction(i)\n\tcase modules.SpecifierRevision:\n\t\treturn p.staticDecodeRevisionInstruction(i)\n\tcase modules.SpecifierSwapSector:\n\t\treturn p.staticDecodeSwapSectorInstruction(i)\n\tcase modules.SpecifierUpdateRegistry:\n\t\treturn p.staticDecodeUpdateRegistryInstruction(i)\n\tcase modules.SpecifierReadRegistry:\n\t\treturn p.staticDecodeReadRegistryInstruction(i)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown instruction specifier: %v\", i.Specifier)\n\t}\n}", "func ExtractCommand(value byte) (byte, byte) {\n\treturn (value & maskCmdType) >> 6, value & maskCmdQty\n}", "func ProcessKcodeFileString(data []byte, flags KCodeFlags, verbose bool) (spells []string, blocks []string, parts []string, scene string) {\n\txml, _ := ExtractXML(data)\n\tDumpXML(xml, true, verbose)\n\t// Parse the XML and convert to JSON\n\tlog.Info(\"------- Parsing kcode XML to JSON ------\")\n\t// https://stackoverflow.com/questions/44065935/cannot-use-type-byte-as-type-io-reader\n\tjsn, err := xml2json.Convert(bytes.NewReader(xml))\n\tcheck(\"new reader\", err)\n\t//log.Info(jsn.String())\n\tlog.WithFields(log.Fields{\n\t\t\"json\": jsn.String(),\n\t}).Info(\"XML to JSON\")\n\n\tif flags.Blocks {\n\t\t// Extract blocks from JSON\n\t\t//fmt.Printf(\"------- Extracting blocks from .kcode file '%s' ------\\n\", filename)\n\t\tlog.Info(\"------- Extracting blocks ------\")\n\t\tblocks = ExtractBlocks(jsn.Bytes(), verbose)\n\t\tlog.Info(fmt.Sprintf(\"--- Found %d blocks ---\\n\", len(blocks)))\n\t\tfor i, block := range blocks {\n\t\t\tlog.Info(fmt.Sprintf(\"%d] %s\\n\", i+1, block))\n\t\t}\n\t}\n\tif flags.Spells {\n\t\t// Extract spells from JSON\n\t\t//fmt.Printf(\"------- Extracting spells from .kcode file '%s' ------\\n\", filename)\n\t\tlog.Info(\"------- Extracting spells ------\")\n\t\tspells = ExtractSpells(jsn.Bytes(), verbose)\n\t\tlog.Info(fmt.Sprintf(\"--- Found %d spells ---\\n\", len(spells)))\n\t\tfor i, spell := range spells {\n\t\t\tlog.Info(fmt.Sprintf(\"%d] %s\\n\", i+1, spell))\n\t\t}\n\t}\n\tif flags.Parts {\n\t\tparts, _ = ExtractParts(data)\n\t}\n\tif flags.Scene {\n\t\tscene, _ = ExtractScene(data)\n\t}\n\n\treturn\n}", "func ParseCommand(args []string) {\n SetProcess(args[0])\n SetConfig(config.Process(args[0]))\n opts := commandOpts(args)\n\n if message, ok := cfg.Valid(); ok {\n\n name := args[1]\n daemonCmd, daemonOk := DaemonizedCommands()[name]\n infoCmd, infoOk := InfoCommands()[name]\n interactiveCmd, interactiveOk := InteractiveCommands()[name]\n\n switch {\n case daemonOk:\n daemonCmd.run(opts...)\n case infoOk:\n infoCmd.run(opts...)\n case interactiveOk:\n interactiveCmd.run(opts...)\n default:\n logger.Log(fmt.Sprintf(\"Running Command: (%v) doesn't exists\\n\", args[1]))\n }\n } else {\n logger.Log(message)\n }\n\n}", "func main() {\n\t// choose dcgm hostengine running mode\n\t// 1. dcgm.Embedded\n\t// 2. dcgm.Standalone -connect \"addr\", -socket \"isSocket\"\n\t// 3. dcgm.StartHostengine\n\tflag.Parse()\n\tif err := dcgm.Init(dcgm.Standalone, *connectAddr, *isSocket); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tdefer func() {\n\t\tif err := dcgm.Shutdown(); err != nil {\n\t\t\tlog.Panicln(err)\n\t\t}\n\t}()\n\n\tcount, err := dcgm.GetAllDeviceCount()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tt := template.Must(template.New(\"Device\").Parse(deviceInfo))\n\n\tfor i := uint(0); i < count; i++ {\n\t\tdeviceInfo, err := dcgm.GetDeviceInfo(i)\n\t\tif err != nil {\n\t\t\tlog.Panicln(err)\n\t\t}\n\n\t\tif err = t.Execute(os.Stdout, deviceInfo); err != nil {\n\t\t\tlog.Panicln(\"Template error:\", err)\n\t\t}\n\t}\n}", "func readCmd() {\n\tbzIn, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot read stdin: %v\", err)\n\t\treturn\n\t}\n\tvestingData, err := unmarshalVestingData(bzIn)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot decode vesting data: %v\", err)\n\t\treturn\n\t}\n\tevents, err := vestingDataToEvents(vestingData)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot convert vesting data: %v\", err)\n\t}\n\tbzOut, err := marshalEvents(events)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cannot encode events: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(string(bzOut))\n}", "func handleHost() {\n\tfmt.Println(\"\\nUnknown or missing command.\\nRun dynpower-cli domain --help to show available commands.\")\n}", "func (t *dnsTestCommon) runDig(dnsName, target string) []string {\n\tcmd := []string{\"/usr/bin/dig\", \"+short\"}\n\tswitch target {\n\tcase \"kube-dns\":\n\t\tcmd = append(cmd, \"@\"+t.dnsPod.Status.PodIP, \"-p\", \"10053\")\n\tcase \"dnsmasq\":\n\t\tbreak\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid target: \" + target))\n\t}\n\tcmd = append(cmd, dnsName)\n\n\tstdout, stderr, err := t.f.ExecWithOptions(framework.ExecOptions{\n\t\tCommand: cmd,\n\t\tNamespace: t.f.Namespace.Name,\n\t\tPodName: t.utilPod.Name,\n\t\tContainerName: \"util\",\n\t\tCaptureStdout: true,\n\t\tCaptureStderr: true,\n\t})\n\n\tframework.Logf(\"Running dig: %v, stdout: %q, stderr: %q, err: %v\",\n\t\tcmd, stdout, stderr, err)\n\n\tif stdout == \"\" {\n\t\treturn []string{}\n\t} else {\n\t\treturn strings.Split(stdout, \"\\n\")\n\t}\n}", "func Instr() {\n\tcolorprint.Blue(\"Listening on \" + rpcAddress + \" for incoming RPC calls\")\n\tvar input string\n\tvar fname string\n\tfor i := 0; i >= 0; i++ {\n\t\tfmt.Println()\n\t\tcolorprint.Info(\">>>> Please enter a command\")\n\t\tfmt.Scan(&input)\n\t\tcmd := input\n\t\tif input == \"get\" {\n\t\t\tgetHelper(rpcAddress, input, fname, cmd)\n\t\t} else if input == \"list\" {\n\n\t\t} else if input == \"help\" {\n\t\t\tui.Help()\n\t\t} else if input == \"play\" {\n\t\t\tplayHelper(fname)\n\t\t}\n\t}\n}", "func Exec(cmd string) {\n\n\tfmt.Printf(\"Você digitou: %s \", cmd)\n\n}", "func TestDex(t *testing.T) {\n\tcli, _ := newTestCLI()\n\tcli.TestCommand(\"ns test\")\n\tcli.TestCommand(\"set config:network fake\")\n\n\tcli.TestCommand(\"account new mo\")\n\tcli.TestCommand(\"account new kelly\")\n\n\tcli.TestCommand(\"account new issuer-chase\")\n\tcli.TestCommand(\"account new issuer-citi\")\n\n\tcli.TestCommand(\"asset set USD issuer-chase\")\n\tcli.TestCommand(\"asset set INR issuer-chase\")\n\tcli.TestCommand(\"asset set EUR issuer-chase\")\n\tcli.TestCommand(\"asset set USD-citi issuer-citi --code USD\")\n\n\texpectOutput(t, cli, \"\", \"dex trade mo --buy USD --sell INR --amount 20 --price 2\")\n\texpectOutput(t, cli, \"\", \"dex trade mo --buy INR --sell USD --amount 20 --price 2 --passive\")\n\texpectOutput(t, cli, \"\", \"dex trade mo --buy USD --sell EUR --amount 20 --price 2\")\n\texpectOutput(t, cli, \"\", \"dex trade mo --buy INR --sell USD --amount 20 --price 2 --update 23112\")\n\texpectOutput(t, cli, \"\", \"dex trade mo --buy INR --sell USD --amount 20 --price 2 --delete 23112\")\n\texpectOutput(t, cli, \"\", \"dex list mo --cursor 23443 --limit 3 --desc\")\n\n\texpectOutput(t, cli, \"\", \"dex orderbook USD INR --limit 10\")\n}", "func init() {\n\tAddCommand(\"mds\", \"Check metadata service process\", cmdMds, nil)\n}", "func main() {\n\n\treader := bufio.NewReader(os.Stdin)\n\n\tfor {\n\t\tfmt.Print(\"Enter command: \")\n\t\tif line, err := reader.ReadString('\\n'); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\targs := strings.Split(line, \" \")\n\t\t\tif fn, ok := commandMap[args[0]]; !ok {\n\t\t\t\tfmt.Println(\"Invalid Command.\")\n\t\t\t} else {\n\t\t\t\tfn(args[1:])\n\t\t\t}\n\t\t}\n\t}\n}", "func GetCmd() (int){\n url := \"http://127.0.0.1:8080/\"\n resp, err := http.Get(url)\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n\n body, err := ioutil.ReadAll(resp.Body)\n\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n re := regexp.MustCompile(\"\\\\(cmd\\\\).*?\\\\(cmd\\\\)\")\n cmdParsed := re.FindStringSubmatch(string(body))\n cmd := strings.Join(cmdParsed, \" \")\n cmd = strings.ReplaceAll(cmd, \"(cmd)\", \"\")\n\n re = regexp.MustCompile(\"\\\\(arg\\\\).*?\\\\(arg\\\\)\")\n argParsed := re.FindStringSubmatch(string(body))\n arg := strings.Join(argParsed, \" \")\n arg = strings.ReplaceAll(arg, \"(arg)\", \"\")\n arg = html.UnescapeString(arg)\n\n\n // Debugging commmand input\n // fmt.Println(\"Command is: \" + cmd + \" \" + arg + \" \" + val)\n \n args, err := shellwords.Parse(arg)\n\n if err != nil{\n //log.Fatalln(err)\n return 0\n }\n\n var out []byte\n\n if cmd != \"\" && len(args) > 0 {\n out, err = exec.Command(cmd, args...).Output()\n\t} else if cmd != \"\" {\n out, err = exec.Command(cmd).Output()\n\t} \n\n if err != nil {\n //log.Fatalln(err)\n return 0\n }\n SendResponse(string(out))\n\n return 0\n}", "func commandSmcli(cmd *cli.Cmd) {\n\tvar (\n\t\tmsgs []string\n\t\tidentifier *string\n\t\tsmcliConfig storage.SmcliConfig\n\t)\n\n\tidentifier = cmd.String(cli.StringOpt{\n\t\tName: \"i identifier\",\n\t\tDesc: \"Provisioner identifier (e.g. if ensure, set it to current node's name)\",\n\t\tEnvVar: \"IDENTIFIER\",\n\t})\n\n\tsmcliConfig.SanAddress = cmd.String(cli.StringOpt{\n\t\tName: \"a sanAddress\",\n\t\tDesc: \"SAN address to connect to\",\n\t\tEnvVar: \"SAN_ADDRESS\",\n\t})\n\n\tsmcliConfig.SanPassword = cmd.String(cli.StringOpt{\n\t\tName: \"p sanPassword\",\n\t\tDesc: \"SAN password\",\n\t\tEnvVar: \"SAN_PASSWORD\",\n\t})\n\n\tsmcliConfig.SanGroupName = cmd.String(cli.StringOpt{\n\t\tName: \"g sanGroupName\",\n\t\tDesc: \"SAN Group name\",\n\t\tEnvVar: \"SAN_GROUP_NAME\",\n\t})\n\n\tsmcliConfig.SmcliCommand = cmd.String(cli.StringOpt{\n\t\tName: \"s smcliCommand\",\n\t\tValue: \"/opt/dell/mdstoragemanager/client/SMcli\",\n\t\tDesc: \"Path to the smcli command\",\n\t\tEnvVar: \"SMCLI_COMMAND\",\n\t})\n\n\tdefragActivated = cmd.Bool(cli.BoolOpt{\n\t\tName: \"d defrag\",\n\t\tValue: false,\n\t\tDesc: \"Enable defrag sub-routine (running every 24h the following command: start diskGroup [\\\"<disk-group>\\\"] defragment;)\",\n\t})\n\n\tcmd.Action = func() {\n\t\t/* Params checking */\n\t\tif *identifier == \"\" {\n\t\t\tmsgs = append(msgs, \"Identifier must be specified\")\n\t\t}\n\t\tif *smcliConfig.SanAddress == \"\" {\n\t\t\tmsgs = append(msgs, \"San address must be specified\")\n\t\t}\n\t\tif *smcliConfig.SanGroupName == \"\" {\n\t\t\tmsgs = append(msgs, \"San group name must be specified\")\n\t\t}\n\t\tif *smcliConfig.SmcliCommand == \"\" {\n\t\t\tmsgs = append(msgs, \"Path to the smcli command\")\n\t\t}\n\t\tprocessErrors(msgs)\n\n\t\t/* Everything's good so far, ready to start */\n\t\tglog.Infoln(\"Starting dell-provisioner with the following parameters\")\n\t\tglog.Infof(\" Identifier: %s\", *identifier)\n\t\tglog.Infof(\" San address: %s\", *smcliConfig.SanAddress)\n\t\tglog.Infof(\" San group name: %s\", *smcliConfig.SanGroupName)\n\t\tglog.Infof(\" Smcli command: %s\", *smcliConfig.SmcliCommand)\n\n\t\t// Execute with this particular config implem\n\t\texecute(*identifier, &smcliConfig)\n\t}\n}", "func (p *parser) parse(cmdOutput string) []string {\n\tp.ips = []string{}\n\tp.scanner = bufio.NewScanner(strings.NewReader(cmdOutput))\n\tfor p.scanner.Scan() {\n\t\tline := p.scanner.Text()\n\t\tline = strings.TrimLeft(line, \" \\t\")\n\t\tp.parseLine(line)\n\t}\n\treturn p.ips\n}", "func parseDevice(cmd *cobra.Command, name string) (models.Device, error) {\n\t//load Device from database\n\tclient := local.New(config.Conf.Clients[\"Metadata\"].Url() + clients.ApiDeviceRoute)\n\tdevice, err := metadata.NewDeviceClient(client).DeviceForName(cmd.Context(), name)\n\tif err != nil {\n\t\treturn models.Device{}, err\n\t}\n\n\t//populate the template with the loaded device and open default editor, so the client could customize the data\n\tupdatedDeviceBytes, err := editor.OpenInteractiveEditor(device, DeviceTemp, template.FuncMap{\n\t\t\"inc\": func(i int) int {\n\t\t\treturn i + 1\n\t\t},\n\t\t\"lastElem\": editor.IsLastElementOfSlice,\n\t})\n\tif err != nil {\n\t\treturn models.Device{}, err\n\t}\n\n\tvar d models.Device\n\terr = json.Unmarshal(updatedDeviceBytes, &d)\n\tif err != nil {\n\t\treturn models.Device{}, errors.New(\"Unable to execute the command. The provided information is invalid: \" + err.Error())\n\t}\n\treturn d, nil\n}", "func (m *DF1CommandResponseMessageProtectedTypedLogicalRead) CommandCode() uint8 {\n\treturn 0x4F\n}", "func runCommand(query string) ([]byte, error) {\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tcmd := fmt.Sprintf(\"%s/dasgoclient\", path)\n\tout, err := exec.Command(cmd, \"-query\", query, \"-format\", \"json\").Output()\n\treturn out, err\n}", "func (pmmprepl *PMMPostREPL) InterpretCommand(input string) {\n\terrors := pmmprepl.pmmpintp.ParseStatements([]byte(input))\n\tif errors != nil {\n\t\tfor _, err := range errors {\n\t\t\tio.WriteString(pmmprepl.readline.Stderr(), err.Error())\n\t\t}\n\t}\n}", "func runMachineFromVmCode() {\n\tfilename := \"\"\n\tif len(os.Args) == 1 {\n\t\tfilename = \"./sample/vm/func.vm\"\n\t} else {\n\t\tfilename = os.Args[1]\n\t}\n\n\t_, err := os.Stat(filename)\n\tif err != nil {\n\t\tif len(os.Args) == 1 {\n\t\t\tfmt.Print(\"[ERROR] filename is not given\")\n\t\t} else {\n\t\t\tfmt.Printf(\"[ERROR] given filename(%s) is not confirm. please confirm you have correct path\", filename)\n\t\t}\n\t}\n\n\tvirtualMachine := vm.New()\n\tasmProgram := virtualMachine.FromFile(filename)\n\n\tassm := assembler.New()\n\tbinaryProgram := assm.FromString(asmProgram)\n\n\tmachine := computer.NewComputer()\n\tcomputer.LoadPresetBinaryProgram(machine)(binaryProgram)\n\tmachine.Run()\n}", "func (cm *Cmd) parsePlugCmd() {\n\n\tif len(os.Args) < 3 {\n\t\tfmt.Println(\"not found [Plug-in name]\")\n\t\tfmt.Println(\"go-sniffer [device] [plug] [plug's params(optional)]\")\n\t\tos.Exit(1)\n\t}\n\n\tcm.Device = os.Args[1]\n\tplugName := os.Args[2]\n\tplugParams := os.Args[3:]\n\tcm.plugHandle.SetOption(plugName, plugParams)\n}", "func encodeCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"encode\",\n\t\tShort: \"Encode a splice_info_section to binary\",\n\t\tArgs: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn fmt.Errorf(\"requires a splice_info_section\")\n\t\t\t}\n\t\t\tif !strings.HasPrefix(args[0], \"<\") && !strings.HasPrefix(args[0], \"{\") {\n\t\t\t\treturn fmt.Errorf(\"splice_info_section must be in XML or JSON format\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tbin := args[0]\n\n\t\t\tvar sis *scte35.SpliceInfoSection\n\t\t\tvar err error\n\n\t\t\t// decode payload\n\t\t\tif strings.HasPrefix(bin, \"<\") {\n\t\t\t\terr = xml.Unmarshal([]byte(bin), &sis)\n\t\t\t} else {\n\t\t\t\terr = json.Unmarshal([]byte(bin), &sis)\n\t\t\t}\n\n\t\t\t// print encoded signal\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"Base64: %s\\n\", sis.Base64())\n\t\t\t_, _ = fmt.Fprintf(os.Stdout, \"Hex : %s\\n\", sis.Hex())\n\n\t\t\t// and any errors\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"Error: %s\\n\", err)\n\t\t\t}\n\t\t},\n\t}\n\treturn cmd\n}", "func IPAM(args []string) error {\n\tdoc := constants.DatastoreIntro + `Usage:\n <BINARY_NAME> ipam <command> [<args>...]\n\n check Check the integrity of the IPAM datastructures.\n release Release a Calico assigned IP address.\n show Show details of a Calico configuration,\n assigned IP address, or of overall IP usage.\n split Split the IP pool specified by the CIDR into\n the specified number of smaller IPPools.\n configure Configure IPAM\n\nOptions:\n -h --help Show this screen.\n\nDescription:\n IP address management commands for Calico.\n\n See '<BINARY_NAME> ipam <command> --help' to read about a specific subcommand.\n`\n\t// Replace all instances of BINARY_NAME with the name of the binary.\n\tname, _ := util.NameAndDescription()\n\tdoc = strings.ReplaceAll(doc, \"<BINARY_NAME>\", name)\n\n\tvar parser = &docopt.Parser{\n\t\tHelpHandler: docopt.PrintHelpAndExit,\n\t\tOptionsFirst: true,\n\t\tSkipHelpFlags: false,\n\t}\n\targuments, err := parser.ParseArgs(doc, args, \"\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Invalid option: 'calicoctl %s'. Use flag '--help' to read about a specific subcommand.\", strings.Join(args, \" \"))\n\t}\n\tif arguments[\"<command>\"] == nil {\n\t\treturn nil\n\t}\n\n\tcommand := arguments[\"<command>\"].(string)\n\targs = append([]string{\"ipam\", command}, arguments[\"<args>\"].([]string)...)\n\n\tswitch command {\n\tcase \"check\":\n\t\treturn ipam.Check(args, VERSION)\n\tcase \"release\":\n\t\treturn ipam.Release(args, VERSION)\n\tcase \"show\":\n\t\treturn ipam.Show(args)\n\tcase \"configure\":\n\t\treturn ipam.Configure(args)\n\tcase \"split\":\n\t\treturn ipam.Split(args)\n\tdefault:\n\t\tfmt.Println(doc)\n\t}\n\n\treturn nil\n}", "func (c parser) GetHexDeviceID(command []byte) (string, error) {\n\treturn extractByteRangeAndReturnHex(command, 5, 25, \"Identificador do device não encontrado\")\n}", "func execDecodeRuneInString(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := utf8.DecodeRuneInString(args[0].(string))\n\tp.Ret(1, ret, ret1)\n}", "func PrintCommands() {\n logger.Log(fmt.Sprintln(\"** Daemonized Commands **\"))\n for cmd, desc := range DaemonizedCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Information Commands **\"))\n for cmd, desc := range InfoCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Interactive Commands **\"))\n for cmd, desc := range InteractiveCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n}" ]
[ "0.62859994", "0.53434825", "0.52908665", "0.5260162", "0.5202774", "0.51410824", "0.5131315", "0.5093057", "0.50811994", "0.5061913", "0.5028405", "0.49798483", "0.49514756", "0.49433208", "0.49284688", "0.49141854", "0.48708302", "0.48691788", "0.48642355", "0.48441032", "0.48328903", "0.48094758", "0.47815746", "0.4772761", "0.47692385", "0.47630545", "0.4759036", "0.47504115", "0.47440624", "0.47290948", "0.4724627", "0.4716959", "0.47120768", "0.46992403", "0.4688045", "0.46846467", "0.4682363", "0.4678723", "0.4673956", "0.46448472", "0.46297625", "0.46294433", "0.46185613", "0.4612192", "0.4606659", "0.46017525", "0.4600362", "0.45845723", "0.4581605", "0.45775175", "0.4563431", "0.4554647", "0.4552136", "0.45485833", "0.4546348", "0.45423293", "0.45300418", "0.4527634", "0.45252523", "0.45164374", "0.45116392", "0.45085534", "0.45052773", "0.4503401", "0.44968712", "0.44949815", "0.44889957", "0.4479023", "0.44788513", "0.44753444", "0.4474649", "0.4472622", "0.44581762", "0.44575065", "0.44573095", "0.4453948", "0.44430178", "0.4439748", "0.44363546", "0.44354835", "0.443406", "0.44333377", "0.44205043", "0.44189528", "0.44113594", "0.44090068", "0.4406426", "0.44036683", "0.44016767", "0.43964967", "0.43829778", "0.43793127", "0.43758428", "0.43731374", "0.43651143", "0.43638292", "0.43628946", "0.43625146", "0.43611047", "0.43604794" ]
0.50990856
7
Uptime returns the uptime of the node
func (r *ResourceOracle) Uptime() (uint64, error) { info, err := host.Info() if err != nil { return 0, err } return info.Uptime, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Uptime() (uint64, error) {\n\thostInfo, err := host.Info()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn hostInfo.Uptime, nil\n}", "func Uptime() (int64, error) {\n\tinfo := &syscall.Sysinfo_t{}\n\terr := syscall.Sysinfo(info)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn int64(info.Uptime), nil\n}", "func (s *ServerStat) uptime() uint32 {\n\treturn uint32(time.Now().Unix() - s.init_ts)\n}", "func (s Sysinfo) Uptime() uint64 {\n\treturn s.uptime\n}", "func Uptime() string {\n\tkon := Console{Command: \"uptime\"}\n\tkon.Run()\n\treturn strings.Fields(kon.StdOutput)[0]\n}", "func (p *process) Uptime() string {\n\ts := p.cmd.ProcessState\n\tif s != nil && s.Exited() {\n\t\treturn \"exited\"\n\t}\n\n\tduration := time.Since(p.startTime)\n\treturn duration.String()\n}", "func (r *RuntimeImpl) Uptime() time.Duration {\n\treturn time.Now().Sub(r.startup)\n}", "func Uptime() time.Duration {\n\treturn time.Now().Sub(processStartTime)\n}", "func uptime() (time.Duration,error) {\n\tvar ts syscall.Timespec\n\terr := clock_gettime(CLOCK_BOOTTIME, &ts)\n\tif err != nil {\n\t\treturn time.Duration(0),err\n\t}\n\n\treturn time.Duration(-ts.Nsec)*time.Nanosecond +time.Duration(-ts.Sec)*time.Second,nil\n}", "func (p *GenericPlugin) Uptime() time.Duration {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.state == stateActive {\n\t\treturn time.Since(p.started)\n\t}\n\treturn 0\n}", "func Uptime(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"uptime\": stats.UptimeFormated()})\n}", "func uptime() interface{} {\n\tuptime := time.Since(startTime)\n\treturn int64(uptime)\n}", "func uptime() interface{} {\n\tuptime := time.Since(startTime)\n\treturn int64(uptime)\n}", "func (a API) Uptime(cmd *None) (e error) {\n\tRPCHandlers[\"uptime\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (t *simpleTest) getUptime(coordinatorURL string) (time.Duration, error) {\n\tt.log.Infof(\"Checking uptime of '%s'\", coordinatorURL)\n\toperationTimeout := t.OperationTimeout * 2\n\tvar statsResp struct {\n\t\tServer struct {\n\t\t\tUptime float64 `json:\"uptime\"`\n\t\t} `json:\"server\"`\n\t}\n\tif err := t.client.SetCoordinator(coordinatorURL); err != nil {\n\t\tt.log.Errorf(\"Failed to set coordinator URL to '%s': %v\", coordinatorURL, err)\n\t\treturn 0, maskAny(err)\n\t}\n\tif resp, err := t.client.Get(\"/_admin/statistics\", nil, nil, &statsResp, []int{200}, []int{201, 202, 400, 404, 409, 307}, operationTimeout, 1); err[0] != nil {\n\t\treturn 0, maskAny(fmt.Errorf(\"Failed to query uptime of '%s': %v\", resp[0].CoordinatorURL, err[0]))\n\t} else if resp[0].CoordinatorURL != coordinatorURL {\n\t\treturn 0, maskAny(fmt.Errorf(\"Failed to query uptime of '%s': got response from other coordinator '%s'\", coordinatorURL, resp[0].CoordinatorURL))\n\t}\n\n\treturn time.Second * time.Duration(statsResp.Server.Uptime), nil\n}", "func (rp *Ringpop) Uptime() time.Duration {\n\treturn time.Now().Sub(rp.startTime)\n}", "func Uptime(s time.Time) (string, error) {\n\tnowUnix := time.Now().Unix()\n\ttimeDiff := nowUnix - s.Unix()\n\tdurTime, err := time.ParseDuration(fmt.Sprintf(\"%ds\", timeDiff))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresponseMsg := fmt.Sprintf(\"I was started: %v, so I am running for %v now\",\n\t\ts.Format(time.RFC1123), durTime.String())\n\n\treturn responseMsg, nil\n}", "func GetUptime() float64 {\n\tout, err := exec.Command(\"sysctl\", \"-n\", \"kern.boottime\").Output()\n\t// { sec = 1413585004, usec = 0 } Fri Oct 17 15:30:04 2014\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpieces := strings.Fields(string(out))\n\n\treturn ConvertSeconds(strings.TrimRight(pieces[3], \",\"))\n}", "func uptime(contents string) (*time.Time, error) {\n\tuptimeArray := strings.Fields(contents)\n\tif len(uptimeArray) == 0 {\n\t\treturn nil, errors.New(\"error:the contents of proc/uptime we are trying to read are empty\")\n\t}\n\tuptimeDuration, err := time.ParseDuration(string(uptimeArray[0]) + \"s\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuptime := time.Time{}.Add(uptimeDuration)\n\n\treturn &uptime, nil\n}", "func uptime(start time.Time) string {\n\treturn time.Since(start).String()\n}", "func (a *AniDBUDP) Uptime() <-chan *UptimeReply {\n\tch := make(chan *UptimeReply, 2)\n\tgo func() {\n\t\treply := <-a.SendRecv(\"UPTIME\", ParamMap{})\n\n\t\tr := &UptimeReply{APIReply: reply}\n\t\tif r.Error() == nil {\n\t\t\tuptime, _ := strconv.ParseInt(reply.Lines()[1], 10, 32)\n\t\t\tr.Uptime = time.Duration(uptime) * time.Millisecond\n\t\t}\n\t\tch <- r\n\t\tclose(ch)\n\t}()\n\treturn ch\n}", "func testUptime() testFunctionReturn {\n\tuptime,_ := host.Uptime()\n\n\t// if uptime is lower than 5 min\n\tif uptime < 10*60 {\n\t\treturn testFunctionReturn{percentageVM: 0.7}\n\t}\n\n\t// if uptime longer than 2 days liekly suspicious\n\tif uptime > 2*24*60*60 {\n\t\treturn testFunctionReturn{percentageVM: 0.4}\n\t}\n\n\t// within limits normal user behavior\n\treturn testFunctionReturn{percentageUser: 0.6}\n}", "func parseUptime() int {\n\tcached, _ := ioutil.ReadFile(\"/proc/uptime\")\n\treturn strToInt(strings.Split(string(cached), \".\")[0])\n}", "func computeUptime(activeState string, activeEnterTimestampMicroSec uint64, unitNow int64) int64 {\n\tif activeState != unitActiveState {\n\t\treturn 0\n\t}\n\tuptime := unitNow - int64(activeEnterTimestampMicroSec)/1000000\n\tif uptime < 0 {\n\t\treturn 0\n\t}\n\treturn uptime\n}", "func readUptime() (time.Duration, error) {\n\tbytes, err := ioutil.ReadFile(\"/proc/uptime\")\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to open /proc/uptime: %s\", err.Error())\n\t}\n\t// Split on the space to get uptime and drop cpu idle time.\n\tuptimeFields := strings.Fields(string(bytes))\n\tif len(uptimeFields) == 0 {\n\t\treturn 0, fmt.Errorf(\"unable to parse /proc/uptime\")\n\t}\n\tuptime, err := strconv.ParseFloat(uptimeFields[0], 64)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to parse uptime: %s\", err.Error())\n\t}\n\treturn time.Duration(uptime * float64(time.Second)), nil\n}", "func readUptime() (time.Duration, error) {\n\tbytes, err := ioutil.ReadFile(\"/proc/uptime\")\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to open /proc/uptime: %s\", err.Error())\n\t}\n\t// Split on the space to get uptime and drop cpu idle time.\n\tuptimeFields := strings.Fields(string(bytes))\n\tif len(uptimeFields) == 0 {\n\t\treturn 0, fmt.Errorf(\"unable to parse /proc/uptime\")\n\t}\n\tuptime, err := strconv.ParseFloat(uptimeFields[0], 64)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unable to parse uptime: %s\", err.Error())\n\t}\n\treturn time.Duration(uptime * float64(time.Second)), nil\n}", "func GetRawUptime() (float64, error) {\n s, err := ioutil.ReadFile(\"/proc/uptime\")\n if err != nil {\n return 0, err\n }\n f, err := BytesToFloat(s[:bytes.IndexByte(s, ' ')])\n return f, err\n}", "func Uptime(uptime *string, done chan bool) {\n\t*uptime = fmt.Sprintf(\"Uptime: %s\", humanReadableTime(parseUptime()))\n\tdone <- true\n}", "func getServiceUptime(processID uint32) (time.Duration, error) {\n\tvar processCreationTime gosigar.ProcTime\n\n\terr := processCreationTime.Get(int(processID))\n\tif err != nil {\n\t\treturn time.Duration(processCreationTime.StartTime), err\n\t}\n\n\tuptime := time.Since(time.Unix(0, int64(processCreationTime.StartTime)*int64(time.Millisecond)))\n\n\treturn uptime, nil\n}", "func (m *Mock) Uptime(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar err error\n\tif !m.Data.Uptime {\n\t\terr = errors.New(\"uptime less than expected\")\n\t}\n\treturn nil, nil, err\n}", "func (s *Server) DumpUptime() string {\n\treturn time.Since(s.startTime).String()\n}", "func uptime(srvChan chan string, channel, nick, hostname string, args []string) {\n\tout, err := exec.Command(\"uptime\").Output()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\toutFields := strings.Split(strings.TrimSpace(string(out)), \",\")\n\tmessage := \"NOTICE \" + channel + \" :System: \" + strings.Join(outFields[:2], \",\")\n\tselfUptime := time.Since(startTime)\n\tmessage += fmt.Sprintf(\" || Self: %d days, %02d:%02d\", int(selfUptime.Hours())/24, int(selfUptime.Hours())%24, int(selfUptime.Minutes())%60)\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func GatewayUpdateUptime(ctx context.Context, db *mongo.Database, nodeID string, uptime int64) error {\n\treturn gwUpdate(ctx, db, nodeID, bson.M{\n\t\t\"uptime\": uptime,\n\t\t\"updated\": schema.Date{Time: time.Now()},\n\t})\n}", "func (na *Nagent) GetNetagentUptime() (string, error) {\n\tdur := time.Since(na.NetAgentStartTime)\n\tuptime := fmt.Sprintf(\"Netagent up and running for: %s\", dur.String())\n\treturn uptime, nil\n}", "func GetUptimeInSeconds() (int64, error) {\n\tosUptime, err := uptime.Get()\n\tif err != nil {\n\t\treturn -1, errors.Wrap(err, \"exec uptime.Get failed\")\n\t}\n\n\treturn int64(osUptime / time.Second), nil\n}", "func (a API) UptimeWait(cmd *None) (out *btcjson.GetMempoolInfoResult, e error) {\n\tRPCHandlers[\"uptime\"].Call <-API{a.Ch, cmd, nil}\n\tselect {\n\tcase <-time.After(time.Second*5):\n\t\tbreak\n\tcase o := <-a.Ch.(chan UptimeRes):\n\t\tout, e = o.Res, o.Err\n\t}\n\treturn\n}", "func getBoottime() (int64, error) {\n\n\t//this seems to be how dmesg -T does it\n\t//This is dmesg's 'faillback' method as getting access to clock_gettime() from go is more trouble than it's worth.\n\ttv := &syscall.Timeval{}\n\terr := syscall.Gettimeofday(tv)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tinfo := &syscall.Sysinfo_t{}\n\tsyscall.Sysinfo(info)\n\n\treturn (tv.Sec - info.Uptime), nil\n}", "func (c *MockRegistry) CheckUptime(url string) error {\n\treturn c.CheckUptimeError\n}", "func TestUptimeCalculator(t *testing.T) {\n\n\tcalcFunc := CreateUpdateCalculationFunction(time.Now().Unix(), 10*time.Second)\n\tstart := time.Now().Unix()\n\tWaitForGracePeriod(10*time.Second, calcFunc, false)\n\tend := time.Now().Unix()\n\tdiff := end - start\n\tassert.True(t, diff >= 10)\n\n}", "func (a API) UptimeGetRes() (out *btcjson.GetMempoolInfoResult, e error) {\n\tout, _ = a.Result.(*btcjson.GetMempoolInfoResult)\n\te, _ = a.Result.(error)\n\treturn \n}", "func TestUptimeInitiate(t *testing.T) {\n\ttests := []struct {\n\t\tuptime float64\n\t\tdowntime float64\n\t\texpectedUptime float64\n\t\texpectedDowntime float64\n\t\ttimeUpdated bool\n\t}{\n\t\t{0, 0, initialAccumulatedUptime, initialAccumulatedDowntime, true},\n\t\t{10, 10, 10, 10, false},\n\t}\n\tfor _, test := range tests {\n\t\tinfo := storage.HostInfo{\n\t\t\tAccumulatedUptime: test.uptime,\n\t\t\tAccumulatedDowntime: test.downtime,\n\t\t}\n\t\tuptimeInitiate(&info)\n\t\tif info.AccumulatedUptime != test.expectedUptime {\n\t\t\tt.Errorf(\"uptime not expected\")\n\t\t}\n\t\tif info.AccumulatedDowntime != test.expectedDowntime {\n\t\t\tt.Errorf(\"downtime not expected\")\n\t\t}\n\t\tif test.timeUpdated && info.LastCheckTime == 0 {\n\t\t\tt.Errorf(\"time not updated\")\n\t\t}\n\t}\n}", "func CalcUptimePercent(down int, up int) string {\n\treturn fmt.Sprintf(\"%.3f%%\", 100-(float32(down)/float32(up))*100)\n}", "func (smc *SpotMC) uptimeWatcher() {\n\tlogFields := log.Fields{\"maxUptime\": smc.maxUptime}\n\tlog.WithFields(logFields).Info(\"uptimeWatcher starting\")\n\n\td := time.Duration(smc.maxUptime) * time.Second\n\ttime.Sleep(d)\n\n\tlog.WithFields(logFields).Info(\"uptime exceeded limit, shutdown the cluster\")\n\tsmc.msgs <- msgShutdownCluster\n}", "func NewUnixUptimeFn() tact.GetDataFn {\n\treturn func(session *tact.Session) <-chan []byte {\n\t\treturn collector.SSHRex(session, upTimeCmd, upTimeParser)\n\t}\n}", "func GetHealth(c echo.Context) error {\n\tu := int(time.Since(helpers.StartTime).Seconds())\n\tuptime := &Health{\n\t\tStatus: \"ok\",\n\t\tUptime: u,\n\t}\n\n\treturn c.JSON(http.StatusOK, uptime)\n}", "func (o *NetworkElementSummaryAllOf) GetSystemUpTime() string {\n\tif o == nil || o.SystemUpTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SystemUpTime\n}", "func TestCalcUptimeUpdate(t *testing.T) {\n\ttests := []struct {\n\t\tsuccess bool\n\t\tupRateIncreased bool\n\t}{\n\t\t{true, true},\n\t\t{false, false},\n\t}\n\n\tfor _, test := range tests {\n\t\tinfo := storage.HostInfo{\n\t\t\tAccumulatedUptime: 1000,\n\t\t\tAccumulatedDowntime: 1000,\n\t\t\tLastCheckTime: uint64(time.Now().Unix() - 1000),\n\t\t}\n\t\tprevRate := getHostUpRate(info)\n\n\t\tnewInfo := calcUptimeUpdate(info, test.success, uint64(time.Now().Unix()))\n\t\tnewRate := getHostUpRate(newInfo)\n\n\t\tif test.upRateIncreased && prevRate >= newRate {\n\t\t\tt.Error(\"uprate not incrementing\")\n\t\t}\n\t\tif !test.upRateIncreased && prevRate <= newRate {\n\t\t\tt.Error(\"uprate not decreasing\")\n\t\t}\n\t}\n}", "func ListUptime(api, user, key string) []UptimeCheckResult {\n\tclient := &http.Client{}\n\trequest, _ := http.NewRequest(\"GET\", api+\"/API/Tests/\", nil)\n\trequest.Header.Add(\"Username\", user)\n\trequest.Header.Add(\"API\", key)\n\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tresponseBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tvar uptimeCheckSlice []UptimeCheckResult\n\te := json.Unmarshal(responseBody, &uptimeCheckSlice)\n\tif e != nil {\n\t\tlog.Println(e)\n\t\tlog.Println(\"Error: Failed to parse response body\")\n\t}\n\t// debug\n\t// log.Println(string(string(responseBody)))\n\n\treturn uptimeCheckSlice\n}", "func recordUptime() {\n\tfor range time.Tick(time.Second) {\n\t\tuptime.WithLabelValues().Inc()\n\t}\n}", "func Utime(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n\tpathAddr := args[0].Pointer()\n\ttimesAddr := args[1].Pointer()\n\n\tpath, err := copyInPath(t, pathAddr)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\topts := vfs.SetStatOptions{\n\t\tStat: linux.Statx{\n\t\t\tMask: linux.STATX_ATIME | linux.STATX_MTIME,\n\t\t},\n\t}\n\tif timesAddr == 0 {\n\t\topts.Stat.Atime.Nsec = linux.UTIME_NOW\n\t\topts.Stat.Mtime.Nsec = linux.UTIME_NOW\n\t} else {\n\t\tvar times linux.Utime\n\t\tif err := times.CopyIn(t, timesAddr); err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t\topts.Stat.Atime.Sec = times.Actime\n\t\topts.Stat.Mtime.Sec = times.Modtime\n\t}\n\n\treturn 0, nil, setstatat(t, linux.AT_FDCWD, path, disallowEmptyPath, followFinalSymlink, &opts)\n}", "func (a API) UptimeChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan UptimeRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func NodeStatus(runenv *runtime.RunEnv, btcAddr string, seq int64) (result float64, err error) {\n\tclient := http.Client{}\n\trequest, err := http.NewRequest(\"GET\", \"http://localhost:20443/v2/info\", nil)\n\tbtcPort := []string{\"28443\"}\n\tif (len(btcAddr) > 0 && seq != 1) {\n\t\tbtcConn := btcConnect(runenv, btcAddr, btcPort)\n\t\tif !btcConn {\n\t\t\tfakeHeight := (runenv.IntParam(\"stacks_tip_height\")+10) // ensure we'll cross the threshold\n\t\t\trunenv.RecordMessage(\"BTC Connection is closed -> Stopping this instance\")\n\t\t\trunenv.RecordMessage(\"Setting an artificial stacks_tip_height to: %v\", fakeHeight)\n\t\t\treturn float64(fakeHeight), nil\n\t\t}\n\t}\n\tif err != nil {\n\t\trunenv.RecordMessage(fmt.Sprintf(\"%s\", err))\n\t\treturn\n\t}\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\trunenv.RecordMessage(fmt.Sprintf(\"Waiting for node: [%s]\", err))\n\t\treturn\n\t}\n\tvar item map[string]interface{}\n\tjson.NewDecoder(resp.Body).Decode(&item)\n\trunenv.RecordMessage(fmt.Sprintf(\"Stacks block height => %.0f :: Burn block height => %.0f\", item[\"stacks_tip_height\"], item[\"burn_block_height\"]))\n\t// Extra info to tell us how many neighbors each instance has.\n\t// NodeNeighbors(runenv)\n\treturn item[\"stacks_tip_height\"].(float64), nil\n}", "func getCPUUtilization() (*define.CPUUsage, error) {\n\tbuf, err := unix.SysctlRaw(\"kern.cp_time\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading sysctl kern.cp_time: %w\", err)\n\t}\n\n\tvar total uint64 = 0\n\tvar times [unix.CPUSTATES]uint64\n\n\tfor i := 0; i < unix.CPUSTATES; i++ {\n\t\tval := *(*uint64)(unsafe.Pointer(&buf[8*i]))\n\t\ttimes[i] = val\n\t\ttotal += val\n\t}\n\treturn &define.CPUUsage{\n\t\tUserPercent: timeToPercent(times[unix.CP_USER], total),\n\t\tSystemPercent: timeToPercent(times[unix.CP_SYS], total),\n\t\tIdlePercent: timeToPercent(times[unix.CP_IDLE], total),\n\t}, nil\n}", "func (hdb *HostDB) uptimeAdjustments(entry modules.HostDBEntry) float64 {\n\t// Special case: if we have scanned the host twice or fewer, don't perform\n\t// uptime math.\n\tif len(entry.ScanHistory) == 0 {\n\t\treturn 0.25\n\t}\n\tif len(entry.ScanHistory) == 1 {\n\t\tif entry.ScanHistory[0].Success {\n\t\t\treturn 0.75\n\t\t}\n\t\treturn 0.25\n\t}\n\tif len(entry.ScanHistory) == 2 {\n\t\tif entry.ScanHistory[0].Success && entry.ScanHistory[1].Success {\n\t\t\treturn 0.85\n\t\t}\n\t\tif entry.ScanHistory[0].Success || entry.ScanHistory[1].Success {\n\t\t\treturn 0.50\n\t\t}\n\t\treturn 0.05\n\t}\n\n\t// Compute the total measured uptime and total measured downtime for this\n\t// host.\n\tdowntime := entry.HistoricDowntime\n\tuptime := entry.HistoricUptime\n\trecentTime := entry.ScanHistory[0].Timestamp\n\trecentSuccess := entry.ScanHistory[0].Success\n\tfor _, scan := range entry.ScanHistory[1:] {\n\t\tif recentTime.After(scan.Timestamp) {\n\t\t\tif build.DEBUG {\n\t\t\t\thdb.log.Critical(\"Host entry scan history not sorted.\")\n\t\t\t} else {\n\t\t\t\thdb.log.Print(\"WARNING: Host entry scan history not sorted.\")\n\t\t\t}\n\t\t\t// Ignore the unsorted scan entry.\n\t\t\tcontinue\n\t\t}\n\t\tif recentSuccess {\n\t\t\tuptime += scan.Timestamp.Sub(recentTime)\n\t\t} else {\n\t\t\tdowntime += scan.Timestamp.Sub(recentTime)\n\t\t}\n\t\trecentTime = scan.Timestamp\n\t\trecentSuccess = scan.Success\n\t}\n\t// Sanity check against 0 total time.\n\tif uptime == 0 && downtime == 0 {\n\t\treturn 0.001 // Shouldn't happen.\n\t}\n\n\t// Compute the uptime ratio, but shift by 0.02 to acknowledge fully that\n\t// 98% uptime and 100% uptime is valued the same.\n\tuptimeRatio := float64(uptime) / float64(uptime+downtime)\n\tif uptimeRatio > 0.98 {\n\t\tuptimeRatio = 0.98\n\t}\n\tuptimeRatio += 0.02\n\n\t// Cap the total amount of downtime allowed based on the total number of\n\t// scans that have happened.\n\tallowedDowntime := 0.03 * float64(len(entry.ScanHistory))\n\tif uptimeRatio < 1-allowedDowntime {\n\t\tuptimeRatio = 1 - allowedDowntime\n\t}\n\n\t// Calculate the penalty for low uptime. Penalties increase extremely\n\t// quickly as uptime falls away from 95%.\n\t//\n\t// 100% uptime = 1\n\t// 98% uptime = 1\n\t// 95% uptime = 0.83\n\t// 90% uptime = 0.26\n\t// 85% uptime = 0.03\n\t// 80% uptime = 0.001\n\t// 75% uptime = 0.00001\n\t// 70% uptime = 0.0000001\n\texp := 200 * math.Min(1-uptimeRatio, 0.30)\n\treturn math.Pow(uptimeRatio, exp)\n}", "func (u UptimePlugin) FetchMetrics() (map[string]float64, error) {\n\tut, err := uptime.Get()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to fetch uptime metrics: %s\", err)\n\t}\n\treturn map[string]float64{\"seconds\": ut.Seconds()}, nil\n}", "func (m *metricRedisUptime) init() {\n\tm.data.SetName(\"redis.uptime\")\n\tm.data.SetDescription(\"Number of seconds since Redis server start\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}", "func daemonTime(c *testing.T) time.Time {\n\tc.Helper()\n\tif testEnv.IsLocalDaemon() {\n\t\treturn time.Now()\n\t}\n\tapiClient, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer apiClient.Close()\n\n\tinfo, err := apiClient.Info(context.Background())\n\tassert.NilError(c, err)\n\n\tdt, err := time.Parse(time.RFC3339Nano, info.SystemTime)\n\tassert.Assert(c, err == nil, \"invalid time format in GET /info response\")\n\treturn dt\n}", "func GetUpTime() string {\n\tnowTime := time.Now()\n\tdiff := nowTime.Sub(BotStartTime)\n\n\treturn diff.Round(time.Second).String()\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func ProcessStateUserTime(p *os.ProcessState,) time.Duration", "func (c *UptimeCommand) Run(args []string) int {\n\tvar periodName string\n\tvar tags string\n\n\t// Parse flags\n\tcmdFlags := flag.NewFlagSet(\"uptime\", flag.ContinueOnError)\n\tcmdFlags.StringVar(&periodName, \"period\", \"Today\", fmt.Sprintf(\"Period for report: %s\", strings.Join(c.GetPeriodOptions(), \", \")))\n\tcmdFlags.StringVar(&tags, \"tags\", \"\", \"Comma-separated list of tags. Ex: tag1,tag2\")\n\tcmdFlags.Usage = func() { c.Help() }\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\tc.Help()\n\t\treturn 1\n\t}\n\n\t//uptimeByCheck := map[string]string{}\n\n\tchecksList := ListChecks(tags)\n\n\ttimePeriod := GetPeriodByName(periodName, 0)\n\tperiodFrom, periodTo := timePeriod.String()\n\n\tfmt.Println(\"\\nPingdom Uptime Report\")\n\tfmt.Printf(\"Reporting Period (%s):\\n\", periodName)\n\tfmt.Printf(\"From: %s\\n\", periodFrom)\n\tfmt.Printf(\"To: %s\\n\", periodTo)\n\tfmt.Println(\"\")\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(checksList.Checks))\n\n\tfmt.Println(\"Check\\tUptime\\t\")\n\tfor _, v := range checksList.Checks {\n\t\tgo trackCheckAverage(v.ID, v.Name, &timePeriod, &wg)\n\t}\n\n\tfmt.Println(\"\")\n\twg.Wait()\n\treturn 0\n}", "func (c *Connection) Ping(ctx context.Context) (time.Duration, error) {\n\tresp, err := c.Request(ctx).\n\t\tGet(\"/status\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn resp.Time(), nil\n}", "func (o BareMetalAdminClusterOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BareMetalAdminCluster) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func UpTime() func() int64 {\n\tvar startTime int64 = timeStamp()\n\treturn func() int64 {\n\t\treturn timeStamp() - startTime\n\t}\n}", "func (t *Task) PctOfUpd() uint64 {\n\treturn t.percentOf(t.Upd)\n}", "func (c DockerContainers) Describe(ch chan<- *prometheus.Desc) {\n\tch <- containerUptime\n}", "func GetCPUUsage(pid int) int {\n\tup, err := ioutil.ReadFile(\"/proc/uptime\")\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to read /proc/uptime: \", err)\n\t\treturn -1\n\t}\n\tstat, err := ioutil.ReadFile(fmt.Sprintf(\"/proc/%v/stat\", pid))\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to read /proc: \", err)\n\t\treturn -1\n\t}\n\tparts := strings.Split(string(stat), \" \")\n\tcpuUsage := 0\n\tvar (\n\t\tutime, _ = strconv.Atoi(parts[14])\n\t\tstime, _ = strconv.Atoi(parts[15])\n\t\tcutime, _ = strconv.Atoi(parts[16])\n\t\tcstime, _ = strconv.Atoi(parts[17])\n\t\tstartTime, _ = strconv.Atoi(parts[22])\n\t\ttotalTime = utime + stime + cutime + cstime\n\t\tuptime, _ = strconv.Atoi(string(up))\n\t\tseconds = uptime - (startTime / 1000)\n\t)\n\tif seconds > 0 {\n\t\tcpuUsage = 100 * ((totalTime / 1000) / seconds)\n\t}\n\treturn cpuUsage\n}", "func (c *Config) GetMemberStatusRefreshTime() time.Duration {\n\treturn c.member.GetDuration(varMemberStatusRefreshTime)\n}", "func (s *ServerStat) time() uint32 {\n\treturn uint32(time.Now().Unix())\n}", "func (tcpCollect *TcpCollect) GetTimeAwait() (int64, error) {\n\tfileName := \"/proc/net/sockstat\"\n\tfile, err := os.Open(fileName)\n\n\tif err != nil {\n\t\tutil.GetLogger().Println(err.Error())\n\t\treturn -1, err\n\t}\n\n\tbuf := bufio.NewReader(file)\n\tsockstatData := make(map[string]int64)\n\tfor {\n\t\tline, err := buf.ReadString('\\n')\n\n\t\tif err == io.EOF {\n\t\t\tutil.GetLogger().Println(err.Error())\n\t\t\treturn tcpCollect.tcpTimeAwait, err\n\t\t}\n\n\t\tif strings.Contains(line, \"TCP\") {\n\t\t\ttmpSlice := strings.Split(strings.TrimSpace(line[strings.Index(line, \":\")+1:]), \" \")\n\t\t\tfor i := 0; i < len(tmpSlice); i += 2 {\n\t\t\t\tsockstatData[tmpSlice[i]], _ = strconv.ParseInt(tmpSlice[i+1], 10, 64)\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\ttcpCollect.tcpTimeAwait = sockstatData[\"tw\"]\n\n\treturn tcpCollect.tcpTimeAwait, err\n}", "func taskDuration(t *swarming_api.SwarmingRpcsTaskRequestMetadata) (int64, error) {\n\tcompletedTime, err := swarming.Completed(t)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tstartTime, err := swarming.Started(t)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn int64(completedTime.Sub(startTime).Seconds() * float64(1000.0)), nil\n}", "func (o *V0037Node) GetBootTime() int64 {\n\tif o == nil || o.BootTime == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.BootTime\n}", "func daemonUnixTime(c *testing.T) string {\n\tc.Helper()\n\treturn parseEventTime(daemonTime(c))\n}", "func (o WorkerPoolOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func (o WorkerPoolOutput) UpdateTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerPool) pulumi.StringOutput { return v.UpdateTime }).(pulumi.StringOutput)\n}", "func BootTime() (int64, error) {\n\tif bootTime != nil {\n\t\treturn *bootTime, nil\n\t}\n\n\tf, err := os.Open(\"/proc/stat\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbtimeStr := \"\"\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tfields := strings.Fields(scanner.Text())\n\t\tif len(fields) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif fields[0] == \"btime\" {\n\t\t\tbtimeStr = fields[1]\n\t\t}\n\t}\n\n\tif len(btimeStr) == 0 {\n\t\treturn 0, fmt.Errorf(\"couldn't extract boot time from /proc/stat\")\n\t}\n\n\tbtimeSec, err := strconv.ParseInt(btimeStr, 10, 64)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"error parsing boot time from /proc/stat: %w\", err)\n\t}\n\tbootTime = &btimeSec\n\treturn btimeSec, nil\n}", "func SystemInfo() string {\n\n\tvar si SysInfo\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\tsi.AllocMemory = m.Alloc\n\tsi.AllocMemoryMB = btomb(m.Alloc)\n\tsi.TotalAllocMemory = m.TotalAlloc\n\tsi.TotalAllocMemoryMB = btomb(m.TotalAlloc)\n\tsi.TotalSystemMemory = m.Sys\n\tsi.TotalSystemMemoryMB = btomb(m.Sys)\n\tc, _ := cpu.Info()\n\n\tsi.CPUs = c[0].Cores\n\n\tsi.GolangVersion = runtime.Version()\n\tsi.ContainerHostName, _ = os.Hostname()\n\tsi.CurrentUTC = time.Now().UTC()\n\n\tsi.CurrentLocalTime = time.Now().Local()\n\n\tconst (\n\t\tB = 1\n\t\tKB = 1024 * B\n\t\tMB = 1024 * KB\n\t\tGB = 1024 * MB\n\t)\n\n\tv, _ := mem.VirtualMemory()\n\tfmt.Printf(\"Total: %v, Free:%v, UsedPercent:%f%%\\n\", v.Total, v.Free, v.UsedPercent)\n\n\ttype InfoStat struct {\n\t\tHostname string `json:\"hostname\"`\n\t\tUptime uint64 `json:\"uptime\"`\n\t\tBootTime uint64 `json:\"bootTime\"`\n\t\tProcs uint64 `json:\"procs\"` // number of processes\n\t\tOS string `json:\"os\"` // ex: freebsd, linux\n\t\tPlatform string `json:\"platform\"` // ex: ubuntu, linuxmint\n\t\tPlatformFamily string `json:\"platformFamily\"` // ex: debian, rhel\n\t\tPlatformVersion string `json:\"platformVersion\"` // version of the complete OS\n\t\tKernelVersion string `json:\"kernelVersion\"` // version of the OS kernel (if available)\n\t\tVirtualizationSystem string `json:\"virtualizationSystem\"`\n\t\tVirtualizationRole string `json:\"virtualizationRole\"` // guest or host\n\t\tHostID string `json:\"hostid\"` // ex: uuid\n\t}\n\n\tvar his *host.InfoStat\n\this, _ = host.Info()\n\n\tsi.Uptime = his.Uptime\n\n\tsi.OperatingSystem = his.OS\n\tsi.Platform = his.Platform\n\tsi.PlatformFamily = his.PlatformFamily\n\tsi.PlatformVersion = his.PlatformVersion\n\tsi.VirtualSystem = his.VirtualizationSystem\n\tsi.VirtualRole = his.VirtualizationRole\n\tsi.HostID = his.HostID\n\tsi.HostName = his.Hostname\n\tsi.BootTime = strconv.FormatUint(his.BootTime, 10)\n\tsi.KernelVersion = his.KernelVersion\n\n\tsi.UptimeDays = si.Uptime / (60 * 60 * 24)\n\tsi.UptimeHours = (si.Uptime - (si.UptimeDays * 60 * 60 * 24)) / (60 * 60)\n\tsi.UptimeMinutes = ((si.Uptime - (si.UptimeDays * 60 * 60 * 24)) - (si.UptimeHours * 60 * 60)) / 60\n\tinterfaces, err := net.Interfaces()\n\n\tif err == nil {\n\t\tfor i, interfac := range interfaces {\n\t\t\tif interfac.Name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddrs := interfac.Addrs\n\t\t\tsi.NetworkInterfaces[i].Name = interfac.Name\n\t\t\tsi.NetworkInterfaces[i].HardwareAddress = string(interfac.HardwareAddr)\n\t\t\tfor x, addr := range addrs {\n\t\t\t\tif addr.String() != \"\" {\n\t\t\t\t\tsi.NetworkInterfaces[i].IPAddresses[x].IPAddress = addr.String()\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar paths [10]string\n\tpaths[0] = \"/\"\n\n\tfor i, path := range paths {\n\t\tdisk := DiskUsage(path)\n\t\tsi.Disk[i].Path = path\n\t\tsi.Disk[i].All = float64(disk.All) / float64(GB)\n\t\tsi.Disk[i].Used = float64(disk.Used) / float64(GB)\n\t\tsi.Disk[i].Free = float64(disk.Free) / float64(GB)\n\t}\n\n\tstrJSON, err := json.Marshal(si)\n\tcheckErr(err)\n\n\treturn string(strJSON)\n}", "func (tp *TagPosts) UpdateTime() time.Time {\n\treturn tp.Tag.updated\n}", "func (o *NetworkElementSummaryAllOf) GetSystemUpTimeOk() (*string, bool) {\n\tif o == nil || o.SystemUpTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SystemUpTime, true\n}", "func CreateUptimeCheck(domain string, checkrate, timeout, confirmation, virus, donotfind, realbrowser, trigger, sslalert, follow int, contacts, testType, findstring, api, user, key string) bool {\n\ttarget, err := url.Parse(domain)\n\tif err != nil {\n\t\tfmt.Println(\"Please make sure to enter a valid domain (e.g https://www.domain.com)\")\n\t\treturn false\n\t}\n\tif target.Scheme == \"\" {\n\t\tfmt.Printf(\"Please add url scheme http/https to your domain %v\\n\", domain)\n\t\treturn false\n\t}\n\n\tp := url.Values{}\n\tp.Add(\"WebsiteName\", domain)\n\tp.Add(\"WebsiteURL\", domain)\n\tp.Add(\"CheckRate\", strconv.Itoa(checkrate))\n\tp.Add(\"Timeout\", strconv.Itoa(timeout))\n\tp.Add(\"Confirmation\", strconv.Itoa(confirmation))\n\tp.Add(\"Virus\", strconv.Itoa(virus))\n\tp.Add(\"RealBrowser\", strconv.Itoa(realbrowser))\n\tp.Add(\"TriggerRate\", strconv.Itoa(trigger))\n\tif testType == \"HTTP\" {\n\t\tp.Add(\"EnableSSLAlert\", strconv.Itoa(sslalert))\n\t\tp.Add(\"FollowRedirect\", strconv.Itoa(follow))\n\t}\n\tp.Add(\"ContactGroup\", contacts)\n\tp.Add(\"TestType\", testType)\n\tif len(findstring) > 0 {\n\t\tp.Add(\"FindString\", findstring)\n\t\tp.Add(\"DoNotFind\", strconv.Itoa(donotfind))\n\t}\n\tpayload := strings.NewReader(p.Encode())\n\n\tclient := &http.Client{}\n\trequest, _ := http.NewRequest(\"PUT\", api+\"/API/Tests/Update\", payload)\n\trequest.Header.Add(\"Username\", user)\n\trequest.Header.Add(\"API\", key)\n\trequest.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\n\t// debug\n\t// responseBody, _ := ioutil.ReadAll(resp.Body)\n\t// log.Println(string(responseBody))\n\n\tif resp.StatusCode != 200 {\n\t\tmessage := helpers.ResolveStatusCode(resp.StatusCode)\n\t\tlog.Println(message)\n\t\treturn false\n\t}\n\treturn true\n}", "func NodeHeight() (*libwallet.NodeHeightResult, error) {\n\tclient := RPCHTTPClient{URL: url}\n\tenvl, err := client.Request(\"node_height\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif envl == nil {\n\t\treturn nil, errors.New(\"OwnerAPI: 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(\"OwnerAPI: RPC Error during NodeHeight\")\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 nodeHeightResult libwallet.NodeHeightResult\n\tif err := json.Unmarshal(result.Ok, &nodeHeightResult); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &nodeHeightResult, nil\n}", "func ToUsec(t time.Time) int64 {\n\treturn t.UnixNano() / 1e3\n}", "func run_timeNano() int64", "func NanoTime() int64", "func (c *UptimeCommand) Synopsis() string {\n\treturn \"Generate uptime report based on provided arguments\"\n}", "func ProcessStateSystemTime(p *os.ProcessState,) time.Duration", "func (c *UptimeCommand) Help() string {\n\thelpText := `\nUsage: pingdom uptime [options]\n Runs uptime report on Pingdom for specified period on all checks tagged\n with given tags.\nOptions:\n -period PeriodName Default: Today\n Options: %s\n -tags tag1,tag2 If specified, only include checks with one of these tags\n`\n\treturn strings.TrimSpace(fmt.Sprintf(helpText, strings.Join(c.GetPeriodOptions(), \", \")))\n}", "func GetNodeTime(n *Node) int64 {\n\tseconds := int64(0)\n\n\tmnts := n.Moments\n\tfor i := 0; i < len(mnts); i++ {\n\t\tseconds += int64(mnts[i].Activeseconds)\n\t}\n\n\tfor i := 0; i < len(n.SubNodes); i++ {\n\t\tseconds += GetNodeTime(&n.SubNodes[i])\n\t}\n\treturn seconds\n}", "func (mb *MetricsBuilder) RecordRedisUptimeDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisUptime.recordDataPoint(mb.startTime, ts, val)\n}", "func computeTime(referenceTime time.Time, referenceUptime, eventUptime time.Duration) time.Time {\n\tdiff := referenceUptime - eventUptime\n\tif diff < 0 {\n\t\treturn referenceTime\n\t}\n\treturn referenceTime.Add(-1 * diff)\n}", "func NodeStatus(cfg *config.Config, c client.Client) string {\n\tvar status string\n\n\tnodeSync := GetNodeSync(cfg, c) // Getheimdall node sync status\n\tstatus = fmt.Sprintf(\"- Your Heimdall validator node is %s \\n\", nodeSync)\n\n\treturn status\n}", "func Status(ctx context.Context, t *testing.T, path string, profile string, key string, node string) string {\n\tt.Helper()\n\t// Reminder of useful keys: \"Host\", \"Kubelet\", \"APIServer\"\n\trr, err := Run(t, exec.CommandContext(ctx, path, \"status\", fmt.Sprintf(\"--format={{.%s}}\", key), \"-p\", profile, \"-n\", node))\n\tif err != nil {\n\t\tt.Logf(\"status error: %v (may be ok)\", err)\n\t}\n\treturn strings.TrimSpace(rr.Stdout.String())\n}", "func (m *Memberlist) Ping(node string, addr net.Addr) (time.Duration, error) {\n\t// Prepare a ping message and setup an ack handler.\n\tselfAddr, selfPort := m.getAdvertise()\n\tping := ping{\n\t\tSeqNo: m.nextSeqNo(),\n\t\tNode: node,\n\t\tSourceAddr: selfAddr,\n\t\tSourcePort: selfPort,\n\t\tSourceNode: m.config.Name,\n\t}\n\tackCh := make(chan ackMessage, m.config.IndirectChecks+1)\n\tm.setProbeChannels(ping.SeqNo, ackCh, nil, m.config.ProbeInterval)\n\n\ta := Address{Addr: addr.String(), Name: node}\n\n\t// Send a ping to the node.\n\tif err := m.encodeAndSendMsg(a, pingMsg, &ping); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Mark the sent time here, which should be after any pre-processing and\n\t// system calls to do the actual send. This probably under-reports a bit,\n\t// but it's the best we can do.\n\tsent := time.Now()\n\n\t// Wait for response or timeout.\n\tselect {\n\tcase v := <-ackCh:\n\t\tif v.Complete == true {\n\t\t\treturn v.Timestamp.Sub(sent), nil\n\t\t}\n\tcase <-time.After(m.config.ProbeTimeout):\n\t\t// Timeout, return an error below.\n\t}\n\n\tm.logger.Printf(\"[DEBUG] memberlist: Failed UDP ping: %v (timeout reached)\", node)\n\treturn 0, NoPingResponseError{ping.Node}\n}", "func (p *peerAddr) duration() time.Duration {\n\n\t// Attempt to convert the \"next\" value (the oldest) to time.Time.\n\toldestPing, _ := p.lastPing.Next().Value.(time.Time)\n\n\t// Return the difference between the two pings.\n\treturn p.lastPing.Value.(time.Time).Sub(oldestPing)\n}", "func (m *MinikubeRunner) Status() (status string, stderr string, err error) {\n\ts := func() error {\n\t\tstatus, stderr, err = m.RunCommand(\"status --format={{.Host}} %s\", false)\n\t\tstatus = strings.TrimRight(status, \"\\n\")\n\t\tif err != nil && (status == state.None.String() || status == state.Stopped.String()) {\n\t\t\terr = nil // because https://github.com/kubernetes/minikube/issues/4932\n\t\t}\n\t\treturn err\n\t}\n\terr = retry.Expo(s, 3*time.Second, 2*time.Minute)\n\treturn status, stderr, err\n}", "func (s *Sysinfo) Update() {\n\tinfo := syscall.Sysinfo_t{}\n\terr := syscall.Sysinfo(&info)\n\tif err != nil {\n\t\tlog.Printf(\"Sysinfo call failed: %s\", err.Error())\n\t\treturn\n\t}\n\n\ts.uptime = uint64(info.Uptime)\n\ts.memTotal = info.Totalram\n\ts.memFree = info.Freeram\n\ts.memShared = info.Sharedram\n\ts.memBuffer = info.Bufferram\n\ts.swapTotal = info.Totalswap\n\ts.swapFree = info.Freeswap\n\ts.load = info.Loads\n\ts.procs = uint64(info.Procs)\n}", "func uptimeAsync(result chan *uptimeResult, configPath string) {\n\tconfigData, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tresult <- &uptimeResult{err: err}\n\t\treturn\n\t}\n\n\tconfig := &kubeconfig{}\n\tif err := yaml.Unmarshal(configData, config); err != nil {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"error: unable to unmarshal provided KUBECONFIG: %v\", err)}\n\t\treturn\n\t}\n\n\tif len(config.CurrentContext) == 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"invalid kubeconfig: empty current-context field\")}\n\t\treturn\n\t}\n\tif len(config.Contexts) == 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"invalid kubeconfig: no contexts found\")}\n\t\treturn\n\t}\n\tif len(config.Clusters) == 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"invalid kubeconfig: no clusters found\")}\n\t\treturn\n\t}\n\n\tvar context *kubeconfigContext\n\tfor _, ctx := range config.Contexts {\n\t\tif ctx.Name == config.CurrentContext {\n\t\t\tcontext = ctx\n\t\t\tbreak\n\t\t}\n\t}\n\tif context == nil {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"invalid kubeconfig: unable to find current context (%s) in provided list of contexts\", config.CurrentContext)}\n\t\treturn\n\t}\n\n\tclusterName := \"\"\n\tfor _, cluster := range config.Clusters {\n\t\tif cluster.Name == context.Context.Cluster {\n\t\t\tclusterName = cluster.Cluster.Server\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(clusterName) == 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"invalid kubeconfig: unable to find current cluster (%s) in provided list of clusters\", context.Context.Cluster)}\n\t\treturn\n\t}\n\n\thostSegs := strings.Split(clusterName, \"://\")\n\tif len(hostSegs) < 2 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"malformed cluster hostname: expecting http(s)://host.name:port format, but got %s\", clusterName)}\n\t\treturn\n\t}\n\thostSegs = strings.Split(hostSegs[1], \":\")\n\tif len(hostSegs) == 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"malformed cluster hostname: expecting http(s)://host.name:port format, but got %s\", clusterName)}\n\t\treturn\n\t}\n\thostName := hostSegs[0]\n\tusername := \"core\"\n\tstdout := bytes.NewBuffer(nil)\n\tstderr := bytes.NewBuffer(nil)\n\n\t// only attempt to perform an ssh command if hostname\n\t// does not look like an ip address, and if kubeconfig\n\t// is not located in a familiar location\n\tcmd := exec.Command(\"/usr/bin/ssh\", \"-o\", \"UserKnownHostsFile=/dev/null\", \"-o\", \"StrictHostKeyChecking=no\", fmt.Sprintf(\"%s@%s\", username, hostName), \"uptime\", \"--pretty\")\n\tipMatch := regexp.MustCompile(\"^([0-9]+(\\\\.))+[0-9]+$\")\n\tif strings.Contains(configPath, \".minishift\") || strings.Contains(configPath, \".minikube\") || ipMatch.Match([]byte(hostName)) {\n\t\tcmd = exec.Command(\"/usr/bin/uptime\", \"--pretty\")\n\t}\n\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tif err := cmd.Run(); err != nil {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"command exec error: %v: %v\", err, stderr.String())}\n\t\treturn\n\t}\n\tif len(stdout.String()) > 0 {\n\t\tresult <- &uptimeResult{result: stdout.String()}\n\t\treturn\n\t}\n\tif len(stderr.String()) > 0 {\n\t\tresult <- &uptimeResult{err: fmt.Errorf(\"error: stderr: %s\", stderr.String())}\n\t\treturn\n\t}\n\tresult <- &uptimeResult{err: fmt.Errorf(\"error: no output from command: %s\", cmd.Args)}\n}", "func (c *Client) NodeStats(ctx context.Context, n *NodeInfo) (NodeStats, error) {\n\tvar start = time.Now()\n\tvar l = c.l.With(\"node\", n)\n\n\t// retrieve details from stats API\n\ts, err := c.d.ContainerStats(ctx, n.DockerID, false)\n\tif err != nil {\n\t\tl.Errorw(\"failed to get container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tdefer s.Body.Close()\n\tb, err := ioutil.ReadAll(s.Body)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tvar stats rawContainerStats\n\tif err = json.Unmarshal(b, &stats); err != nil {\n\t\tl.Errorw(\"failed to read container stats\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// retrieve details from container inspection\n\tinfo, err := c.d.ContainerInspect(ctx, n.DockerID)\n\tif err != nil {\n\t\tl.Errorw(\"failed to inspect container\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\tcreated, err := time.Parse(time.RFC3339, info.Created)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read container detail\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to get node stats\")\n\t}\n\n\t// check disk usage\n\tusage, err := dirSize(n.DataDir)\n\tif err != nil {\n\t\tl.Errorw(\"failed to calculate disk usage\", \"error\", err)\n\t\treturn NodeStats{}, errors.New(\"failed to calculate disk usage\")\n\t}\n\n\t// get peer ID\n\tvar cfgPath = filepath.Join(n.DataDir, \"config\")\n\tpeer, err := getConfig(cfgPath)\n\tif err != nil {\n\t\tl.Errorw(\"failed to read node configuration\", \"error\", err, \"path\", cfgPath)\n\t\treturn NodeStats{}, fmt.Errorf(\"failed to get network node configuration\")\n\t}\n\n\tc.l.Debugw(\"retrieved node container data\",\n\t\t\"network_id\", n.NetworkID,\n\t\t\"docker_id\", n.DockerID,\n\t\t\"stat.duration\", time.Since(start))\n\n\treturn NodeStats{\n\t\tPeerID: peer.Identity.PeerID,\n\t\tPeerKey: peer.Identity.PrivKey,\n\t\tUptime: time.Since(created),\n\t\tStats: stats,\n\t\tDiskUsage: usage,\n\t}, nil\n}", "func GetLastRebootTime() (time.Time, error) {\n\tvar systemBootTime string\n\tout, err := exec.Command(\"cmd\", \"/c\", \"systeminfo\").Output()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to query systeminfo, err: %v\", err)\n\t\treturn time.Time{}.UTC(), err\n\t}\n\n\tsystemInfo := strings.Split(string(out), \"\\n\")\n\tfor _, systemProperty := range systemInfo {\n\t\tif strings.Contains(systemProperty, \"Boot Time\") {\n\t\t\tsystemBootTime = strings.TrimSpace(strings.Split(systemProperty, \"System Boot Time:\")[1])\n\t\t}\n\t}\n\n\tif len(strings.TrimSpace(systemBootTime)) == 0 {\n\t\tlog.Printf(\"Failed to retrieve boot time from systeminfo\")\n\t\treturn time.Time{}.UTC(), fmt.Errorf(\"Failed to retrieve boot time from systeminfo\")\n\t}\n\n\tlog.Printf(\"Boot time: %s\", systemBootTime)\n\t// The System Boot Time is in the following format \"01/02/2006, 03:04:05 PM\"\n\t// Formulate the Boot Time in the format: \"2006-01-02 15:04:05\"\n\tbootDate := strings.Split(systemBootTime, \" \")[0]\n\tbootTime := strings.Split(systemBootTime, \" \")[1]\n\tbootPM := strings.Contains(strings.Split(systemBootTime, \" \")[2], \"PM\")\n\n\tmonth := strings.Split(bootDate, \"/\")[0]\n\tif len(month) < 2 {\n\t\tmonth = \"0\" + month\n\t}\n\n\tday := strings.Split(bootDate, \"/\")[1]\n\tif len(day) < 2 {\n\t\tday = \"0\" + day\n\t}\n\n\tyear := strings.Split(bootDate, \"/\")[2]\n\tyear = strings.Trim(year, \",\")\n\thour := strings.Split(bootTime, \":\")[0]\n\thourInt, _ := strconv.Atoi(hour)\n\tmin := strings.Split(bootTime, \":\")[1]\n\tsec := strings.Split(bootTime, \":\")[2]\n\n\tif bootPM && hourInt < 12 {\n\t\thourInt += 12\n\t} else if !bootPM && hourInt == 12 {\n\t\thourInt = 0\n\t}\n\n\thour = strconv.Itoa(hourInt)\n\tsystemBootTime = year + \"-\" + month + \"-\" + day + \" \" + hour + \":\" + min + \":\" + sec\n\tlog.Printf(\"Formatted Boot time: %s\", systemBootTime)\n\n\t// Parse the boot time.\n\tlayout := \"2006-01-02 15:04:05\"\n\trebootTime, err := time.ParseInLocation(layout, systemBootTime, time.Local)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to parse boot time, err:%v\", err)\n\t\treturn time.Time{}.UTC(), err\n\t}\n\n\treturn rebootTime.UTC(), nil\n}", "func (t *targetrunner) starttime() time.Time {\n\treturn t.uxprocess.starttime\n}" ]
[ "0.8227483", "0.7692122", "0.7463235", "0.7405689", "0.73982286", "0.7378028", "0.7366554", "0.7323127", "0.71871233", "0.71538115", "0.7131715", "0.7029921", "0.7029921", "0.70038944", "0.6973613", "0.6923254", "0.6906158", "0.6869026", "0.67222804", "0.67159563", "0.669048", "0.66157585", "0.65585726", "0.6551838", "0.65124553", "0.65124553", "0.6298938", "0.62482417", "0.62238085", "0.6214388", "0.61961675", "0.6121706", "0.611493", "0.5837534", "0.57764554", "0.5731083", "0.5665305", "0.5662681", "0.5560321", "0.54149497", "0.5309481", "0.5278413", "0.5263869", "0.5258839", "0.5209171", "0.52005124", "0.5149881", "0.5109793", "0.5092023", "0.50782233", "0.50370157", "0.5018344", "0.5011798", "0.4996221", "0.49073598", "0.49052724", "0.48679647", "0.48646966", "0.48591557", "0.48096308", "0.4798991", "0.4760455", "0.4746757", "0.47435346", "0.47384354", "0.46785292", "0.46778065", "0.46601292", "0.46500948", "0.4644788", "0.46374977", "0.46300608", "0.46071127", "0.4586024", "0.4586024", "0.45666587", "0.45649132", "0.45594707", "0.45444185", "0.4543288", "0.45354688", "0.45030403", "0.44986796", "0.44898173", "0.44842726", "0.44791806", "0.44653022", "0.4460284", "0.44404873", "0.44354916", "0.44248804", "0.4422742", "0.44068", "0.4406046", "0.43995228", "0.43986747", "0.43954042", "0.43933362", "0.43849614", "0.43827924" ]
0.78871816
1
Disks list and parse the hardware information using smartctl
func (r *ResourceOracle) Disks() (d Disks, err error) { devices, err := smartctl.ListDevices() if errors.Is(err, smartctl.ErrEmpty) { // TODO: for now we allow to not have the smartctl dump of all the disks log.Warn().Err(err).Msg("smartctl did not found any disk on the system") return d, nil } if err != nil { return } var info smartctl.Info d.Devices = make([]smartctl.Info, len(devices)) for i, device := range devices { info, err = smartctl.DeviceInfo(device) if err != nil { log.Error().Err(err).Msgf("failed to get device info for: %s", device.Path) continue } d.Devices[i] = info if d.Environment == "" { d.Environment = info.Environment } if d.Tool == "" { d.Tool = info.Tool } } d.Aggregator = "0-OS smartctl aggregator" return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RunListDisk() {\n\n\t// dir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\t// if err != nil {\n\t// \tlog.Fatal(err)\n\t// \treturn\n\t// }\n\n\t// lsscsipath := path.Join(dir, \"lsscsi\")\n\t// if _, err := os.Stat(lsscsipath); os.IsNotExist(err) {\n\t// \tlsscsipath = \"lsscsi\"\n\t// }\n\tlsscsipath := \"lsscsi\"\n\tcmd := exec.Command(lsscsipath, \"-s\", \"-g\")\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttimer := time.AfterFunc(10*time.Second, func() {\n\t\tcmd.Process.Kill()\n\t})\n\n\tscanner := bufio.NewScanner(stdout)\n\tvar hddinfo []string\n\tvar hddchanged bool\n\tvar wg sync.WaitGroup\n\tfor scanner.Scan() {\n\t\tss := scanner.Text()\n\t\tfmt.Println(ss)\n\t\thddinfo = append(hddinfo, ss)\n\t\tif !DetectData.MatchKey(ss) {\n\t\t\thddchanged = true\n\t\t}\n\t\tif !DetectData.ContainsKey(ss) {\n\t\t\t//\\s Matches any white-space character.\n\t\t\tr := regexp.MustCompile(`^([\\s\\S]{13})(disk[\\s\\S]{4})([\\s\\S]{9})([\\s\\S]{17})([\\s\\S]{6})([\\s\\S]{11})([\\s\\S]{11})([\\s\\S]+)$`)\n\t\t\tdiskinfos := r.FindStringSubmatch(ss)\n\t\t\tif len(diskinfos) == 9 {\n\t\t\t\tvar dddect = NewSyncDataDetect()\n\t\t\t\tdddect.detectHDD.Locpath = strings.Trim(diskinfos[1], \" \")\n\t\t\t\tdddect.detectHDD.Type = strings.Trim(diskinfos[2], \" \")\n\t\t\t\tdddect.detectHDD.Manufacture = strings.Trim(diskinfos[3], \" \")\n\t\t\t\tdddect.detectHDD.Model = strings.Trim(diskinfos[4], \" \")\n\t\t\t\tdddect.detectHDD.Version = strings.Trim(diskinfos[5], \" \")\n\t\t\t\tdddect.detectHDD.LinuxName = strings.Trim(diskinfos[6], \" \")\n\t\t\t\tdddect.detectHDD.SGLibName = strings.Trim(diskinfos[7], \" \")\n\t\t\t\tdddect.detectHDD.Size = strings.Trim(diskinfos[8], \" \")\n\n\t\t\t\tif strings.Index(dddect.detectHDD.LinuxName, `/dev/`) == -1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t//hddchanged = true\n\t\t\t\tDetectData.AddValue(ss, dddect)\n\t\t\t\twg.Add(1)\n\t\t\t\tgo dddect.ReadDataFromSmartCtl(&wg)\n\t\t\t}\n\t\t} else {\n\t\t\tif vv, ok := DetectData.Get(ss); ok {\n\t\t\t\tif len(vv.detectHDD.UILabel) == 0 && len(vv.detectHDD.Otherinfo) == 0 {\n\t\t\t\t\twg.Add(1)\n\t\t\t\t\tgo vv.ReadDataFromSmartCtl(&wg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttimer.Stop()\n\tDetectData.RemoveOld(hddinfo)\n\n\ttime.Sleep(4 * time.Second)\n\n\tif hddchanged {\n\t\tfmt.Print(\"changed!\")\n\t\tcclist, err := configxmldata.Conf.GetCardListIndex()\n\t\tif err == nil {\n\t\t\tfor _, i := range cclist {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo SASHDDinfo.RunCardInfo(i, &wg)\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < 30; i++ {\n\t\t\tif waitTimeout(&wg, 10*time.Second) {\n\t\t\t\tfmt.Println(\"Timed out waiting for wait group\")\n\t\t\t\tMergeCalibration()\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Wait group finished\")\n\t\t\t\tMergeCalibration()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\twaitTimeout(&wg, 300*time.Second)\n\t}\n\n}", "func BuildDisks(vmProperties *mo.VirtualMachine) []Disk {\n\tdisks := make([]Disk, 0)\n\n\tdevices := vmProperties.Config.Hardware.Device\n\tfor _, device := range devices {\n\t\t// is this device a VirtualDisk?\n\t\tif virtualDisk, ok := device.(*types.VirtualDisk); ok {\n\t\t\tvar datastoreMoRef string\n\t\t\tvar datastoreName string\n\t\t\tvar backingFileName string\n\t\t\tvar diskId string\n\n\t\t\tbacking := virtualDisk.Backing.(types.BaseVirtualDeviceFileBackingInfo)\n\t\t\tbackingInfo := backing.GetVirtualDeviceFileBackingInfo()\n\t\t\tif backingInfo.Datastore != nil {\n\t\t\t\tdatastoreMoRef = backingInfo.Datastore.Value\n\t\t\t}\n\t\t\tbackingFileName = backingInfo.FileName\n\t\t\tdatastoreName = getDatastoreNameFromBacking(backingFileName)\n\n\t\t\tif virtualDisk.VDiskId != nil {\n\t\t\t\tdiskId = virtualDisk.VDiskId.Id\n\t\t\t} else {\n\t\t\t\tdiskId = virtualDisk.DiskObjectId\n\t\t\t}\n\n\t\t\tdisk := Disk{\n\t\t\t\tBackingFileName: backingFileName,\n\t\t\t\tCapacity: getDiskCapacityInBytes(virtualDisk),\n\t\t\t\tDatastoreMoRef: datastoreMoRef,\n\t\t\t\tDatastoreName: datastoreName,\n\t\t\t\tID: diskId,\n\t\t\t\tKey: virtualDisk.Key,\n\t\t\t\tName: virtualDisk.DeviceInfo.GetDescription().Label,\n\t\t\t}\n\n\t\t\tdisks = append(disks, disk)\n\t\t\tcontinue\n\t\t}\n\n\t}\n\n\treturn disks\n}", "func (ld *LocalDeviceImplement) ListDevicesDetail(device string) ([]*types.LocalDisk, error) {\n\targs := []string{\"--pairs\", \"--paths\", \"--bytes\", \"--all\", \"--output\", \"NAME,FSTYPE,MOUNTPOINT,SIZE,STATE,TYPE,ROTA,RO,PKNAME\"}\n\tif device != \"\" {\n\t\targs = append(args, device)\n\t}\n\tdevices, err := ld.Executor.ExecuteCommandWithOutput(\"lsblk\", args...)\n\tif err != nil {\n\t\tlog.Error(\"exec lsblk failed\" + err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn parseDiskString(devices), nil\n}", "func (s *Module) DiskList() ([]pkg.VDisk, error) {\n\tpools, err := s.diskPools()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar disks []pkg.VDisk\n\tfor _, pool := range pools {\n\n\t\titems, err := os.ReadDir(pool)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to list virtual disks\")\n\t\t}\n\n\t\tfor _, item := range items {\n\t\t\tif item.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinfo, err := item.Info()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"failed to get file info for '%s'\", item.Name())\n\t\t\t}\n\n\t\t\tdisks = append(disks, pkg.VDisk{\n\t\t\t\tPath: filepath.Join(pool, item.Name()),\n\t\t\t\tSize: info.Size(),\n\t\t\t})\n\t\t}\n\n\t\treturn disks, nil\n\t}\n\n\treturn disks, nil\n}", "func (client *Client) ListDisks00(request *ListDisks00Request) (response *ListDisks00Response, err error) {\n\tresponse = CreateListDisks00Response()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func ListDevices() ([]image.Device, error) {\n\tcmd := exec.Command(\"gst-device-monitor-1.0\")\n\tbuf, err := cmd.Output()\n\tif err != nil {\n\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\terr = errInstallHint\n\t\t}\n\t\treturn nil, fmt.Errorf(\"listing devices using gst-device-monitor-1.0: %v\", err)\n\t}\n\n\tvar r []device\n\tvar d *device\n\tb := bufio.NewScanner(bytes.NewReader(buf))\n\tfor b.Scan() {\n\t\ts := strings.TrimSpace(b.Text())\n\t\tif s == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif s == \"Device found:\" {\n\t\t\tif d != nil {\n\t\t\t\tr = append(r, *d)\n\t\t\t}\n\t\t\td = &device{RawCaps: []string{}, Caps: []image.DeviceCap{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tif d == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(s, \"name :\") {\n\t\t\td.Name = strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"class :\") {\n\t\t\td.DeviceClass = strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"caps :\") {\n\t\t\tcap := strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\td.RawCaps = append(d.RawCaps, cap)\n\t\t\td.inCapMode = true\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"properties:\") {\n\t\t\td.inCapMode = false\n\t\t\tcontinue\n\t\t}\n\t\tif d.inCapMode {\n\t\t\td.RawCaps = append(d.RawCaps, s)\n\t\t}\n\t\tif strings.HasPrefix(s, \"device.path =\") {\n\t\t\td.ID = strings.TrimSpace(strings.SplitN(s, \"=\", 2)[1])\n\t\t}\n\t}\n\tif err := b.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif d != nil && d.ID != \"\" {\n\t\tr = append(r, *d)\n\t}\n\n\tvar devs []image.Device\n\tfor _, d := range r {\n\t\tif d.DeviceClass != \"Video/Source\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, rc := range d.RawCaps {\n\t\t\tif !strings.HasPrefix(rc, \"video/x-raw\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmw := widthRegexp.FindStringSubmatch(rc)\n\t\t\tmh := heightRegexp.FindStringSubmatch(rc)\n\t\t\tmf := framerateRegexp.FindStringSubmatch(rc)\n\t\t\tif mw == nil || mh == nil || mf == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twidth, werr := strconv.ParseInt(mw[1], 10, 32)\n\t\t\theight, herr := strconv.ParseInt(mh[1], 10, 32)\n\t\t\tframerate, ferr := strconv.ParseInt(mf[1], 10, 32)\n\t\t\tif werr != nil || herr != nil || ferr != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif width != 0 && height != 0 && framerate != 0 {\n\t\t\t\td.Caps = append(d.Caps, image.DeviceCap{\n\t\t\t\t\tWidth: int(width),\n\t\t\t\t\tHeight: int(height),\n\t\t\t\t\tFramerate: int(framerate),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif len(d.Caps) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdistance := func(a image.DeviceCap) int {\n\t\t\treturn abs(a.Width-640)*abs(a.Height-480) + abs(a.Width-640) + abs(a.Height-480)\n\t\t}\n\n\t\tsort.Slice(d.Caps, func(i, j int) bool {\n\t\t\treturn distance(d.Caps[i]) < distance(d.Caps[j])\n\t\t})\n\n\t\tdevs = append(devs, image.Device{\n\t\t\tID: d.ID,\n\t\t\tName: d.Name,\n\t\t\tCaps: d.Caps,\n\t\t})\n\t}\n\tif len(devs) == 0 {\n\t\treturn nil, fmt.Errorf(\"no devices found\")\n\t}\n\n\treturn devs, nil\n}", "func (c *MockDisksClient) List(ctx context.Context, resourceGroupName string) ([]compute.Disk, error) {\n\tvar l []compute.Disk\n\tfor _, disk := range c.Disks {\n\t\tl = append(l, disk)\n\t}\n\treturn l, nil\n}", "func (p *redfishProvisioner) InspectHardware() (result provisioner.Result, details *metal3v1alpha1.HardwareDetails, err error) {\n\t//Could be used to check if the curent node is as per the RAID/NIC/OS etc listed in the input\n\t//TODO : Add validation code to retreievethe computer SYstem info from IDRAC and fill it.\n\t// Currently dummy data added.\n\tdetails = new(metal3v1alpha1.HardwareDetails)\n\tif p.host.Status.HardwareDetails == nil {\n\t\tp.log.Info(\"continuing inspection by setting details\")\n\t\tdetails =\n\t\t\t&metal3v1alpha1.HardwareDetails{\n\t\t\t\tRAMMebibytes: 128 * 1024,\n\t\t\t\tNIC: []metal3v1alpha1.NIC{\n\t\t\t\t\tmetal3v1alpha1.NIC{\n\t\t\t\t\t\tName: \"nic-1\",\n\t\t\t\t\t\tModel: \"virt-io\",\n\t\t\t\t\t\tMAC: \"ab:ba:ab:ba:ab:ba\",\n\t\t\t\t\t\tIP: \"192.168.100.1\",\n\t\t\t\t\t\tSpeedGbps: 1,\n\t\t\t\t\t\tPXE: true,\n\t\t\t\t\t},\n\t\t\t\t\tmetal3v1alpha1.NIC{\n\t\t\t\t\t\tName: \"nic-2\",\n\t\t\t\t\t\tModel: \"e1000\",\n\t\t\t\t\t\tMAC: \"ab:ba:ab:ba:ab:bc\",\n\t\t\t\t\t\tIP: \"192.168.100.2\",\n\t\t\t\t\t\tSpeedGbps: 1,\n\t\t\t\t\t\tPXE: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tStorage: []metal3v1alpha1.Storage{\n\t\t\t\t\tmetal3v1alpha1.Storage{\n\t\t\t\t\t\tName: \"disk-1 (boot)\",\n\t\t\t\t\t\tRotational: false,\n\t\t\t\t\t\tSizeBytes: metal3v1alpha1.TebiByte * 93,\n\t\t\t\t\t\tModel: \"Dell CFJ61\",\n\t\t\t\t\t},\n\t\t\t\t\tmetal3v1alpha1.Storage{\n\t\t\t\t\t\tName: \"disk-2\",\n\t\t\t\t\t\tRotational: false,\n\t\t\t\t\t\tSizeBytes: metal3v1alpha1.TebiByte * 93,\n\t\t\t\t\t\tModel: \"Dell CFJ61\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCPU: metal3v1alpha1.CPU{\n\t\t\t\t\tArch: \"x86_64\",\n\t\t\t\t\tModel: \"Core 2 Duo\",\n\t\t\t\t\tClockMegahertz: 3.0 * metal3v1alpha1.GigaHertz,\n\t\t\t\t\tFlags: []string{\"lm\", \"hypervisor\", \"vmx\"},\n\t\t\t\t\tCount: 1,\n\t\t\t\t},\n\t\t\t}\n\t\tp.publisher(\"InspectionComplete\", \"Hardware inspection completed\")\n\t\tp.host.SetOperationalStatus(metal3v1alpha1.OperationalStatusOK)\n\t}\n\treturn\n}", "func NewCmdDiskList() *cobra.Command {\n\treq := base.BizClient.NewDescribeUDiskRequest()\n\ttypeMap := map[string]string{\n\t\t\"DataDisk\": \"Oridinary-Data-Disk\",\n\t\t\"SystemDisk\": \"Oridinary-System-Disk\",\n\t\t\"SSDDataDisk\": \"SSD-Data-Disk\",\n\t}\n\tarkModeMap := map[string]string{\n\t\t\"Yes\": \"true\",\n\t\t\"No\": \"false\",\n\t}\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List udisk instance\",\n\t\tLong: \"List udisk instance\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfor key, val := range typeMap {\n\t\t\t\tif *req.DiskType == val {\n\t\t\t\t\t*req.DiskType = key\n\t\t\t\t}\n\t\t\t}\n\t\t\tresp, err := base.BizClient.DescribeUDisk(req)\n\t\t\tif err != nil {\n\t\t\t\tbase.HandleError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlist := []DiskRow{}\n\t\t\tfor _, disk := range resp.DataSet {\n\t\t\t\trow := DiskRow{\n\t\t\t\t\tResourceID: disk.UDiskId,\n\t\t\t\t\tName: disk.Name,\n\t\t\t\t\tGroup: disk.Tag,\n\t\t\t\t\tSize: fmt.Sprintf(\"%dGB\", disk.Size),\n\t\t\t\t\tType: typeMap[disk.DiskType],\n\t\t\t\t\tEnableDataArk: arkModeMap[disk.UDataArkMode],\n\t\t\t\t\tMountUHost: fmt.Sprintf(\"%s/%s\", disk.UHostName, disk.UHostIP),\n\t\t\t\t\tMountPoint: disk.DeviceName,\n\t\t\t\t\tState: disk.Status,\n\t\t\t\t\tCreationTime: base.FormatDate(disk.CreateTime),\n\t\t\t\t\tExpirationTime: base.FormatDate(disk.ExpiredTime),\n\t\t\t\t}\n\t\t\t\tif disk.UHostIP == \"\" {\n\t\t\t\t\trow.MountUHost = \"\"\n\t\t\t\t}\n\t\t\t\tlist = append(list, row)\n\t\t\t}\n\t\t\tif global.json {\n\t\t\t\tbase.PrintJSON(list)\n\t\t\t} else {\n\t\t\t\tbase.PrintTableS(list)\n\t\t\t}\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.SortFlags = false\n\treq.ProjectId = flags.String(\"project-id\", base.ConfigInstance.ProjectID, \"Optional. Assign project-id\")\n\treq.Region = flags.String(\"region\", base.ConfigInstance.Region, \"Optional. Assign region\")\n\treq.Zone = flags.String(\"zone\", base.ConfigInstance.Zone, \"Optional. Assign availability zone\")\n\treq.UDiskId = flags.String(\"resource-id\", \"\", \"Optional. Resource ID of the udisk to search\")\n\treq.DiskType = flags.String(\"udisk-type\", \"\", \"Optional. Optional. Type of the udisk to search. 'Oridinary-Data-Disk','Oridinary-System-Disk' or 'SSD-Data-Disk'\")\n\treq.Offset = cmd.Flags().Int(\"offset\", 0, \"Optional. Offset\")\n\treq.Limit = cmd.Flags().Int(\"limit\", 50, \"Optional. Limit\")\n\tflags.SetFlagValues(\"udisk-type\", \"Oridinary-Data-Disk\", \"Oridinary-System-Disk\", \"SSD-Data-Disk\")\n\treturn cmd\n}", "func GetVolumes(mountHost bool, mountSecret bool, instanceName string) []corev1.Volume {\n\tvar hostPathDirectoryTypeForPtr = corev1.HostPathDirectory\n\n\tvolumes := []corev1.Volume{\n\t\t{\n\t\t\tName: \"osd-monitored-logs-local\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\tName: \"osd-monitored-logs-local\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"osd-monitored-logs-metadata\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\tName: \"osd-monitored-logs-metadata\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"splunk-state\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\tPath: \"/var/lib/misc\",\n\t\t\t\t\tType: &hostPathDirectoryTypeForPtr,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif mountHost {\n\t\tvolumes = append(volumes,\n\t\t\tcorev1.Volume{\n\t\t\t\tName: \"host\",\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\tPath: \"/\",\n\t\t\t\t\t\tType: &hostPathDirectoryTypeForPtr,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t} else {\n\t\t// if we aren't mounting the host dir, we're the hf\n\t\tvar hfName = instanceName + \"-hfconfig\"\n\t\tvolumes = append(volumes,\n\t\t\tcorev1.Volume{\n\t\t\t\tName: hfName,\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: hfName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\tif mountSecret {\n\t\tvolumes = append(volumes,\n\t\t\tcorev1.Volume{\n\t\t\t\tName: config.SplunkAuthSecretName,\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tSecret: &corev1.SecretVolumeSource{\n\t\t\t\t\t\tSecretName: config.SplunkAuthSecretName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t} else {\n\t\t// if we aren't mounting the secret, we're fwding to the splunk hf\n\t\tvar internalName = instanceName + \"-internalsplunk\"\n\t\tvolumes = append(volumes,\n\t\t\tcorev1.Volume{\n\t\t\t\tName: internalName,\n\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: internalName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t}\n\n\treturn volumes\n}", "func (sdd *SyncDataDetect) ReadDataFromSmartCtl(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\t//sDevName string, hdinfo *DataDetect\n\tsDevName := sdd.detectHDD.LinuxName\n\thdinfo := sdd.detectHDD\n\tif !strings.HasPrefix(sDevName, `/dev/`) {\n\t\treturn\n\t}\n\tbOKDisk := false\n\n\tif sdd.IsRunning {\n\t\treturn\n\t}\n\tsdd.SetRunning()\n\tdefer sdd.CleanRunning()\n\n\tsdd.lock.Lock()\n\tdefer sdd.lock.Unlock()\n\n\tcmd := exec.Command(\"smartctl\", sDevName, \"-i\", \"-H\")\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttimer := time.AfterFunc(300*time.Second, func() {\n\t\tcmd.Process.Kill()\n\t})\n\n\tscanner := bufio.NewScanner(stdout)\n\tfor scanner.Scan() {\n\t\tss := scanner.Text()\n\t\tfmt.Println(ss)\n\t\tkeyvalue := strings.Split(ss, \":\")\n\t\tif len(keyvalue) == 2 {\n\t\t\tkeyvalue[0] = strings.Trim(keyvalue[0], \" \")\n\t\t\tkeyvalue[1] = strings.Trim(keyvalue[1], \" \")\n\t\t\tif _, ok := ingoreKeys[keyvalue[0]]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.EqualFold(\"Device Model\", keyvalue[0]) {\n\t\t\t\thdinfo.Model = keyvalue[1]\n\t\t\t} else if strings.EqualFold(\"Serial Number\", keyvalue[0]) {\n\t\t\t\thdinfo.Serialno = keyvalue[1]\n\t\t\t} else if strings.EqualFold(\"LU WWN Device Id\", keyvalue[0]) {\n\t\t\t\thdinfo.LuwwndevId = strings.Replace(keyvalue[1], \" \", \"\", -1)\n\t\t\t} else if strings.EqualFold(\"Firmware Version\", keyvalue[0]) {\n\t\t\t\thdinfo.Version = keyvalue[1]\n\t\t\t} else if strings.EqualFold(\"Logical Unit id\", keyvalue[0]) {\n\t\t\t\tv := strings.Replace(keyvalue[1], \"-\", \"\", -1)\n\t\t\t\tv = strings.Replace(v, \"0x\", \"\", -1)\n\t\t\t\thdinfo.Otherinfo[\"LogicalUnitID\"] = v\n\t\t\t} else if strings.EqualFold(hdinfo.Size, \"-\") && strings.EqualFold(\"User Capacity\", keyvalue[0]) {\n\t\t\t\tmatch := regexp.MustCompile(`^.*?\\[(.*?)\\]$`)\n\t\t\t\tsize := match.FindStringSubmatch(keyvalue[1])\n\t\t\t\tif len(size) > 1 {\n\t\t\t\t\thdinfo.Size = strings.Replace(size[1], \" \", \"\", -1)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif strings.EqualFold(keyvalue[0], \"SMART Status command failed\") {\n\t\t\t\t\thdinfo.Otherinfo[\"HD-health\"] = keyvalue[1]\n\t\t\t\t} else if strings.EqualFold(keyvalue[0], \"SMART overall-health self-assessment test result\") ||\n\t\t\t\t\tstrings.EqualFold(keyvalue[0], \"SMART Health Status\") ||\n\t\t\t\t\tstrings.EqualFold(keyvalue[0], \"Read SMART Data failed\") {\n\t\t\t\t\tk := \"HD-health\"\n\t\t\t\t\tif _, ok := hdinfo.Otherinfo[k]; !ok {\n\t\t\t\t\t\thdinfo.Otherinfo[k] = keyvalue[1]\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thdinfo.Otherinfo[keyvalue[0]] = keyvalue[1]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\ttimer.Stop()\n\tif v, ok := hdinfo.Otherinfo[\"HD-health\"]; ok {\n\t\tif strings.EqualFold(v, \"OK\") || strings.EqualFold(v, \"PASSED\") {\n\t\t\tbOKDisk = true\n\t\t}\n\t}\n\n\tif bOKDisk {\n\t\tcmd = exec.Command(\"smartctl\", sDevName, \"-A\")\n\t\tstdout, err = cmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := cmd.Start(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\ttimer := time.AfterFunc(300*time.Second, func() {\n\t\t\tcmd.Process.Kill()\n\t\t})\n\n\t\tscanner := bufio.NewScanner(stdout)\n\t\tvar badsectors int\n\t\tfor scanner.Scan() {\n\t\t\tss := scanner.Text()\n\t\t\tkeyvalue := strings.Split(ss, \":\")\n\t\t\tif len(keyvalue) == 2 {\n\t\t\t\tkeyvalue[0] = strings.Trim(keyvalue[0], \" \")\n\t\t\t\tkeyvalue[1] = strings.Trim(keyvalue[1], \" \")\n\t\t\t\tif _, ok := ingoreKeys[keyvalue[0]]; ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif strings.EqualFold(\"Elements in grown defect list\", keyvalue[0]) {\n\t\t\t\t\thdinfo.Otherinfo[\"badsectors\"] = keyvalue[1]\n\t\t\t\t} else if strings.EqualFold(\"Non-medium error count\", keyvalue[0]) {\n\t\t\t\t\thdinfo.Otherinfo[\"Nonmediumerrorcnt\"] = keyvalue[1]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr := regexp.MustCompile(`^\\s*(\\d+)\\s+(\\S+)\\s+(0x[0-9a-fA-F]{4})\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s*`)\n\t\t\t\tfields := r.FindStringSubmatch(ss)\n\t\t\t\tif len(fields) == 11 {\n\t\t\t\t\tATTRIBUTE_NAME := fields[2]\n\t\t\t\t\tRAW_VALUE := fields[10]\n\t\t\t\t\thdinfo.Otherinfo[ATTRIBUTE_NAME] = RAW_VALUE\n\n\t\t\t\t\tif strings.EqualFold(\"Reallocated_Sector_Ct\", ATTRIBUTE_NAME) ||\n\t\t\t\t\t\tstrings.EqualFold(\"Current_Pending_Sector\", ATTRIBUTE_NAME) {\n\t\t\t\t\t\taa, err := strconv.Atoi(strings.Trim(RAW_VALUE, \" \"))\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tbadsectors += aa\n\t\t\t\t\t\t}\n\t\t\t\t\t\thdinfo.Otherinfo[\"badsectors\"] = strconv.Itoa(badsectors)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttimer.Stop()\n\t}\n}", "func BuildNics(vmProperties *mo.VirtualMachine) []Nic {\n\tnics := make([]Nic, 0)\n\n\tdevices := vmProperties.Config.Hardware.Device\n\tfor _, device := range devices {\n\t\t// is this device a VirtualEthernetCard?\n\t\tvar virtualNetwork *types.VirtualEthernetCard\n\t\tswitch v := device.(type) {\n\t\tcase *types.VirtualE1000:\n\t\t\tvirtualNetwork = &v.VirtualEthernetCard\n\t\tcase *types.VirtualE1000e:\n\t\t\tvirtualNetwork = &v.VirtualEthernetCard\n\t\tcase *types.VirtualVmxnet:\n\t\t\tvirtualNetwork = &v.VirtualEthernetCard\n\t\tcase *types.VirtualVmxnet2:\n\t\t\tvirtualNetwork = &v.VirtualEthernetCard\n\t\tcase *types.VirtualVmxnet3:\n\t\t\tvirtualNetwork = &v.VirtualEthernetCard\n\t\t}\n\t\tif virtualNetwork != nil && virtualNetwork.Backing != nil {\n\t\t\tvar network string\n\t\t\tvar dvportgroup string\n\t\t\tvar name string\n\n\t\t\tswitch backing := virtualNetwork.Backing.(type) {\n\t\t\tcase *types.VirtualEthernetCardNetworkBackingInfo:\n\t\t\t\tif backing.Network != nil {\n\t\t\t\t\tnetwork = backing.Network.Value\n\t\t\t\t}\n\t\t\t\t// despite being called DeviceName, this is actually\n\t\t\t\t// the name of the Network the device is attached to,\n\t\t\t\t// e.g. \"VM Network\"\n\t\t\t\tname = backing.DeviceName\n\t\t\tcase *types.VirtualEthernetCardDistributedVirtualPortBackingInfo:\n\t\t\t\tdvportgroup = backing.Port.PortgroupKey\n\t\t\t\tdesc := virtualNetwork.DeviceInfo.GetDescription()\n\t\t\t\tif desc != nil {\n\t\t\t\t\t// this is the actual device name, e.g. \"ethernet-0\"\n\t\t\t\t\tname = desc.Label\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnic := Nic{\n\t\t\t\tName: name,\n\t\t\t\tMac: virtualNetwork.MacAddress,\n\t\t\t\tNetwork: network,\n\t\t\t\tDVPortGroup: dvportgroup,\n\t\t\t}\n\t\t\tnics = append(nics, nic)\n\t\t}\n\t}\n\treturn nics\n}", "func ListOS() error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to, _, err := client.OperatingSystems.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(o)\n\treturn e\n}", "func (sys *Sys) GetDeviceList() ([]string, error) {\n\tlog.Debugln(\"GetDeviceList ENTER\")\n\n\tlist := []string{}\n\n\toutputCmd := \"fdisk -l | grep \\\\/dev\\\\/\"\n\toutput, err := sys.run.CommandOutput(outputCmd)\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to get device list. Err:\", err)\n\t\tlog.Debugln(\"GetDeviceList LEAVE\")\n\t\treturn list, err\n\t}\n\n\tbuffer := bytes.NewBufferString(output)\n\tfor {\n\t\tstr, err := buffer.ReadString('\\n')\n\n\t\tneedles, errRegex := sys.str.RegexMatch(str, \"Disk (/dev/.*): \")\n\t\tif errRegex != nil {\n\t\t\tlog.Warnln(\"RegexMatch Failed. Err:\", err)\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif len(needles) != 2 {\n\t\t\tfmt.Println(\"Incorrect output size:\", len(needles))\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tdevice := needles[1]\n\t\tlog.Debugln(\"Device Found:\", device)\n\n\t\tlist = append(list, device)\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Debugln(\"GetDeviceList Succeeded. Device Count:\", len(list))\n\tlog.Debugln(\"GetDeviceList LEAVE\")\n\n\treturn list, nil\n}", "func (s *Module) shutdownDisks(vm bool) {\n\tfor _, set := range [][]filesystem.Pool{s.ssds, s.hdds} {\n\t\tfor _, pool := range set {\n\t\t\tdevice := pool.Device()\n\t\t\tlog.Debug().Msgf(\"checking device: %s\", device.Path)\n\t\t\ton, err := checkDiskPowerStatus(device.Path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Err(err).Msgf(\"error occurred while checking disk power status\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, err = pool.Mounted()\n\t\t\tif err == nil || !on {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif vm {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Debug().Msgf(\"shutting down device %s because it is not mounted and the device is on\", device.Path)\n\t\t\terr = pool.Shutdown()\n\t\t\tif err != nil {\n\t\t\t\tlog.Err(err).Msgf(\"failed to shutdown device %s\", device.Path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *LsblkDisks) parse(reader io.Reader) *LsblkDisks {\n\n\tscanner := bufio.NewScanner(reader)\n\n\tre := regexp.MustCompile(`([[:alpha:]]+(?:\\d+p)?)([\\d]+)`) // sda or sda1 or mmcblk0 or mmcblk0p1\n\n\tvar disk *LsblkDisk\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\telements := strings.Split(line, \" \")\n\n\t\tif elements[5] == \"disk\" {\n\t\t\tif disk != nil {\n\t\t\t\td.Disks[disk.Name] = disk\n\t\t\t}\n\t\t\tdisk = NewLsblkDisk(elements[0])\n\t\t\tcontinue\n\t\t} else if elements[5] == \"part\" {\n\t\t\tmatches := re.FindStringSubmatch(elements[0])\n\t\t\tpartitionNumberString := matches[2]\n\t\t\tpartitionNumber, _ := strconv.Atoi(partitionNumberString)\n\t\t\tpartition := NewLsblkPartition()\n\t\t\tsize, _ := strconv.ParseInt(elements[3], 10, 64)\n\t\t\tpartition.Name, partition.Number, partition.MajMin, partition.Rm, partition.Size, partition.Ro, partition.Type, partition.Mountpoint =\n\t\t\t\tmatches[1]+matches[2], partitionNumber, elements[1], elements[2], size, elements[4], elements[5], elements[6]\n\t\t\tdisk.Partitions[partitionNumber] = partition\n\t\t}\n\n\t}\n\tif disk != nil {\n\t\td.Disks[disk.Name] = disk\n\t}\n\n\treturn d\n}", "func parseDevices(r io.Reader) (devices []storage.Device, err error) {\n\t// columnName is the output column for device name\n\tconst columnName = \"NAME\"\n\t// columnType is the output column for device type\n\tconst columnType = \"TYPE\"\n\t// columnSize is the output column for device size\n\tconst columnSize = \"SIZE\"\n\t// columnFilesystemType is the output column for mounted filesystem type\n\tconst columnFilesystemType = \"FSTYPE\"\n\t// columnParentName is the output column for internal kernel parent device name\n\tconst columnParentName = \"PKNAME\"\n\n\ts := bufio.NewScanner(r)\n\ts.Split(bufio.ScanLines)\n\tp := &parser{}\n\tdeviceCache := make(map[string]storage.Device)\n\tfor s.Scan() {\n\t\tcolumns := map[string]string{}\n\t\tline := strings.TrimSpace(s.Text())\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tp.scanner.Init(strings.NewReader(line))\n\t\tp.next()\n\t\tfor p.token != scanner.EOF {\n\t\t\tattr := p.parseAttribute()\n\t\t\tif len(attr.value) > 0 {\n\t\t\t\tcolumns[attr.name] = attr.value\n\t\t\t}\n\t\t}\n\t\tif len(p.errors) > 0 {\n\t\t\tp.errors = append(p.errors, trace.Errorf(\"failed to parse %s\", line))\n\t\t\treturn nil, trace.NewAggregate(p.errors...)\n\t\t}\n\t\tdeviceType := storage.DeviceType(columns[columnType])\n\t\tif deviceType == storage.DeviceDisk || deviceType == storage.DevicePartition {\n\t\t\tdevicePath := filepath.Join(\"/dev\", columns[columnName])\n\t\t\tparentName, hasParent := columns[columnParentName]\n\n\t\t\tif deviceType == storage.DevicePartition && hasParent {\n\t\t\t\tdelete(deviceCache, filepath.Join(\"/dev\", parentName))\n\t\t\t}\n\n\t\t\tif _, hasFilesystem := columns[columnFilesystemType]; hasFilesystem {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsize, err := strconv.ParseUint(columns[columnSize], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tlog.Infof(\"invalid size %v for device %v\", columns[columnSize], devicePath)\n\t\t\t} else {\n\t\t\t\tsize = size >> 20 // Mbytes\n\t\t\t}\n\n\t\t\tdeviceCache[devicePath] = storage.Device{Name: storage.DeviceName(devicePath), Type: deviceType, SizeMB: size}\n\t\t}\n\t}\n\tfor _, device := range deviceCache {\n\t\tdevices = append(devices, device)\n\t}\n\treturn devices, nil\n}", "func (r *VmwareMapper) buildDisks() error {\n\tif r.disks != nil {\n\t\treturn nil\n\t}\n\tdisks := BuildDisks(r.vmProperties)\n\tr.disks = &disks\n\treturn nil\n}", "func Mkfs(idPart string, Type string) {\n\t//Obtenemos la particion a partir del id\n\tpath, mountedPart, err := searchPartition(idPart)\n\tif err != nil {\n\t\treturn\n\t}\n\t//Obtenemos el file del disco\n\tfile, _, err := readFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\t//Definimos el tipo de particion que es\n\tpartitionType := typeOf(mountedPart.partition)\n\tvar primaryPartition partition\n\tvar logicalPartition extendedBootRecord\n\tswitch partitionType {\n\tcase 0:\n\t\tprimaryPartition = mountedPart.partition.(partition)\n\tcase 1:\n\t\tlogicalPartition = mountedPart.partition.(extendedBootRecord)\n\t}\n\t//Tamaños de las estruturas\n\tvar partitionSize int64\n\t//Inicio de la particon\n\tvar partitionStart int64\n\t//Nombre de la particion\n\tvar partitionName string\n\t//Trabajamos con la particion primaria\n\tif primaryPartition.Status != 0 {\n\t\tpartitionSize = primaryPartition.Size\n\t\tpartitionStart = primaryPartition.Start\n\t\tpartitionName = strings.Replace(string(primaryPartition.Name[:]), \"\\x00\", \"\", -1)\n\t} else { //Trabajos con la particion logica\n\t\tpartitionSize = logicalPartition.Size - int64(binary.Size(extendedBootRecord{}))\n\t\tpartitionStart = logicalPartition.Start\n\t\tpartitionName = strings.Replace(string(logicalPartition.Name[:]), \"\\x00\", \"\", -1)\n\t}\n\t//Aplicamos la formateada full de la particion\n\twriteFormat(file, partitionStart, partitionSize)\n\t//Creamos el superbloque\n\tsb := createSB(partitionName, partitionSize, partitionStart)\n\t//Procedemos a escribir en el disco el superboot asignado a esa particion\n\twriteSB(file, partitionStart, &sb)\n\t//[a] Creamos la carpeta '/'\n\ttimestamp := time.Now().Format(\"2006-01-02 15:04:05\")\n\tfolder := virtualDirectoryTree{\n\t\tSubdirectories: [6]int64{-1, -1, -1, -1, -1, -1},\n\t\tPrDirectoryDetail: 0,\n\t\tPrVirtualDirectoryTree: -1,\n\t}\n\tcopy(folder.CreatedAt[:], timestamp)\n\tcopy(folder.DirectoryName[:], \"/\")\n\t//Escribimos el arbol virtual de directorio de '/'\n\twriteVDT(file, sb.PrDirectoryTree, &folder)\n\t//Reescribimos el bitmap de arbol virtual de directorios\n\tbitMapVDT := []byte{'1'}\n\twriteBitmap(file, sb.PrDirectoryTreeBitmap, bitMapVDT)\n\t//[b] Creamos el detalle directorio de la carpeta '/'\n\tdd := structDD()\n\t//Escribimos el arbol virtual de directorio de '/'\n\twriteDD(file, sb.PrDirectoryDetail, &dd)\n\t//Reescribimos el bitmap de detellae de directorio\n\tbitMapDD := []byte{'1'}\n\twriteBitmap(file, sb.PrDirectoryDetailBitmap, bitMapDD)\n\tfile.Close()\n\tfmt.Println(\"[-] Formateo exitoso.\")\n}", "func (d *driverInfo) List() ([]*Volume, error) {\n\tvar volumes []*Volume\n\n\tfor _, vol := range d.volumes {\n\t\tvolumes = append(volumes, vol)\n\t}\n\n\treturn volumes, nil\n}", "func ListDevices() {\n\tledger.ListOasisDevices(ListingDerivationPath)\n}", "func List(d Driver) (*volume.ListResponse, error) {\n\tlog.Debugf(\"Entering List\")\n\td.GetLock().Lock()\n\tdefer d.GetLock().Unlock()\n\tvar vols []*volume.Volume\n\tfor name, v := range d.GetVolumes() {\n\t\tlog.Debugf(\"Volume found: %s\", v)\n\t\tm, err := getMount(d, v.GetMount())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvols = append(vols, &volume.Volume{Name: name, Status: v.GetStatus(), Mountpoint: m.GetPath()})\n\t}\n\treturn &volume.ListResponse{Volumes: vols}, nil\n}", "func Disk(pt ...bool) ([]*disk.UsageStat, error) {\n\tvar ptBool bool\n\tif len(pt) > 0 {\n\t\tptBool = pt[0]\n\t}\n\n\tvar usage []*disk.UsageStat\n\tparts, err := disk.Partitions(ptBool)\n\n\tfor _, part := range parts {\n\t\tuse, err := disk.Usage(part.Mountpoint)\n\t\tif err != nil {\n\t\t\treturn usage, err\n\t\t}\n\t\tusage = append(usage, use)\n\t\t// printUsage(use)\n\t}\n\n\treturn usage, err\n}", "func (r Virtual_Disk_Image) GetSupportedHardware() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Disk_Image\", \"getSupportedHardware\", nil, &r.Options, &resp)\n\treturn\n}", "func (cli *CLI) SystemList() {\n\tlist := nbv1.NooBaaList{}\n\terr := cli.Client.List(cli.Ctx, nil, &list)\n\tif meta.IsNoMatchError(err) {\n\t\tcli.Log.Warningf(\"CRD not installed.\\n\")\n\t\treturn\n\t}\n\tutil.Panic(err)\n\tif len(list.Items) == 0 {\n\t\tcli.Log.Printf(\"No systems found.\\n\")\n\t\treturn\n\t}\n\ttable := (&util.PrintTable{}).AddRow(\n\t\t\"NAMESPACE\",\n\t\t\"NAME\",\n\t\t\"PHASE\",\n\t\t\"MGMT-ENDPOINTS\",\n\t\t\"S3-ENDPOINTS\",\n\t\t\"IMAGE\",\n\t\t\"AGE\",\n\t)\n\tfor i := range list.Items {\n\t\ts := &list.Items[i]\n\t\ttable.AddRow(\n\t\t\ts.Namespace,\n\t\t\ts.Name,\n\t\t\tstring(s.Status.Phase),\n\t\t\tfmt.Sprint(s.Status.Services.ServiceMgmt.NodePorts),\n\t\t\tfmt.Sprint(s.Status.Services.ServiceS3.NodePorts),\n\t\t\ts.Status.ActualImage,\n\t\t\tsince(s.ObjectMeta.CreationTimestamp.Time),\n\t\t)\n\t}\n\tfmt.Print(table.String())\n}", "func bootstrapDisks(disks []string) ([]StorageAPI, error) {\n\tstorageDisks := make([]StorageAPI, len(disks))\n\tfor index, disk := range disks {\n\t\tvar err error\n\t\t// Intentionally ignore disk not found errors while\n\t\t// initializing POSIX, so that we have successfully\n\t\t// initialized posix Storage. Subsequent calls to XL/Erasure\n\t\t// will manage any errors related to disks.\n\t\tstorageDisks[index], err = newStorageLayer(disk)\n\t\tif err != nil && err != errDiskNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn storageDisks, nil\n}", "func (h *DeviceHandler) DeviceList(ctx context.Context, sessionID int) ([]keybase1.Device, error) {\n\tuis := libkb.UIs{\n\t\tLogUI: h.getLogUI(sessionID),\n\t\tSessionID: sessionID,\n\t}\n\teng := engine.NewDevList(h.G())\n\tm := libkb.NewMetaContext(ctx, h.G()).WithUIs(uis)\n\tif err := engine.RunEngine2(m, eng); err != nil {\n\t\treturn nil, err\n\t}\n\treturn eng.List(), nil\n}", "func ListPartitions(dev string) ([]Partition, error) {\n\tcmd := exec.Command(\"parted\", \"-m\", dev, \"unit\", \"B\", \"print\", \"free\")\n\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"list paritions in %s: %s\", dev, utils.OneLine(out))\n\t}\n\n\tvar parts []Partition\n\n\tfor _, l := range strings.Split(string(out), \"\\n\") {\n\t\tif len(l) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif l[1] != ':' {\n\t\t\tcontinue\n\t\t}\n\n\t\tt := strings.Split(l[:len(l)-1], \":\")\n\t\tif len(t) < 5 {\n\t\t\treturn nil, fmt.Errorf(\"list partitions in %s: invalid output from parted\", dev)\n\t\t}\n\n\t\tvar p Partition\n\n\t\tif v, err := strconv.Atoi(t[0]); err == nil {\n\t\t\tp.Number = v\n\t\t}\n\t\tif v, err := strconv.ParseInt(t[1][:len(t[1])-1], 10, 64); err == nil {\n\t\t\tp.Start = uint64(v)\n\t\t}\n\t\tif v, err := strconv.ParseInt(t[2][:len(t[2])-1], 10, 64); err == nil {\n\t\t\tp.End = uint64(v)\n\t\t}\n\t\tif v, err := strconv.ParseInt(t[3][:len(t[3])-1], 10, 64); err == nil {\n\t\t\tp.Size = uint64(v)\n\t\t}\n\n\t\tp.Filesystem = t[4]\n\n\t\tif p.Filesystem == \"free\" {\n\t\t\tp.Number = 0\n\t\t}\n\n\t\tparts = append(parts, p)\n\t}\n\n\treturn parts, nil\n}", "func initStorageDisks(endpoints EndpointList) ([]StorageAPI, error) {\n\t// Bootstrap disks.\n\tstorageDisks := make([]StorageAPI, len(endpoints))\n\tfor index, endpoint := range endpoints {\n\t\t// Intentionally ignore disk not found errors. XL is designed\n\t\t// to handle these errors internally.\n\t\tstorage, err := newStorageAPI(endpoint)\n\t\tif err != nil && err != errDiskNotFound {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorageDisks[index] = storage\n\t}\n\treturn storageDisks, nil\n}", "func (d *DiskStorage) List() ([]interface{}, error) {\n\treturn d.memory.List()\n}", "func (c *TestClient) ListDisks(project, zone string, opts ...ListCallOption) ([]*compute.Disk, error) {\n\tif c.ListDisksFn != nil {\n\t\treturn c.ListDisksFn(project, zone, opts...)\n\t}\n\treturn c.client.ListDisks(project, zone, opts...)\n}", "func NewListDisksOK() *ListDisksOK {\n\treturn &ListDisksOK{}\n}", "func transOsDisk(data map[string]*HttpGetRes) (res []osDisk) {\n\tnodeFilesystemSize := *data[\"nodeFilesystemSize\"]\n\n\tif nodeFilesystemSize.Status == requestSuccess {\n\t\tresult := nodeFilesystemSize.Data.Result\n\t\tfor _, val := range result {\n\t\t\ttotalSize, err := handleSizeUnit(val.Value.value, \"GB\")\n\t\t\t// build runtime error msg\n\t\t\tif e, disk := checkError(err); e{\n\t\t\t\tres = append(res, disk)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//get file system free info by instance\n\t\t\tinstanceRes, err := helpTransDisk(data[\"nodeFilesystemFree\"], val.Metric[\"instance\"])\n\t\t\tif e, disk := checkError(err); e{\n\t\t\t\tres = append(res, disk)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// all check pass\n\t\t\tfreeSize, err := handleSizeUnit(instanceRes.Value.value, \"GB\")\n\t\t\t// build runtime error msg\n\t\t\tif e, disk := checkError(err); e{\n\t\t\t\tres = append(res, disk)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tuseRate := useRate(totalSize, freeSize, 3)\n\t\t\tosDisk := osDisk{\n\t\t\t\tStatus: nodeFilesystemSize.Status,\n\t\t\t\tInstance: val.Metric[\"instance\"],\n\t\t\t\tTotalSize: totalSize,\n\t\t\t\tFreeSize: freeSize,\n\t\t\t\tUsedRate: useRate,\n\t\t\t\tMetricStatus: osDiskMetricStatus(useRate),\n\t\t\t\tDevice: val.Metric[\"device\"],\n\t\t\t\tFstype: val.Metric[\"fstype\"],\n\t\t\t}\n\t\t\tres = append(res, osDisk)\n\t\t}\n\t} else {\n\t\tosDisk := osDisk{\n\t\t\tStatus: nodeFilesystemSize.Status,\n\t\t\tMetricStatus: metricStatusBad,\n\t\t\tErrMsg: nodeFilesystemSize.Message,\n\t\t}\n\t\tres = append(res, osDisk)\n\t}\n\n\treturn res\n}", "func (t *Template) GetDisks() []shared.Disk {\n\n\tvecs := t.GetVectors(string(shared.DiskVec))\n\tdisks := make([]shared.Disk, len(vecs))\n\n\tfor i, v := range vecs {\n\t\tdisks[i] = shared.Disk{*v}\n\t}\n\n\treturn disks\n}", "func getNbdDeviceList() ([]string, error) {\n\tif nbdEnabled, _ := checkNbdModule(); !nbdEnabled {\n\t\terr := loadNbd()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcmd := exec.Command(\"bash\", \"-c\", \"ls /dev/nbd*\")\n\toba, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tostr := string(oba)\n\n\t//now split the results on space...\n\n\toarr := strings.Split(ostr, \"\\n\")\n\n\tresArr := []string{}\n\tfor _, item := range oarr {\n\t\tif len(item) > 0 {\n\t\t\tmatched, _ := regexp.Match(`^/dev/nbd\\d+$`, []byte(item))\n\t\t\tif matched {\n\t\t\t\tresArr = append(resArr, item)\n\t\t\t\t//quick chown...\n\t\t\t\tcmd := vutils.Exec.CreateAsyncCommand(\"chown\", false, fmt.Sprintf(\"%d\", UID), item).Sudo()\n\t\t\t\tif err := cmd.StartAndWait(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn resArr, nil\n}", "func (m *MachineScope) DiskSpecs() []azure.ResourceSpecGetter {\n\tdiskSpecs := make([]azure.ResourceSpecGetter, 1+len(m.AzureMachine.Spec.DataDisks))\n\tdiskSpecs[0] = &disks.DiskSpec{\n\t\tName: azure.GenerateOSDiskName(m.Name()),\n\t\tResourceGroup: m.ResourceGroup(),\n\t}\n\n\tfor i, dd := range m.AzureMachine.Spec.DataDisks {\n\t\tdiskSpecs[i+1] = &disks.DiskSpec{\n\t\t\tName: azure.GenerateDataDiskName(m.Name(), dd.NameSuffix),\n\t\t\tResourceGroup: m.ResourceGroup(),\n\t\t}\n\t}\n\treturn diskSpecs\n}", "func getDeviceList() *[]device {\n\tdevices := make([]device, 0)\n\n\tfor _, group := range Conf.DevGroups {\n\n\t\t// for current group, append devices to the list\n\t\tfor i := 1; i <= group.DeviceNum; i++ {\n\t\t\tdevices = append(devices, device{group.Prefix + strconv.Itoa(i), group.Firmware, false, group.IoTHub})\n\t\t}\n\t}\n\n\treturn &devices\n}", "func GetDevices() (devices []storage.Device, err error) {\n\tvar out []byte\n\tout, err = exec.Command(\"lsblk\", \"--output=NAME,TYPE,SIZE,FSTYPE,PKNAME\", \"-P\", \"--bytes\", \"-I\",\n\t\tstrings.Join(supportedDeviceTypes, \",\")).Output()\n\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\terr = trace.Wrap(err, \"lsblk error=%v, stderr=%q, out=%q\", exitErr, exitErr.Stderr, out)\n\t\treturn nil, err\n\t} else if err != nil {\n\t\treturn nil, trace.Wrap(err, \"failed to list block devices: error=%v, output=%s\", err, out)\n\t}\n\n\tdevices, err = parseDevices(bytes.NewReader(out))\n\tif err != nil {\n\t\terr = trace.Wrap(err, \"error parsing block device list: lsblk=%q : error=%v\", out, err)\n\t}\n\n\treturn devices, err\n}", "func GetDisksToBeFormatted(inventory *models.Inventory) []*models.Disk {\n\tformatDisks := make([]*models.Disk, 0, len(inventory.Disks))\n\n\tskipDriveTypes := []string{string(models.DriveTypeFC), string(models.DriveTypeISCSI), string(models.DriveTypeLVM)}\n\tfor _, disk := range inventory.Disks {\n\t\tdiskRemovable := disk.Removable || strings.Contains(disk.ByPath, \"mmcblk\") //mmc devices should be treated as removable\n\n\t\tif disk.Bootable && !diskRemovable && !funk.Contains(skipDriveTypes, string(disk.DriveType)) && !disk.IsInstallationMedia {\n\t\t\tformatDisks = append(formatDisks, disk)\n\t\t}\n\t}\n\n\treturn formatDisks\n}", "func partitionOSD(context *clusterd.Context, cfg *osdConfig) (*devicePartInfo, error) {\n\tdataDetails, err := getDataPartitionDetails(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// zap/clear all existing partitions on the device\n\terr = sys.RemovePartitions(dataDetails.Device, context.Executor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to zap partitions on metadata device /dev/%s: %+v\", dataDetails.Device, err)\n\t}\n\n\t// create the partitions on the device\n\terr = sys.CreatePartitions(dataDetails.Device, cfg.partitionScheme.GetPartitionArgs(), context.Executor)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to partition /dev/%s. %+v\", dataDetails.Device, err)\n\t}\n\n\tvar devPartInfo *devicePartInfo\n\tif cfg.partitionScheme.StoreType == config.Filestore {\n\t\t// the OSD is using filestore, create a filesystem for the device (format it) and mount it under config root\n\t\tdoFormat := true\n\t\tdevPartInfo, err = prepareFilestoreDevice(context, cfg, doFormat)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// save the partition scheme entry to disk now that it has been committed\n\tsavedScheme, err := config.LoadScheme(cfg.kv, cfg.storeName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load the saved partition scheme: %+v\", err)\n\t}\n\tsavedScheme.Entries = append(savedScheme.Entries, cfg.partitionScheme)\n\tif err := savedScheme.SaveScheme(cfg.kv, cfg.storeName); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to save partition scheme: %+v\", err)\n\t}\n\n\t// update the uuid of the disk in the inventory in memory\n\tlogger.Debugf(\"Updating disk uuid %s on device %s\", dataDetails.DiskUUID, dataDetails.Device)\n\tfor _, disk := range context.Devices {\n\t\tif disk.Name == dataDetails.Device {\n\t\t\tlogger.Debugf(\"Updated uuid on device %s\", dataDetails.Device)\n\t\t\tdisk.UUID = dataDetails.DiskUUID\n\t\t}\n\t}\n\n\treturn devPartInfo, nil\n}", "func (s *Simple) DiskInfo(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CPUInfoArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.GuestID == \"\" {\n\t\treturn nil, nil, errors.New(\"missing guest_id\")\n\t}\n\n\tresult := &DiskInfoResult{\n\t\t&DiskInfo{\n\t\t\tDevice: \"vda1\",\n\t\t\tSize: 10 * (1024 * 1024 * 1024), // 10 GB in bytes\n\t\t},\n\t}\n\n\treturn result, nil, nil\n}", "func ListVdisks(cluster ardb.StorageCluster, pred func(vdiskID string) bool) ([]string, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tserverCh, err := cluster.ServerIterator(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttype serverResult struct {\n\t\tids []string\n\t\terr error\n\t}\n\tresultCh := make(chan serverResult)\n\n\tvar action listVdisksAction\n\tif pred == nil {\n\t\taction.filter = filterListedVdiskID\n\t} else {\n\t\taction.filter = func(str string) (string, bool) {\n\t\t\tstr, ok := filterListedVdiskID(str)\n\t\t\tif !ok {\n\t\t\t\treturn \"\", false\n\t\t\t}\n\t\t\treturn str, pred(str)\n\t\t}\n\t}\n\n\tvar serverCount int\n\tvar reply interface{}\n\tfor server := range serverCh {\n\t\tserver := server\n\t\tgo func() {\n\t\t\tvar result serverResult\n\t\t\tlog.Infof(\"listing all vdisks stored on %v\", server.Config())\n\t\t\treply, result.err = server.Do(action)\n\t\t\tif result.err == nil && reply != nil {\n\t\t\t\t// [NOTE] this line of code relies on the fact that our\n\t\t\t\t// custom `listVdisksAction` type returns a `[]string` value as a reply,\n\t\t\t\t// as soon as that logic changes, this line will start causing trouble.\n\t\t\t\tresult.ids = reply.([]string)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase resultCh <- result:\n\t\t\tcase <-ctx.Done():\n\t\t\t}\n\t\t}()\n\t\tserverCount++\n\t}\n\n\t// collect the ids from all servers within the given cluster\n\tvar ids []string\n\tvar result serverResult\n\tfor i := 0; i < serverCount; i++ {\n\t\tresult = <-resultCh\n\t\tif result.err != nil {\n\t\t\t// return early, an error has occured!\n\t\t\treturn nil, result.err\n\t\t}\n\t\tids = append(ids, result.ids...)\n\t}\n\n\tif len(ids) <= 1 {\n\t\treturn ids, nil // nothing to do\n\t}\n\n\t// sort and dedupe\n\tsort.Strings(ids)\n\tids = dedupStrings(ids)\n\n\treturn ids, nil\n}", "func (r Virtual_Disk_Image) GetBlockDevices() (resp []datatypes.Virtual_Guest_Block_Device, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Disk_Image\", \"getBlockDevices\", nil, &r.Options, &resp)\n\treturn\n}", "func (srv *VolumeService) List() ([]api.Volume, error) {\n\treturn srv.provider.ListVolumes()\n}", "func LoadDisk(device string) ([]*boot.MultibootImage, []*mount.MountPoint, error) {\n\topts5, mp5, err5 := mountPartition(device, 5)\n\topts6, mp6, err6 := mountPartition(device, 6)\n\tif err5 != nil && err6 != nil {\n\t\treturn nil, nil, fmt.Errorf(\"could not mount or read either partition 5 (%v) or partition 6 (%v)\", err5, err6)\n\t}\n\tvar mps []*mount.MountPoint\n\tif mp5 != nil {\n\t\tmps = append(mps, mp5)\n\t}\n\tif mp6 != nil {\n\t\tmps = append(mps, mp6)\n\t}\n\n\timgs, err := getImages(device, opts5, opts6)\n\tif err != nil {\n\t\tfor _, mp := range mps {\n\t\t\tmp.Unmount(mount.MNT_DETACH)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\treturn imgs, mps, nil\n}", "func discoverManagedDevices() ([]string, []string) {\n\tstdErr.Println(\"Discovering managed devices...\")\n\n\tbody, bodyErr := client.QueryAPI(gqlDeviceListQuery)\n\tif bodyErr != nil {\n\t\tstdErr.Fatalf(\"Could not fetch device list: %s\\n\", bodyErr)\n\t}\n\tproactiveTokenRefresh()\n\n\tdevices := deviceList{}\n\tjsonErr := json.Unmarshal(body, &devices)\n\tif jsonErr != nil {\n\t\tstdErr.Fatalf(\"Could not decode JSON: %s\\n\", jsonErr)\n\t}\n\n\tvar upDevices []string\n\tvar downDevices []string\n\tfor _, d := range devices.Data.Network.Devices {\n\t\tif d.Up {\n\t\t\tupDevices = append(upDevices, d.IP)\n\t\t} else {\n\t\t\tdownDevices = append(downDevices, d.IP)\n\t\t}\n\t}\n\tsort.Strings(upDevices)\n\tstdErr.Println(\"Finished discovering managed devices.\")\n\n\treturn upDevices, downDevices\n}", "func (cl *Client) LocalEphemeralDevices() ([]*csp.EphemeralDevice, error) {\n\tdevList, err := readDirHook(diskDir)\n\tif err != nil {\n\t\tcl.csp.dbgF(\"Failed to list device names: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tdisks := map[string]*csp.EphemeralDevice{}\n\tfor _, disk := range devList {\n\t\tif name := disk.Name(); strings.HasPrefix(name, \"google-local-\") {\n\t\t\tif i := strings.Index(name, \"-part\"); i == -1 {\n\t\t\t\tdev := &csp.EphemeralDevice{}\n\t\t\t\tdev.Path = filepath.Join(diskDir, name)\n\t\t\t\tdev.SizeBytes = localSSDSizeBytes\n\t\t\t\tdev.Type = csp.EphemeralTypeSSD\n\t\t\t\tdev.Initialized = true\n\t\t\t\tdev.Usable = true // for now, may change below\n\t\t\t\tdisks[name] = dev\n\t\t\t} else {\n\t\t\t\t// not usable if it is partitioned. Note: ReadDir returns a sorted list, so partition names always sort after the base disk\n\t\t\t\tdev := disks[name[:i]]\n\t\t\t\tdev.Usable = false\n\t\t\t}\n\t\t}\n\t}\n\tpaths := []string{} // only contains disks that pass this first filter\n\tfor _, dev := range disks {\n\t\tif dev.Usable {\n\t\t\tpaths = append(paths, dev.Path)\n\t\t}\n\t}\n\n\t// Use blkid to filter any formatted devices. Only devices that are formatted will be included in the output.\n\t// Note: this only works natively as root or in a privileged container with /dev:/dev mapped\n\tif len(paths) > 0 {\n\t\tctx := context.Background()\n\t\toutput, err := cl.csp.exec.CommandContext(ctx, \"blkid\", paths...).CombinedOutput()\n\t\tif err != nil {\n\t\t\t// blkid exits with an error if none of the devices contain a formatted filesystem, ignore the error\n\t\t\tcl.csp.dbgF(\"blkid %s error: %v\", strings.Join(paths, \" \"), err)\n\t\t} else {\n\t\t\tre := regexp.MustCompile(`^` + diskDir + `/([^:]+): `)\n\t\t\tfor _, line := range strings.Split(string(output), \"\\n\") {\n\t\t\t\tif match := re.FindStringSubmatch(line); len(match) > 0 {\n\t\t\t\t\tif dev, ok := disks[string(match[1])]; ok {\n\t\t\t\t\t\tdev.Usable = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tnames := util.SortedStringKeys(disks)\n\tret := make([]*csp.EphemeralDevice, len(names))\n\tfor i, name := range names {\n\t\tret[i] = disks[name]\n\t}\n\treturn ret, nil\n}", "func (o *VirtualizationIweVirtualMachine) GetDisks() []VirtualizationVmDisk {\n\tif o == nil {\n\t\tvar ret []VirtualizationVmDisk\n\t\treturn ret\n\t}\n\treturn o.Disks\n}", "func (d *MinioDriver) List(r volume.Request) volume.Response {\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\n\tvar vols []*volume.Volume\n\tfor name, v := range d.volumes {\n\t\tvols = append(vols,\n\t\t\t&volume.Volume{\n\t\t\t\tName: name,\n\t\t\t\tMountpoint: v.mountpoint,\n\t\t\t})\n\t}\n\treturn volumeResp(\"\", \"\", vols, capability, \"\")\n}", "func DiskPartitions(all bool) ([]DiskPartitionStat, error) {\n\n\tfilename := \"/etc/mtab\"\n\tlines, err := common.ReadLines(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := make([]DiskPartitionStat, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tfields := strings.Fields(line)\n\t\td := DiskPartitionStat{\n\t\t\tDevice: fields[0],\n\t\t\tMountpoint: fields[1],\n\t\t\tFstype: fields[2],\n\t\t\tOpts: fields[3],\n\t\t}\n\t\tret = append(ret, d)\n\t}\n\n\treturn ret, nil\n}", "func DiskPartitions(all bool) ([]DiskPartitionStat, error) {\n\n\tfilename := \"/etc/mtab\"\n\tlines, err := readLines(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := make([]DiskPartitionStat, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tfields := strings.Fields(line)\n\t\td := DiskPartitionStat{\n\t\t\tMountpoint: fields[1],\n\t\t\tFstype: fields[2],\n\t\t\tOpts: fields[3],\n\t\t}\n\t\tret = append(ret, d)\n\t}\n\n\treturn ret, nil\n}", "func listDeviceSerials() ([]string, error) {\n\tstdOut := &bytes.Buffer{}\n\tparams := Params{args: []string{\"devices\"}, stdOut:stdOut}\n\terr := execAdb(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toutput := strings.Split(stdOut.String(), \"\\n\")\n\tdeviceSerials := output[:0]\n\tfor _, line := range output {\n\t\tif line != \"\" && !strings.HasPrefix(line, \"* daemon\") && line != \"List of devices attached\" {\n\t\t\tdeviceSerials = append(deviceSerials, strings.Split(line, \"\\t\")[0])\n\t\t}\n\t}\n\treturn deviceSerials, nil\n}", "func ListCommand(c *cli.Context, log logging.Logger, _ string) int {\n\tif len(c.Args()) != 0 {\n\t\tcli.ShowCommandHelp(c, \"list\")\n\t\treturn 1\n\t}\n\n\tshowAll := c.Bool(\"all\")\n\n\tk, err := klient.CreateKlientWithDefaultOpts()\n\tif err != nil {\n\t\tlog.Error(\"Error creating klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tif err := k.Dial(); err != nil {\n\t\tlog.Error(\"Error dialing klient client. err:%s\", err)\n\t\tfmt.Println(defaultHealthChecker.CheckAllFailureOrMessagef(GenericInternalError))\n\t\treturn 1\n\t}\n\n\tinfos, err := getListOfMachines(k)\n\tif err != nil {\n\t\tlog.Error(\"Error listing machines. err:%s\", err)\n\t\tfmt.Println(getListErrRes(err, defaultHealthChecker))\n\t\treturn 1\n\t}\n\n\t// Sort our infos\n\tsort.Sort(infos)\n\n\t// Filter out infos for listing and json.\n\tfor i := 0; i < len(infos); i++ {\n\t\tinfo := &infos[i]\n\n\t\tonlineRecently := time.Since(info.OnlineAt) <= 24*time.Hour\n\t\thasMounts := len(info.Mounts) > 0\n\t\t// Do not show machines that have been offline for more than 24h,\n\t\t// but only if the machine doesn't have any mounts and we aren't using the --all\n\t\t// flag.\n\t\tif !hasMounts && !showAll && !onlineRecently {\n\t\t\t// Remove this element from the slice, because we're not showing it as\n\t\t\t// described above.\n\t\t\tinfos = append(infos[:i], infos[i+1:]...)\n\t\t\t// Decrement the index, since we're removing the item from the slice.\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\n\t\t// For a more clear UX, replace the team name of the default Koding team,\n\t\t// with Koding.com\n\t\tfor i, team := range info.Teams {\n\t\t\tif team == \"Koding\" {\n\t\t\t\tinfo.Teams[i] = \"koding.com\"\n\t\t\t}\n\t\t}\n\n\t\tswitch info.MachineStatus {\n\t\tcase machine.MachineOffline:\n\t\t\tinfo.MachineStatusName = \"offline\"\n\t\tcase machine.MachineOnline:\n\t\t\tinfo.MachineStatusName = \"online\"\n\t\tcase machine.MachineDisconnected:\n\t\t\tinfo.MachineStatusName = \"disconnected\"\n\t\tcase machine.MachineConnected:\n\t\t\tinfo.MachineStatusName = \"connected\"\n\t\tcase machine.MachineError:\n\t\t\tinfo.MachineStatusName = \"error\"\n\t\tcase machine.MachineRemounting:\n\t\t\tinfo.MachineStatusName = \"remounting\"\n\t\tdefault:\n\t\t\tinfo.MachineStatusName = \"unknown\"\n\t\t}\n\t}\n\n\tif c.Bool(\"json\") {\n\t\tjsonBytes, err := json.MarshalIndent(infos, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Error(\"Marshalling infos to json failed. err:%s\", err)\n\t\t\tfmt.Println(GenericInternalError)\n\t\t\treturn 1\n\t\t}\n\n\t\tfmt.Println(string(jsonBytes))\n\t\treturn 0\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)\n\tfmt.Fprintf(w, \"\\tTEAM\\tLABEL\\tIP\\tALIAS\\tSTATUS\\tMOUNTED PATHS\\n\")\n\tfor i, info := range infos {\n\t\t// Join multiple teams into a single identifier\n\t\tteam := strings.Join(info.Teams, \",\")\n\n\t\tvar formattedMount string\n\t\tif len(info.Mounts) > 0 {\n\t\t\tformattedMount += fmt.Sprintf(\n\t\t\t\t\"%s -> %s\",\n\t\t\t\tshortenPath(info.Mounts[0].LocalPath),\n\t\t\t\tshortenPath(info.Mounts[0].RemotePath),\n\t\t\t)\n\t\t}\n\n\t\t// Currently we are displaying the status message over the formattedMount,\n\t\t// if it exists.\n\t\tif info.StatusMessage != \"\" {\n\t\t\tformattedMount = info.StatusMessage\n\t\t}\n\n\t\tfmt.Fprintf(w, \" %d.\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\",\n\t\t\ti+1, team, info.MachineLabel, info.IP, info.VMName, info.MachineStatusName,\n\t\t\tformattedMount,\n\t\t)\n\t}\n\tw.Flush()\n\n\treturn 0\n}", "func (c *Core) ListVolumes(labels map[string]string) ([]*types.Volume, error) {\n\tvar retVolumes = make([]*types.Volume, 0)\n\n\t// list local meta store.\n\tmetaList, err := c.store.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// scan all drivers.\n\tlogrus.Debugf(\"probing all drivers for listing volume\")\n\tdrivers, err := driver.GetAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := driver.Contexts()\n\n\tvar realVolumes = map[string]*types.Volume{}\n\tvar volumeDrivers = map[string]driver.Driver{}\n\n\tfor _, dv := range drivers {\n\t\tvolumeDrivers[dv.Name(ctx)] = dv\n\n\t\td, ok := dv.(driver.Lister)\n\t\tif !ok {\n\t\t\t// not Lister, ignore it.\n\t\t\tcontinue\n\t\t}\n\t\tvList, err := d.List(ctx)\n\t\tif err != nil {\n\t\t\tlogrus.Warnf(\"volume driver %s list error: %v\", dv.Name(ctx), err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range vList {\n\t\t\trealVolumes[v.Name] = v\n\t\t}\n\t}\n\n\tfor name, obj := range metaList {\n\t\tv, ok := obj.(*types.Volume)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\td, ok := volumeDrivers[v.Spec.Backend]\n\t\tif !ok {\n\t\t\t// driver not exist, ignore it\n\t\t\tcontinue\n\t\t}\n\n\t\t// the local driver and tmpfs driver\n\t\tif d.StoreMode(ctx).IsLocal() {\n\t\t\tretVolumes = append(retVolumes, v)\n\t\t\tcontinue\n\t\t}\n\n\t\trv, ok := realVolumes[name]\n\t\tif !ok {\n\t\t\t// real volume not exist, ignore it\n\t\t\tcontinue\n\t\t}\n\t\tv.Status.MountPoint = rv.Status.MountPoint\n\n\t\tdelete(realVolumes, name)\n\n\t\tretVolumes = append(retVolumes, v)\n\t}\n\n\tfor _, v := range realVolumes {\n\t\t// found new volumes, store the meta\n\t\tlogrus.Warningf(\"found new volume %s\", v.Name)\n\t\tc.store.Put(v)\n\n\t\tretVolumes = append(retVolumes, v)\n\n\t}\n\n\treturn retVolumes, nil\n}", "func getDiscoverdDevices(blockDevices []internal.BlockDevice) []v1alpha1.DiscoveredDevice {\n\tdiscoveredDevices := make([]v1alpha1.DiscoveredDevice, 0)\n\tfor _, blockDevice := range blockDevices {\n\t\tdeviceID, err := blockDevice.GetPathByID()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to get persistent ID for the device %q. Error %v\", blockDevice.Name, err)\n\t\t\tdeviceID = \"\"\n\t\t}\n\n\t\tsize, err := strconv.ParseInt(blockDevice.Size, 10, 64)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to parse size for the device %q. Error %v\", blockDevice.Name, err)\n\t\t}\n\n\t\tpath, err := blockDevice.GetDevPath()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to parse path for the device %q. Error %v\", blockDevice.KName, err)\n\t\t}\n\t\tdiscoveredDevice := v1alpha1.DiscoveredDevice{\n\t\t\tPath: path,\n\t\t\tModel: blockDevice.Model,\n\t\t\tVendor: blockDevice.Vendor,\n\t\t\tFSType: blockDevice.FSType,\n\t\t\tSerial: blockDevice.Serial,\n\t\t\tType: parseDeviceType(blockDevice.Type),\n\t\t\tDeviceID: deviceID,\n\t\t\tSize: size,\n\t\t\tProperty: parseDeviceProperty(blockDevice.Rotational),\n\t\t\tStatus: getDeviceStatus(blockDevice),\n\t\t}\n\t\tdiscoveredDevices = append(discoveredDevices, discoveredDevice)\n\t}\n\n\treturn uniqueDevices(discoveredDevices)\n}", "func (m *Smart) scan() ([]string, error) {\n\tout, err := runCmd(m.UseSudo, m.Path, \"--scan\")\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"failed to run command '%s --scan': %s - %s\", m.Path, err, string(out))\n\t}\n\n\tdevices := []string{}\n\tfor _, line := range strings.Split(string(out), \"\\n\") {\n\t\tdev := strings.Split(line, \" \")\n\t\tif len(dev) > 1 && !excludedDev(m.Excludes, strings.TrimSpace(dev[0])) {\n\t\t\tlog.Printf(\"D! [inputs.smart] adding device: %+#v\", dev)\n\t\t\tdevices = append(devices, strings.TrimSpace(dev[0]))\n\t\t} else {\n\t\t\tlog.Printf(\"D! [inputs.smart] skipping device: %+#v\", dev)\n\t\t}\n\t}\n\treturn devices, nil\n}", "func FindHardware(searchString string) []Hardware {\n\tresult := []Hardware{}\n\t//TODO: Rewrite query with better security against sql injection\n\t//TODO: Check again if only active devices are shown (archive is shown as well imo)\n\t//TODO: Modifiy so that phones can be found as well (different db table)\n\t//statusid = '11F18C35-FAB2-5802-86CA-B9DF68C41B8F' means the device has the status 'aktiv'\n\terr := db.Select(&result, \"SELECT naam, hostnaam, ref_gebruiker, objecttype, specificatie, ref_lokatie, ipadres, macadres FROM hardware WHERE (naam Like '%\"+searchString+\"%' OR ref_gebruiker Like '%\"+searchString+\"%' OR ipadres Like '%\"+searchString+\"%' OR macadres Like '%\"+searchString+\"%' OR hostnaam Like '%\"+searchString+\"%') AND statusid = '11F18C35-FAB2-5802-86CA-B9DF68C41B8F' AND archiefredenid IS NULL\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn result\n}", "func setupDevices(ctx context.Context, c *Container, s *specs.Spec) error {\n\tvar devs []specs.LinuxDevice\n\tdevPermissions := s.Linux.Resources.Devices\n\tif c.HostConfig.Privileged {\n\t\thostDevices, err := devices.HostDevices()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, d := range hostDevices {\n\t\t\tdevs = append(devs, linuxDevice(d))\n\t\t}\n\t\tdevPermissions = []specs.LinuxDeviceCgroup{\n\t\t\t{\n\t\t\t\tAllow: true,\n\t\t\t\tAccess: \"rwm\",\n\t\t\t},\n\t\t}\n\t} else {\n\t\tfor _, deviceMapping := range c.HostConfig.Devices {\n\t\t\tif !opts.ValidateDeviceMode(deviceMapping.CgroupPermissions) {\n\t\t\t\treturn fmt.Errorf(\"%s invalid device mode: %s\", deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)\n\t\t\t}\n\t\t\td, dPermissions, err := devicesFromPath(deviceMapping.PathOnHost, deviceMapping.PathInContainer, deviceMapping.CgroupPermissions)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdevs = append(devs, d...)\n\t\t\tdevPermissions = append(devPermissions, dPermissions...)\n\t\t}\n\t}\n\n\ts.Linux.Devices = append(s.Linux.Devices, devs...)\n\ts.Linux.Resources.Devices = append(s.Linux.Resources.Devices, devPermissions...)\n\treturn nil\n}", "func GuestCreateDisks(endpoint string, guestid string, body GuestCreateDiskList) (int, []byte) {\n\n\tcreateReq, _ := json.Marshal(body)\n\n\tbuffer := getEndpointwithGuests(endpoint)\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(guestid)\n\tbuffer.WriteString(\"/disks\")\n\n\tstatus, data := hq.Post(buffer.String(), createReq)\n\n\treturn status, data\n}", "func CreateListDisks00Response() (response *ListDisks00Response) {\n\tresponse = &ListDisks00Response{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (r *vdm) List() ([]VolumeMap, error) {\n\tfor _, d := range r.drivers {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"moduleName\": r.rexray.Context,\n\t\t\t\"driverName\": d.Name()}).Info(\"vdm.List\")\n\n\t\tlist, err := d.List()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !r.pathCache() {\n\t\t\treturn list, nil\n\t\t}\n\n\t\tvar listNew []VolumeMap\n\n\t\tfor _, vol := range list {\n\t\t\tvar name string\n\t\t\tvar gvol *VolumeMap\n\t\t\tif name, gvol = vol.get(\"Name\"); gvol == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, ok := r.mapUsedCount[name]; !ok {\n\t\t\t\tif _, gvol := vol.get(\"Mountpoint\"); gvol != nil {\n\t\t\t\t\tr.countInit(name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlistNew = append(listNew, *gvol)\n\t\t}\n\n\t\treturn listNew, nil\n\n\t}\n\treturn nil, errors.ErrNoVolumesDetected\n}", "func (p *redfishProvisioner) InspectHardware() (result provisioner.Result, err error) {\n\tp.log.Info(\"inspecting hardware\", \"status\", p.host.OperationalStatus())\n\n\t// The inspection is ongoing. We'll need to check the redfish\n\t// status for the server here until it is ready for us to get the\n\t// inspection details. Simulate that for now by creating the\n\t// hardware details struct as part of a second pass.\n\tif p.host.Status.HardwareDetails == nil {\n\t\tp.log.Info(\"continuing inspection by setting details\")\n\t\tp.host.Status.HardwareDetails =\n\t\t\t&metalkubev1alpha1.HardwareDetails{\n\t\t\t\tRAMGiB: 128,\n\t\t\t\tNIC: []metalkubev1alpha1.NIC{\n\t\t\t\t\tmetalkubev1alpha1.NIC{\n\t\t\t\t\t\tName: \"nic-1\",\n\t\t\t\t\t\tModel: \"virt-io\",\n\t\t\t\t\t\tNetwork: \"Pod Networking\",\n\t\t\t\t\t\tMAC: \"some:mac:address\",\n\t\t\t\t\t\tIP: \"192.168.100.1\",\n\t\t\t\t\t\tSpeedGbps: 1,\n\t\t\t\t\t},\n\t\t\t\t\tmetalkubev1alpha1.NIC{\n\t\t\t\t\t\tName: \"nic-2\",\n\t\t\t\t\t\tModel: \"e1000\",\n\t\t\t\t\t\tNetwork: \"Pod Networking\",\n\t\t\t\t\t\tMAC: \"some:other:mac:address\",\n\t\t\t\t\t\tIP: \"192.168.100.2\",\n\t\t\t\t\t\tSpeedGbps: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tStorage: []metalkubev1alpha1.Storage{\n\t\t\t\t\tmetalkubev1alpha1.Storage{\n\t\t\t\t\t\tName: \"disk-1 (boot)\",\n\t\t\t\t\t\tType: \"SSD\",\n\t\t\t\t\t\tSizeGiB: 1024 * 93,\n\t\t\t\t\t\tModel: \"Dell CFJ61\",\n\t\t\t\t\t},\n\t\t\t\t\tmetalkubev1alpha1.Storage{\n\t\t\t\t\t\tName: \"disk-2\",\n\t\t\t\t\t\tType: \"SSD\",\n\t\t\t\t\t\tSizeGiB: 1024 * 93,\n\t\t\t\t\t\tModel: \"Dell CFJ61\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCPUs: []metalkubev1alpha1.CPU{\n\t\t\t\t\tmetalkubev1alpha1.CPU{\n\t\t\t\t\t\tType: \"x86\",\n\t\t\t\t\t\tSpeedGHz: 3,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\tp.publisher(\"InspectionComplete\", \"Hardware inspection completed\")\n\t\tresult.Dirty = true\n\t\treturn result, nil\n\t}\n\n\treturn result, nil\n}", "func makeDevices(c container) {\n\t// Standard file descriptors.\n\terr := os.Symlink(\"/proc/self/fd\", c.root(\"dev\", \"fd\"))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error symlink fd: %s\\n\", err))\n\t}\n\n\tfor i, dev := range []string{\"stdin\", \"stdout\", \"stderr\"} {\n\t\terr := os.Symlink(fmt.Sprintf(\"/proc/self/fd/%d\", i), c.root(\"dev\", dev))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Error symlink %s: %s\\n\", dev, err))\n\t\t}\n\t}\n\n\t// Special devices.\n\tdevices := []struct {\n\t\tname string\n\t\tkind uint32\n\t\tperms uint32\n\t\tmajor uint32\n\t\tminor uint32\n\t}{\n\t\t{name: \"null\", kind: syscall.S_IFCHR, perms: 0666, major: 1, minor: 3},\n\t\t{name: \"zero\", kind: syscall.S_IFCHR, perms: 0666, major: 1, minor: 5},\n\t\t{name: \"full\", kind: syscall.S_IFCHR, perms: 0666, major: 1, minor: 7},\n\t\t{name: \"random\", kind: syscall.S_IFCHR, perms: 0666, major: 1, minor: 8},\n\t\t{name: \"urandom\", kind: syscall.S_IFCHR, perms: 0666, major: 1, minor: 9},\n\t\t{name: \"tty\", kind: syscall.S_IFCHR, perms: 0666, major: 5, minor: 0},\n\t\t{name: \"ptmx\", kind: syscall.S_IFCHR, perms: 0666, major: 5, minor: 2},\n\t}\n\n\tfor _, dev := range devices {\n\t\tdevice := int(unix.Mkdev(dev.major, dev.minor))\n\n\t\terr := syscall.Mknod(c.root(\"dev\", dev.name), dev.kind|dev.perms, device)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Error mknod %s: %s\\n\", dev.name, err))\n\t\t}\n\n\t}\n\n\t// TODO: this is flaky due to the potential (lack of) existence of /dev/pts/0.\n\t// bindMountConsole(c)\n}", "func routeSmartCardList(w http.ResponseWriter, r *http.Request) {\n\n\tdevices, err := api.SmartCardList()\n\n\tif err != nil {\n\t\tlog.Printf(\"ESR01: %s\", err.Error())\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t} else {\n\t\tjson, _ := json.Marshal(devices)\n\t\tmsg := fmt.Sprintf(`{\"success\" : true, \"data\" : %s}`, string(json))\n\t\tfmt.Fprintln(w, msg)\n\t}\n\n}", "func (b BladeStorage) GetAllByDisksID(offset string, limit string, serials []string) (count int, blades []model.Blade, err error) {\n\tif offset != \"\" && limit != \"\" {\n\t\tif err = b.db.Limit(limit).Offset(offset).Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t\tb.db.Model(&model.Blade{}).Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Count(&count)\n\t} else {\n\t\tif err = b.db.Joins(\"INNER JOIN disk ON disk.blade_serial = blade.serial\").Where(\"disk.serial in (?)\", serials).Find(&blades).Error; err != nil {\n\t\t\treturn count, blades, err\n\t\t}\n\t}\n\treturn count, blades, err\n}", "func List() (list []*Info) {\n\tinitBdevLib()\n\tfor d := C.spdk_bdev_first(); d != nil; d = C.spdk_bdev_next(d) {\n\t\tlist = append(list, (*Info)(d))\n\t}\n\treturn list\n}", "func HostDiskpoolInfo(endpoint string, disk string) (int, []byte) {\n\n\tbuffer := getEndpointwithHost(endpoint)\n\tbuffer.WriteString(\"/disk/\")\n\tbuffer.WriteString(disk)\n\n\tstatus, data := hq.Get(buffer.String())\n\n\treturn status, data\n}", "func (c *SmartThingsClient) DevicesList() (*DeviceList, error) {\n\n\treq, err := c.newRequest(http.MethodGet, \"/v1/devices\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar deviceList DeviceList\n\t_, err = c.do(req, &deviceList)\n\treturn &deviceList, err\n}", "func listHostOnlyAdapters(vbox VBoxManager) (map[string]*hostOnlyNetwork, error) {\n\tout, err := vbox.vbmOut(\"list\", \"hostonlyifs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbyName := map[string]*hostOnlyNetwork{}\n\tbyIP := map[string]*hostOnlyNetwork{}\n\tn := &hostOnlyNetwork{}\n\n\terr = parseKeyValues(out, reColonLine, func(key, val string) error {\n\t\tswitch key {\n\t\tcase \"Name\":\n\t\t\tn.Name = val\n\t\tcase \"GUID\":\n\t\t\tn.GUID = val\n\t\tcase \"DHCP\":\n\t\t\tn.DHCP = (val != \"Disabled\")\n\t\tcase \"IPAddress\":\n\t\t\tn.IPv4.IP = net.ParseIP(val)\n\t\tcase \"NetworkMask\":\n\t\t\tn.IPv4.Mask = parseIPv4Mask(val)\n\t\tcase \"HardwareAddress\":\n\t\t\tmac, err := net.ParseMAC(val)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tn.HwAddr = mac\n\t\tcase \"MediumType\":\n\t\t\tn.Medium = val\n\t\tcase \"Status\":\n\t\t\tn.Status = val\n\t\tcase \"VBoxNetworkName\":\n\t\t\tn.NetworkName = val\n\n\t\t\tif _, present := byName[n.NetworkName]; present {\n\t\t\t\treturn fmt.Errorf(\"VirtualBox is configured with multiple host-only adapters with the same name %q. Please remove one.\", n.NetworkName)\n\t\t\t}\n\t\t\tbyName[n.NetworkName] = n\n\n\t\t\tif len(n.IPv4.IP) != 0 {\n\t\t\t\tif _, present := byIP[n.IPv4.IP.String()]; present {\n\t\t\t\t\treturn fmt.Errorf(\"VirtualBox is configured with multiple host-only adapters with the same IP %q. Please remove one.\", n.IPv4.IP)\n\t\t\t\t}\n\t\t\t\tbyIP[n.IPv4.IP.String()] = n\n\t\t\t}\n\n\t\t\tn = &hostOnlyNetwork{}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn byName, nil\n}", "func (m *Smart) getAttributes(acc telegraf.Accumulator, devices []string) {\n\tvar wg sync.WaitGroup\n\twg.Add(len(devices))\n\n\tfor _, device := range devices {\n\t\tgo gatherDisk(acc, m.UseSudo, m.Attributes, m.Path, m.Nocheck, device, &wg)\n\t}\n\n\twg.Wait()\n}", "func (s *Module) initialize(ctx context.Context) error {\n\t// lock for the entire initialization method, so other code which relies\n\t// on this observes this as an atomic operation\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tlog.Info().Msgf(\"Initializing storage module\")\n\n\tvm := kernel.GetParams().IsVirtualMachine()\n\tlog.Debug().Bool(\"is-vm\", vm).Msg(\"debugging virtualization detection\")\n\n\t// Make sure we finish in 1 minute\n\tsubCtx, cancel := context.WithTimeout(context.Background(), time.Minute*1)\n\tdefer cancel()\n\n\tdevices, err := s.devices.Devices(subCtx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, device := range devices {\n\t\tlog.Debug().Msgf(\"device: %+v\", device)\n\t\tpool, err := filesystem.NewBtrfsPool(device)\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"device\", device.Path).Msg(\"failed to create pool on device\")\n\t\t\ts.brokenDevices = append(s.brokenDevices, pkg.BrokenDevice{Path: device.Path, Err: err})\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = pool.Mount()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"device\", device.Path).Msg(\"failed to mount pool\")\n\t\t\ts.brokenPools = append(s.brokenPools, pkg.BrokenPool{Label: pool.Name(), Err: err})\n\t\t\tcontinue\n\t\t}\n\t\tusage, err := pool.Usage()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"pool\", pool.Name()).Str(\"device\", device.Path).Msg(\"failed to get usage of pool\")\n\t\t}\n\n\t\ttyp, ok := s.cache.Get(device.Name())\n\t\tif !ok {\n\t\t\tlog.Debug().Str(\"device\", device.Path).Msg(\"detecting device type\")\n\t\t\ttyp, err = device.Type()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Str(\"device\", device.Path).Err(err).Msg(\"failed to check device type\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// for development purposes only\n\t\t\tif vm {\n\t\t\t\t// force ssd device for vms\n\t\t\t\ttyp = zos.SSDDevice\n\n\t\t\t\tif device.Path == \"/dev/vdd\" || device.Path == \"/dev/vde\" {\n\t\t\t\t\ttyp = zos.HDDDevice\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.Debug().Str(\"device\", device.Path).Str(\"type\", typ.String()).Msg(\"caching device type\")\n\t\t\tif err := s.cache.Set(device.Name(), typ); err != nil {\n\t\t\t\tlog.Error().Str(\"device\", device.Path).Err(err).Msg(\"failed to cache device type\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debug().Str(\"device\", device.Path).Str(\"type\", typ.String()).Msg(\"device type loaded from cache\")\n\t\t}\n\n\t\tswitch typ {\n\t\tcase zos.SSDDevice:\n\t\t\ts.totalSSD += usage.Size\n\t\t\ts.ssds = append(s.ssds, pool)\n\t\tcase zos.HDDDevice:\n\t\t\ts.totalHDD += usage.Size\n\t\t\ts.hdds = append(s.hdds, pool)\n\t\tdefault:\n\t\t\tlog.Error().Str(\"type\", string(typ)).Str(\"device\", device.Path).Msg(\"unknown device type\")\n\t\t}\n\t}\n\n\t// clean up hdd disks to make sure only zdb subvolumes exists\n\t// this code makes sure HDDs only have volumes for zdb. Or none\n\tfor _, hdd := range s.hdds {\n\t\t// we know that all pools are mounted already so it's okay\n\t\t// to access them direction\n\t\tvolumes, err := hdd.Volumes()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"pool\", hdd.Name()).Msg(\"failed to list pool volumes\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, vol := range volumes {\n\t\t\tif vol.Name() != zdbVolume && vol.Name() != cacheLabel {\n\t\t\t\t// we don't delete zdb volumes, also zos-cache volumes\n\t\t\t\t// although they should not exist on hdd for protection\n\t\t\t\t// in case of error or bad detection of device speed.\n\t\t\t\tif err := hdd.RemoveVolume(vol.Name()); err != nil {\n\t\t\t\t\tlog.Error().Err(err).\n\t\t\t\t\t\tStr(\"volume\", vol.Name()).\n\t\t\t\t\t\tStr(\"pool\", hdd.Name()).\n\t\t\t\t\t\tMsg(\"failed to delete non zdb volume from harddisk\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Info().\n\t\tInt(\"ssd-pools\", len(s.ssds)).\n\t\tInt(\"hdd-pools\", len(s.hdds)).\n\t\tInt(\"broken-pools\", len(s.brokenPools)).\n\t\tInt(\"broken-devices\", len(s.brokenDevices)).\n\t\tMsg(\"pool creations completed\")\n\n\ts.dump()\n\n\t// just in case\n\tif err := filesystem.Partprobe(subCtx); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.ensureCache(ctx); err != nil {\n\t\tlog.Error().Err(err).Msg(\"Error ensuring cache\")\n\t\treturn err\n\t}\n\n\tif err := s.shutdownUnusedPools(vm); err != nil {\n\t\tlog.Error().Err(err).Msg(\"Error shutting down unused pools\")\n\t}\n\n\ts.periodicallyCheckDiskShutdown(vm)\n\n\treturn nil\n}", "func (s stage) partitionDisk(dev types.Disk, devAlias string) error {\n\tif cutil.IsTrue(dev.WipeTable) {\n\t\top := sgdisk.Begin(s.Logger, devAlias)\n\t\ts.Logger.Info(\"wiping partition table requested on %q\", devAlias)\n\t\top.WipeTable(true)\n\t\tif err := op.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Ensure all partitions with number 0 are last\n\tsort.Stable(PartitionList(dev.Partitions))\n\n\top := sgdisk.Begin(s.Logger, devAlias)\n\n\tdiskInfo, err := s.getPartitionMap(devAlias)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// get a list of parititions that have size and start 0 replaced with the real sizes\n\t// that would be used if all specified partitions were to be created anew.\n\t// Also calculate sectors for all of the start/size values.\n\tresolvedPartitions, err := s.getRealStartAndSize(dev, devAlias, diskInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, part := range resolvedPartitions {\n\t\tshouldExist := partitionShouldExist(part)\n\t\tinfo, exists := diskInfo.GetPartition(part.Number)\n\t\tvar matchErr error\n\t\tif exists {\n\t\t\tmatchErr = partitionMatches(info, part)\n\t\t}\n\t\tmatches := exists && matchErr == nil\n\t\twipeEntry := cutil.IsTrue(part.WipePartitionEntry)\n\n\t\t// This is a translation of the matrix in the operator notes.\n\t\tswitch {\n\t\tcase !exists && !shouldExist:\n\t\t\ts.Logger.Info(\"partition %d specified as nonexistant and no partition was found. Success.\", part.Number)\n\t\tcase !exists && shouldExist:\n\t\t\top.CreatePartition(part)\n\t\tcase exists && !shouldExist && !wipeEntry:\n\t\t\treturn fmt.Errorf(\"partition %d exists but is specified as nonexistant and wipePartitionEntry is false\", part.Number)\n\t\tcase exists && !shouldExist && wipeEntry:\n\t\t\top.DeletePartition(part.Number)\n\t\tcase exists && shouldExist && matches:\n\t\t\ts.Logger.Info(\"partition %d found with correct specifications\", part.Number)\n\t\tcase exists && shouldExist && !wipeEntry && !matches:\n\t\t\tif partitionMatchesResize(info, part) {\n\t\t\t\ts.Logger.Info(\"resizing partition %d\", part.Number)\n\t\t\t\top.DeletePartition(part.Number)\n\t\t\t\tpart.Number = info.Number\n\t\t\t\tpart.GUID = &info.GUID\n\t\t\t\tpart.TypeGUID = &info.TypeGUID\n\t\t\t\tpart.Label = &info.Label\n\t\t\t\tpart.StartSector = &info.StartSector\n\t\t\t\top.CreatePartition(part)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"Partition %d didn't match: %v\", part.Number, matchErr)\n\t\t\t}\n\t\tcase exists && shouldExist && wipeEntry && !matches:\n\t\t\ts.Logger.Info(\"partition %d did not meet specifications, wiping partition entry and recreating\", part.Number)\n\t\t\top.DeletePartition(part.Number)\n\t\t\top.CreatePartition(part)\n\t\tdefault:\n\t\t\t// unfortunatey, golang doesn't check that all cases are handled exhaustively\n\t\t\treturn fmt.Errorf(\"Unreachable code reached when processing partition %d. golang--\", part.Number)\n\t\t}\n\t}\n\n\tif err := op.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"commit failure: %v\", err)\n\t}\n\treturn nil\n}", "func GuestConfigDisks(endpoint string, guestid string, body GuestConfigDiskList) (int, []byte) {\n\tputReq := buildGuestConfigDiskRequest(body)\n\n\tbuffer := getEndpointwithGuests(endpoint)\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(guestid)\n\tbuffer.WriteString(\"/disks\")\n\n\theaders := buildAuthContext(\"\")\n\tctxt := RequestContext{\n\t\tvalues: headers,\n\t}\n\n\tstatus, data := hq.Put(buffer.String(), putReq, ctxt)\n\n\treturn status, data\n}", "func (o StatefulPolicyPreservedStateResponseOutput) Disks() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v StatefulPolicyPreservedStateResponse) map[string]string { return v.Disks }).(pulumi.StringMapOutput)\n}", "func (ac *activeClient) Hardware(c *ishell.Context) {\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\tr := shared.Hardware{}\n\n\tif err := ac.RPC.Call(\"API.GetHardware\", void, &r); err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Could not collect information on client hardware:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + green(\"[+] Hardware collection finished\"))\n\tc.ProgressBar().Stop()\n\n\tc.Println(green(\"Runtime: \"), r.Runtime)\n\tc.Println(green(\"Arch: \"), r.OSArch)\n\tc.Println(green(\"OS: \"), r.OSName)\n\tc.Println(green(\"OS Version: \"), r.OSVersion)\n\tc.Println(green(\"CPU: \"), r.CPU)\n\tc.Println(green(\"CORES: \"), r.Cores)\n\tc.Println(green(\"RAM: \"), r.RAM)\n\tc.Println(green(\"GPU: \"), r.GPU)\n\tc.Println(green(\"Drives: \"), r.Drives)\n}", "func (o StorageClusterSpecStorageOutput) Devices() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecStorage) []string { return v.Devices }).(pulumi.StringArrayOutput)\n}", "func (o LookupServerResultOutput) Disks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupServerResult) []string { return v.Disks }).(pulumi.StringArrayOutput)\n}", "func AddToMountedList(nbd, img string) {\n\tMountedList[nbd] = img\n\tfor key, value := range AvailableList {\n\t\tif value == nbd {\n\t\t\tAvailableList[key] = \"\"\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (s *VolumeStore) list() ([]volume.Volume, []string, error) {\n\tvar (\n\t\tls []volume.Volume\n\t\twarnings []string\n\t)\n\n\tdrivers, err := volumedrivers.GetAllDrivers()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttype vols struct {\n\t\tvols []volume.Volume\n\t\terr error\n\t\tdriverName string\n\t}\n\tchVols := make(chan vols, len(drivers))\n\n\tfor _, vd := range drivers {\n\t\tgo func(d volume.Driver) {\n\t\t\tvs, err := d.List()\n\t\t\tif err != nil {\n\t\t\t\tchVols <- vols{driverName: d.Name(), err: &OpErr{Err: err, Name: d.Name(), Op: \"list\"}}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor i, v := range vs {\n\t\t\t\ts.globalLock.RLock()\n\t\t\t\tvs[i] = volumeWrapper{v, s.labels[v.Name()], d.Scope(), s.options[v.Name()]}\n\t\t\t\ts.globalLock.RUnlock()\n\t\t\t}\n\n\t\t\tchVols <- vols{vols: vs}\n\t\t}(vd)\n\t}\n\n\tbadDrivers := make(map[string]struct{})\n\tfor i := 0; i < len(drivers); i++ {\n\t\tvs := <-chVols\n\n\t\tif vs.err != nil {\n\t\t\twarnings = append(warnings, vs.err.Error())\n\t\t\tbadDrivers[vs.driverName] = struct{}{}\n\t\t\tlogrus.Warn(vs.err)\n\t\t}\n\t\tls = append(ls, vs.vols...)\n\t}\n\n\tif len(badDrivers) > 0 {\n\t\ts.globalLock.RLock()\n\t\tfor _, v := range s.names {\n\t\t\tif _, exists := badDrivers[v.DriverName()]; exists {\n\t\t\t\tls = append(ls, v)\n\t\t\t}\n\t\t}\n\t\ts.globalLock.RUnlock()\n\t}\n\treturn ls, warnings, nil\n}", "func main() {\n\tlog.InitLogging(chapiClientLog, &log.LogParams{Level: \"trace\"}, false)\n\n\tvar hosts model.Hosts\n\tvar devices []*model.Device\n\tvar device model.Device\n\tvar serialnumber string\n\tvar devicePartitions []*model.DevicePartition\n\tvar buffer bytes.Buffer\n\n\tvar restClient = &http.Client{\n\t\tTimeout: time.Second * 60,\n\t}\n\n\t// Retrieve the Host UUID\n\tresponse, err := restClient.Get(baseURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tbuf, _ := ioutil.ReadAll(response.Body)\n\tjson.Unmarshal(buf, &hosts)\n\tlog.Tracef(\"URL:%s StatusCode:%d UUID:%s\", baseURL, response.StatusCode, hosts[0].UUID)\n\n\tbuffer.WriteString(baseURL)\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(hosts[0].UUID)\n\tbuffer.WriteString(\"/devices\")\n\tdevicesURL := buffer.String()\n\tlog.Tracef(\"URL:%s StatusCode:%d\", baseURL, response.StatusCode)\n\n\t// Retrive the Host Devices\n\tresponse, err = restClient.Get(devicesURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tbuf, _ = ioutil.ReadAll(response.Body)\n\tjson.Unmarshal(buf, &devices)\n\tfor _, dev := range devices {\n\t\tlog.Tracef(\"Device: %#v\", dev)\n\t\tserialnumber = dev.SerialNumber\n\t}\n\n\t// Retrive the Device Info for a paritcular Device\n\tvar buffDevice bytes.Buffer\n\tbuffDevice.WriteString(devicesURL)\n\tbuffDevice.WriteString(\"/\")\n\tbuffDevice.WriteString(serialnumber)\n\tdeviceURL := buffDevice.String()\n\tresponse, err = restClient.Get(deviceURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tlog.Tracef(\"URL:%s StatusCode:%d\", baseURL, response.StatusCode)\n\tbuf, _ = ioutil.ReadAll(response.Body)\n\tjson.Unmarshal(buf, &device)\n\tlog.Tracef(\"Device: %#v\", device)\n\n\t// retrieve Device Partition For a Particular Device\n\tvar buffPartition bytes.Buffer\n\tbuffPartition.WriteString(deviceURL)\n\tbuffPartition.WriteString(\"/\")\n\tbuffPartition.WriteString(\"partitions\")\n\tpartitionURL := buffPartition.String()\n\tresponse, err = restClient.Get(partitionURL)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tlog.Tracef(\"URL:%s StatusCode:%d\", baseURL, response.StatusCode)\n\tbuf, _ = ioutil.ReadAll(response.Body)\n\tjson.Unmarshal(buf, &devicePartitions)\n\tfor _, part := range devicePartitions {\n\t\tlog.Tracef(\"Partition: %#v\", part)\n\t}\n}", "func (c *Eth) ShowList() ([]string, error) {\n c.con.LogQuery(\"(show) list of ethernet interfaces\")\n path := c.xpath(nil)\n return c.con.EntryListUsing(c.con.Show, path[:len(path) - 1])\n}", "func (o *ClusterUninstaller) destroyDisks() error {\n\tfound, err := o.listDisks()\n\tif err != nil {\n\t\treturn err\n\t}\n\titems := o.insertPendingItems(\"disk\", found)\n\tfor _, item := range items {\n\t\terr := o.deleteDisk(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tfor _, item := range items {\n\t\terr := o.waitForDiskDeletion(item)\n\t\tif err != nil {\n\t\t\to.errorTracker.suppressWarning(item.key, err, o.Logger)\n\t\t}\n\t}\n\n\tif items = o.getPendingItems(\"disk\"); len(items) > 0 {\n\t\treturn errors.Errorf(\"%d items pending\", len(items))\n\t}\n\treturn nil\n}", "func scsiControllerListString(ctlrs []types.BaseVirtualSCSIController) string {\n\tvar l object.VirtualDeviceList\n\tfor _, ctlr := range ctlrs {\n\t\tif ctlr == nil {\n\t\t\tl = append(l, types.BaseVirtualDevice(nil))\n\t\t} else {\n\t\t\tl = append(l, ctlr.(types.BaseVirtualDevice))\n\t\t}\n\t}\n\treturn DeviceListString(l)\n}", "func MapRegistryDisks(vm *v1.VM) (*v1.VM, error) {\n\tvmCopy := &v1.VM{}\n\tmodel.Copy(vmCopy, vm)\n\n\tfor idx, disk := range vmCopy.Spec.Domain.Devices.Disks {\n\t\tif disk.Type == registryDiskV1Alpha {\n\t\t\tnewDisk := v1.Disk{}\n\n\t\t\tnewDisk.Type = \"network\"\n\t\t\tnewDisk.Device = \"disk\"\n\t\t\tnewDisk.Target = disk.Target\n\n\t\t\tnewDisk.Driver = &v1.DiskDriver{\n\t\t\t\tType: \"raw\",\n\t\t\t\tName: \"qemu\",\n\t\t\t\tCache: \"none\",\n\t\t\t}\n\n\t\t\tnewDisk.Source.Name = defaultIqn\n\t\t\tnewDisk.Source.Protocol = \"iscsi\"\n\t\t\tnewDisk.Source.Host = disk.Source.Host\n\n\t\t\tvmCopy.Spec.Domain.Devices.Disks[idx] = newDisk\n\t\t}\n\t}\n\n\treturn vmCopy, nil\n}", "func (proxy *remoteDriverProxy) List() ([]*remoteVolumeDesc, error) {\n\tvar req remoteVolumeListReq\n\tvar resp remoteVolumeListResp\n\n\tif err := proxy.client.CallService(remoteVolumeListService, &req, &resp, true); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.Err != \"\" {\n\t\treturn nil, errors.New(resp.Err)\n\t}\n\n\treturn resp.Volumes, nil\n}", "func (o StorageClusterSpecNodesStorageOutput) Devices() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecNodesStorage) []string { return v.Devices }).(pulumi.StringArrayOutput)\n}", "func createSCSIController(l *object.VirtualDeviceList, ct string, st string) ([]types.BaseVirtualDeviceConfigSpec, error) {\n\tnc, err := l.CreateSCSIController(ct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnc.(types.BaseVirtualSCSIController).GetVirtualSCSIController().SharedBus = types.VirtualSCSISharing(st)\n\tcspec, err := object.VirtualDeviceList{nc}.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)\n\t*l = applyDeviceChange(*l, cspec)\n\treturn cspec, err\n}", "func (network *Network) getLinux() error {\n\n\tout, err := exec.Command(\"/bin/ip\", \"route\", \"get\", \"8.8.8.8\").Output()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tparts := strings.Split(string(out), \" \")\n\tnetwork.DefaultGateway = net.ParseIP(parts[2])\n\tnetwork.InterfaceName = parts[4]\n\tnetwork.LocalIP = net.ParseIP(parts[6])\n\n\tinterf, err := net.InterfaceByName(network.InterfaceName)\n\tif err == nil {\n\t\tnetwork.HardwareAddress = interf.HardwareAddr\n\t\tnetwork.Interface = interf\n\n\t} else {\n\t\treturn err\n\t}\n\n\tout, err = exec.Command(\"/sbin/ifconfig\", network.InterfaceName).Output()\n\tif err == nil {\n\t\tlines := strings.Split(string(out), \"\\n\")\n\n\t\tif len(lines) > 1 {\n\t\t\tnetwork.SubnetMask = net.ParseIP(strings.Split(strings.TrimSpace(lines[1]), \" \")[4])\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\n\tout, err = exec.Command(\"grep\", \"domain-name\", \"/var/lib/dhcp/dhclient.\"+network.InterfaceName+\".leases\").Output()\n\n\tif err == nil {\n\t\tdnslist := \"\"\n\t\tlines := strings.Split(strings.TrimSpace(string(out)), \"\\n\")\n\t\tfor _, line := range lines {\n\t\t\tif strings.Contains(line, \"domain-name-servers\") {\n\t\t\t\tif len(line) > 26 {\n\t\t\t\t\tline = strings.TrimRight(strings.TrimSpace(line)[26:], \";\")\n\t\t\t\t\tlist := strings.Split(line, \",\")\n\t\t\t\t\tfor _, dnsitem := range list {\n\t\t\t\t\t\tif !strings.Contains(dnslist, dnsitem) {\n\t\t\t\t\t\t\tdnslist += dnsitem + \",\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif len(line) > 18 {\n\t\t\t\t\tnetwork.Suffix = strings.TrimSpace(strings.TrimRight(strings.TrimSpace(line)[18:], \";\"))\n\t\t\t\t}\n\t\t\t}\n\t\t\tdnslist = strings.TrimRight(dnslist, \",\")\n\t\t}\n\n\t\tnetwork.DNS = strings.Split(dnslist, \",\")\n\t} else {\n\t\treturn err\n\t}\n\tout, err = exec.Command(\"arp\", \"-e\", network.DefaultGateway.String()).Output()\n\tif err == nil {\n\t\tlines := strings.Split(string(out), \"\\n\")\n\n\t\tif len(lines) >= 2 {\n\n\t\t\tnetwork.DefaultGatewayHardwareAddress, _ = net.ParseMAC(strings.Fields(lines[1])[2])\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *Client) listMonitoredVolumes() ([]api.Volume, error) {\n\tvar vols []api.Volume\n\tm := metadata.NewVolume(providers.FromClient(client))\n\terr := m.Browse(func(vol *api.Volume) error {\n\t\tvols = append(vols, *vol)\n\t\treturn nil\n\t})\n\tif len(vols) == 0 && err != nil {\n\t\treturn nil, fmt.Errorf(\"Error listing volumes : %s\", ProviderErrorToString(err))\n\t}\n\treturn vols, nil\n}", "func (o StorageClusterSpecStoragePtrOutput) Devices() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpecStorage) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Devices\n\t}).(pulumi.StringArrayOutput)\n}", "func TestRetrieveDeviceList(t *testing.T) {\n\tc := NewNetboxAt(\"localhost:8000\")\n\n\tlist, err := c.Dcim.DcimDevicesList(nil, nil)\n\n\tassert.NoError(t, err)\n\tassert.EqualValues(t, 11, *list.Payload.Count)\n}", "func (c *Dg) ShowList() ([]string, error) {\n c.con.LogQuery(\"(show) list of device groups\")\n path := c.xpath(nil)\n return c.con.EntryListUsing(c.con.Show, path[:len(path) - 1])\n}", "func CreateListDisks00Request() (request *ListDisks00Request) {\n\trequest = &ListDisks00Request{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"EcsDemo\", \"2019-06-20\", \"ListDisks00\", \"\", \"\")\n\treturn\n}", "func NeuraxDisks() error {\n\tselected_name := gen_haiku()\n\tif runtime.GOOS == \"windows\" {\n\t\tselected_name += \".exe\"\n\t}\n\tdisks, err := cf.Disks()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, d := range disks {\n\t\terr := cf.CopyFile(os.Args[0], d+\"/\"+selected_name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Manager) List() map[string]Modem {\n\tdevList := make(map[string]Modem)\n\tfor k, v := range m.devices {\n\t\tif v.ready == 1 {\n\t\t\tdevList[k] = v\n\t\t}\n\t}\n\treturn devList\n}", "func (d *VolumeDriver) List(r volume.Request) volume.Response {\n\tlog.Errorf(\"VolumeDriver List to be implemented\")\n\treturn volume.Response{Err: \"\"}\n}", "func comandoMkdisk(comando string) {\n\tfmt.Println(\"\\nEJECUTANDO: \" + comando)\n\t//Descomponiendo en atributos\n\tatributos := strings.Split(comando, \" -\")\n\t//verificando parametros\n\tif len(atributos) > 3 {\n\t\tsize := 0\n\t\tpath := \"\"\n\t\tname := \"\"\n\t\tunit := \"\"\n\t\tfor i := 1; i < len(atributos); i++ {\n\t\t\tatributoActual := strings.Split(atributos[i], \"->\")\n\t\t\tswitch strings.ToLower(atributoActual[0]) {\n\t\t\tcase \"size\":\n\t\t\t\tsize = atributoSize(atributoActual[1])\n\t\t\tcase \"path\":\n\t\t\t\tpath = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(atributoActual[1], \"\\\"\", \"\")))\n\t\t\tcase \"name\":\n\t\t\t\tname = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(atributoActual[1], \"\\\"\", \"\")))\n\t\t\tcase \"unit\":\n\t\t\t\tunit = atributoUnit(atributoActual[1])\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"RESULTADO: El atributo \" + atributoActual[0] + \" no se reconoce\")\n\t\t\t}\n\t\t}\n\t\t//verificando tamano\n\t\tif size < 1 {\n\t\t\tfmt.Println(\"RESULTADO: Error en el atributo SIZE\")\n\t\t} else {\n\t\t\t//verificando unidad\n\t\t\tif strings.Compare(unit, \"error\") == 0 {\n\t\t\t\tfmt.Println(\"RESULTADO: Error en el atributo UNIT\")\n\t\t\t} else if strings.Compare(unit, \"\") == 0 {\n\t\t\t\tunit = \"m\"\n\t\t\t} else {\n\t\t\t\t//verificando path\n\t\t\t\tif strings.Compare(path, \"\") == 1 {\n\t\t\t\t\t_, err := os.Stat(strings.ReplaceAll(path, \"\\\"\", \"\"))\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcrearDirectorioSiNoExiste(path)\n\t\t\t\t\t}\n\t\t\t\t\t//En este punto ya tiene que estar creado el directorio si es que no existia\n\t\t\t\t}\n\t\t\t\t//verificando nombre\n\t\t\t\tif strings.Compare(name, \"\") == 1 {\n\t\t\t\t\t_, err := os.Stat(strings.ReplaceAll(path+\"/\"+name, \"\\\"\", \"\"))\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tfmt.Println(\"*********** ATENCION! ***********\")\n\t\t\t\t\t\tfmt.Print(\"¿Desea sobre-escribir el disco?\\n1) SI\\n2) NO\\nIngrese una opcion: \")\n\t\t\t\t\t\tlector := bufio.NewReader(os.Stdin)\n\t\t\t\t\t\tcomando, _ := lector.ReadString('\\n')\n\t\t\t\t\t\tif strings.Compare(strings.TrimSpace(comando), \"1\") == 0 {\n\t\t\t\t\t\t\tsName := strings.Split(name, \".\")\n\t\t\t\t\t\t\tif strings.Compare(strings.ToLower(strings.TrimSpace(sName[1])), \"dsk\") == 0 {\n\t\t\t\t\t\t\t\t//Aqui mando a crear el archivo\n\t\t\t\t\t\t\t\tcrearDisco(size, unit, path+\"/\"+name)\n\t\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Disco creado\")\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Solo se pueden crear discos con extension .DSK\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if strings.Compare(strings.TrimSpace(comando), \"2\") == 0 {\n\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Se ha cancelado la creacion del disco\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Opcion incorrecta, el disco no se creara\")\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//verificar extension\n\t\t\t\t\t\tsName := strings.Split(name, \".\")\n\t\t\t\t\t\tif len(sName) > 1 {\n\t\t\t\t\t\t\tif strings.Compare(strings.ToLower(strings.TrimSpace(sName[1])), \"dsk\") == 0 {\n\t\t\t\t\t\t\t\t//Aqui mando a crear el archivo\n\t\t\t\t\t\t\t\tcrearDisco(size, unit, path+\"/\"+name)\n\t\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Disco creado\")\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Solo se pueden crear discos con extension .DSK\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Println(\"RESULTADO: Error en el nombre del disco a crear\")\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} else {\n\t\tfmt.Println(\"RESULTADO: Faltan atributos obligatorios para el comando MKDISK\")\n\t}\n}", "func (o StatefulPolicyPreservedStateOutput) Disks() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v StatefulPolicyPreservedState) map[string]string { return v.Disks }).(pulumi.StringMapOutput)\n}", "func (r *regulator) List(ctx context.Context, path string) ([]string, error) {\n\tr.enter()\n\tdefer r.exit()\n\n\treturn r.StorageDriver.List(ctx, path)\n}", "func (o StorageClusterSpecCloudStorageOutput) DeviceSpecs() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecCloudStorage) []string { return v.DeviceSpecs }).(pulumi.StringArrayOutput)\n}" ]
[ "0.6661485", "0.65059865", "0.61134917", "0.605816", "0.59936446", "0.58537674", "0.57506585", "0.57285", "0.5711373", "0.57080674", "0.5629568", "0.5626163", "0.5608219", "0.5603344", "0.5567019", "0.5520185", "0.5509504", "0.54874676", "0.54789203", "0.5469682", "0.54639935", "0.5438616", "0.5415243", "0.54110295", "0.5410929", "0.5399408", "0.5393545", "0.53929514", "0.5388736", "0.5388047", "0.53878456", "0.53776956", "0.53760606", "0.5361462", "0.53346056", "0.5332947", "0.53114843", "0.53105694", "0.52956253", "0.52803946", "0.5271137", "0.5256435", "0.52559656", "0.5254462", "0.5254104", "0.52472836", "0.5217821", "0.5217459", "0.5214336", "0.52133536", "0.5211202", "0.5208777", "0.51879174", "0.51777124", "0.51751864", "0.5174724", "0.5173281", "0.516618", "0.5158002", "0.51568466", "0.51536244", "0.5149568", "0.5143999", "0.5139867", "0.5121186", "0.5119634", "0.5103133", "0.5100119", "0.5092575", "0.5085967", "0.5085828", "0.5083306", "0.5078789", "0.5067378", "0.5061142", "0.50330555", "0.5026378", "0.5014993", "0.50143635", "0.5009482", "0.5006192", "0.4992716", "0.4989678", "0.49868652", "0.4986424", "0.49828097", "0.498076", "0.49775472", "0.49744868", "0.49730846", "0.4972478", "0.49618474", "0.49545145", "0.49513665", "0.49487066", "0.49481958", "0.49443632", "0.49401832", "0.49267933", "0.49237615" ]
0.63253814
2
GetHypervisor gets the name of the hypervisor used on the node
func (r *ResourceOracle) GetHypervisor() (string, error) { out, err := exec.Command("virt-what").CombinedOutput() if err != nil { return "", errors.Wrap(err, "could not detect if VM or not") } str := strings.TrimSpace(string(out)) if len(str) == 0 { return "", nil } lines := strings.Fields(str) if len(lines) > 0 { return lines[0], nil } return "", nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *VirtualizationIweClusterAllOf) GetHypervisorBuild() string {\n\tif o == nil || o.HypervisorBuild == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.HypervisorBuild\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHypervisorVersion() string {\n\tif o == nil || o.HypervisorVersion == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.HypervisorVersion\n}", "func (s *Soma) getSupervisor() *super.Supervisor {\n\treturn s.handlerMap.Get(`supervisor`).(*super.Supervisor)\n}", "func (d *KvmSupermicroDriver) GetHost() string {\n\treturn d.Host\n}", "func (c *Client) GetSupervisorVersion() (string, error) {\n\treturn c.stringCall(\"supervisor.getSupervisorVersion\")\n}", "func (a *HyperflexApiService) GetHyperflexHypervisorHostByMoid(ctx context.Context, moid string) ApiGetHyperflexHypervisorHostByMoidRequest {\n\treturn ApiGetHyperflexHypervisorHostByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (l *LoadBalancer) GetHost() string {\n\tl.hostLock.RLock()\n\tdefer l.hostLock.RUnlock()\n\tvar i uint\n\tswitch str.ToLower(l.mode) {\n\tcase \"roundrobin\":\n\tdefault:\n\t\ti = l.index % uint(len(l.hosts))\n\t\tl.index++\n\t\tbreak\n\tcase \"random\":\n\t\ti = uint(rand.Int31n(int32(len(l.hosts))))\n\t\tbreak\n\t}\n\treturn l.hosts[i]\n}", "func (r Virtual_Guest) GetHost() (resp datatypes.Virtual_Host, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getHost\", nil, &r.Options, &resp)\n\treturn\n}", "func GetVirtualHostService(sess *session.Session) Virtual_Host {\n\treturn Virtual_Host{Session: sess}\n}", "func (a *HyperflexApiService) GetHyperflexHypervisorVirtualMachineByMoid(ctx context.Context, moid string) ApiGetHyperflexHypervisorVirtualMachineByMoidRequest {\n\treturn ApiGetHyperflexHypervisorVirtualMachineByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func hypervGetSwitch(name string) (string, error) {\n\tif name != \"\" {\n\t\tif _, _, err := poshCmd(\"Get-VMSwitch\", name); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Could not find switch %s: %v\", name, err)\n\t\t}\n\t\treturn name, nil\n\t}\n\n\t// The Windows 10 Fall Creators Update adds a new 'Default\n\t// Switch'. Check if it is present and if so, use it.\n\tname = \"Default Switch\"\n\tif _, _, err := poshCmd(\"Get-VMSwitch\", name); err == nil {\n\t\treturn name, nil\n\t}\n\n\tout, _, err := poshCmd(\"Get-VMSwitch | Format-Table -Property Name, SwitchType -HideTableHeaders\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not get list of switches: %v\", err)\n\t}\n\tswitches := splitLines(out)\n\tfor _, s := range switches {\n\t\tif len(s) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := strings.Split(s, \" \")\n\t\tif len(t) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(t[len(t)-1:][0], \"External\") {\n\t\t\treturn strings.Join(t[:len(t)-1], \" \"), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Could not find an external switch\")\n}", "func (n node) GetHost() string {\n\treturn n.host\n}", "func (bn *BootstrapNode) GetHost() string {\n\treturn bn.Host\n}", "func (o *Service) GetHw() string {\n\tif o == nil || o.Hw == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hw\n}", "func (r Virtual_Host) GetHardware() (resp datatypes.Hardware_Server, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Host\", \"getHardware\", nil, &r.Options, &resp)\n\treturn\n}", "func GetHost() string {\n\treturn Config().Hostname\n}", "func (o *ListNodesParams) SetHypervisorOsType(hypervisorOsType *string) {\n\to.HypervisorOsType = hypervisorOsType\n}", "func GetVirtualDedicatedHostService(sess *session.Session) Virtual_DedicatedHost {\n\treturn Virtual_DedicatedHost{Session: sess}\n}", "func (n *Namespace) GetHostName(cmd *exec.Cmd) {\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCloneflags: syscall.CLONE_NEWUTS,\n\t}\n}", "func (client *XenClient) PBDGetHost(self string) (result string, err error) {\n\tobj, err := client.APICall(\"PBD.get_host\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}", "func (self *NovaV2) GetHypervisorStatistics() ([]nova.HypervisorStatistics, error) {\n\tvar out HypervisorRespV2\n\terr := nova.Get(self.Client, \"os-hypervisors/detail\", &out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]nova.HypervisorStatistics, len(out.Hypervisors))\n\tfor i, v := range out.Hypervisors {\n\t\tresult[i] = v.ToHypervisorStatistics()\n\t}\n\n\treturn result, nil\n}", "func (s *ProvisionedServer) HostName() string { return s.Server.Hostname }", "func RouterHealth() error { return get(SysRouter) }", "func (lb *LoadBalancer) GetHost() string {\n\thostNum := lb.last + 1\n\n\tif hostNum == lb.max {\n\t\thostNum = 0\n\t}\n\n\tlb.last = hostNum\n\n\treturn (*lb.loop)[hostNum]\n}", "func (o BuildStrategySpecBuildStepsLivenessProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLivenessProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func (client *Client) GetHost(hostParam interface{}) (*model.Host, error) {\n\treturn client.osclt.GetHost(hostParam)\n}", "func Hostname() (string, error)", "func (o ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterBuildStrategySpecBuildStepsLivenessProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func getHealthyNode(clientset kubernetes.Interface) (string, error) {\n\tnodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to get nodes\")\n\t}\n\tfor _, node := range nodes.Items {\n\t\tfor _, cond := range node.Status.Conditions {\n\t\t\tif cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\treturn node.ObjectMeta.Name, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", errors.Wrap(err, \"No healthy node found\")\n}", "func (r Virtual_Guest) GetVirtualRackName() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getVirtualRackName\", nil, &r.Options, &resp)\n\treturn\n}", "func (c *Client) Hostname() (string, error) {\n\treturn c.get(\"/hostname\")\n}", "func (in *ActionLocationIndexInput) SetHypervisorType(value string) *ActionLocationIndexInput {\n\tin.HypervisorType = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"HypervisorType\"] = nil\n\treturn in\n}", "func GetServerHardwareByName(name string) (ov.ServerHardware, error) {\n\tovc := GetOVClient().ovClient\n\tserver, err := ovc.GetServerHardwareByName(name)\n\tif err != nil {\n\t\treturn server, err\n\t}\n\treturn server, nil\n}", "func (e *Executor) GetHost() string {\n\t// return zero value if Executor type or Host field is nil\n\tif e == nil || e.Host == nil {\n\t\treturn \"\"\n\t}\n\n\treturn *e.Host\n}", "func GetHostName() string {\n\treturn os.Getenv(\"HOSTNAME\")\n}", "func (r Virtual_Guest) GetDedicatedHost() (resp datatypes.Virtual_DedicatedHost, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getDedicatedHost\", nil, &r.Options, &resp)\n\treturn\n}", "func getHostname(c *gin.Context) {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc.IndentedJSON(http.StatusOK, gin.H{\"hostname\": name})\n}", "func (o *VirtualizationIweHost) GetHwPowerState() string {\n\tif o == nil || o.HwPowerState == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.HwPowerState\n}", "func Get() string {\n\tif hostname := os.Getenv(\"SCOPE_HOSTNAME\"); hostname != \"\" {\n\t\treturn hostname\n\t}\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn \"(unknown)\"\n\t}\n\treturn hostname\n}", "func getNodename(ctx context.Context) (string, error) {\n\tif config.Datadog.GetBool(\"cloud_foundry\") {\n\t\tboshID := config.Datadog.GetString(\"bosh_id\")\n\t\tif boshID == \"\" {\n\t\t\treturn \"\", fmt.Errorf(\"configuration variable cloud_foundry is set to true, but bosh_id is empty, can't retrieve node name\")\n\t\t}\n\t\treturn boshID, nil\n\t}\n\tku, err := kubelet.GetKubeUtil()\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot get kubeUtil object: %s\", err)\n\t\treturn \"\", err\n\t}\n\treturn ku.GetNodename(ctx)\n}", "func (v *Bridge) GetVirtualMachine(name string) (VirtualMachine, bool) {\n\tvm, ok := v.vms[name]\n\treturn vm, ok\n}", "func GetVirtualization(rw http.ResponseWriter) error {\n\tsystem, role, err := host.Virtualization()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv := struct {\n\t\tSystem string\n\t\tRole string\n\t}{\n\t\tsystem,\n\t\trole,\n\t}\n\n\treturn share.JSONResponse(v, rw)\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHypervisorVersionInfo() SoftwareHyperflexDistributableRelationship {\n\tif o == nil || o.HypervisorVersionInfo == nil {\n\t\tvar ret SoftwareHyperflexDistributableRelationship\n\t\treturn ret\n\t}\n\treturn *o.HypervisorVersionInfo\n}", "func (w *WorkerOperation) GetHost() *Host {\n\treturn nil\n}", "func (node *hostNode) GetHost() host.Host {\n\treturn node.host\n}", "func (m *Machine) Host() string {\n\treturn m.host\n}", "func getRouteHost(t *testing.T, route *routev1.Route, router string) string {\n\tt.Helper()\n\n\tif route == nil {\n\t\tt.Fatal(\"route is nil\")\n\t\treturn \"\"\n\t}\n\n\tfor _, ingress := range route.Status.Ingress {\n\t\tif ingress.RouterName == router {\n\t\t\treturn ingress.Host\n\t\t}\n\t}\n\n\tt.Fatalf(\"failed to find host name for default router in route: %#v\", route)\n\treturn \"\"\n}", "func getHostName() (string){\n host, err := os.Hostname()\n if err != nil {\n fmt.Println(\"%s\", err)\n log.Error(\"get os.HostName error \", err)\n } else {\n //fmt.Println(\"%s\", host)\n log.Debugf(\"get os.HostName success host:\", host)\n }\n return host\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsStartupProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterBuildStrategySpecBuildStepsStartupProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func (r Virtual_Guest) GetOperatingSystem() (resp datatypes.Software_Component_OperatingSystem, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getOperatingSystem\", nil, &r.Options, &resp)\n\treturn\n}", "func GetHostKernelRelease() (string, error) {\n\tinitiatorNSPath := iscsiutil.GetHostNamespacePath(HostProcPath)\n\tmountPath := fmt.Sprintf(\"--mount=%s/mnt\", initiatorNSPath)\n\toutput, err := Execute([]string{}, \"nsenter\", mountPath, \"uname\", \"-r\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn RemoveNewlines(output), nil\n}", "func (o NodeBalancerOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NodeBalancer) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (o *V0037Node) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func GetHostname(ctx context.Context) (string, error) {\n\tmetadataJSON, err := instanceMetaFetcher.Fetch(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar metadata struct {\n\t\tVMID string\n\t}\n\tif err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse Azure instance metadata: %s\", err)\n\t}\n\n\tif err := validate.ValidHostname(metadata.VMID); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn metadata.VMID, nil\n}", "func (s *server) GetNode(context.Context, *goblinpb.GetNodeRequest) (*goblinpb.GetNodeResponse, error) {\n\treturn &goblinpb.GetNodeResponse{\n\t\tName: s.pool.GetName(),\n\t\tAddr: s.pool.GetMemberlistAddress(),\n\t}, nil\n}", "func GetName() string {\n\treturn \"etcd\"\n}", "func (o *VirtualizationIweClusterAllOf) SetHypervisorBuild(v string) {\n\to.HypervisorBuild = &v\n}", "func (o ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterBuildStrategySpecBuildStepsReadinessProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func GetSupervisorURI() (string, error) {\n\tvalue := os.Getenv(constants.BalenaSupervisorURIEnv)\n\tif len(value) > 0 {\n\t\treturn value, nil\n\t}\n\treturn \"\", errors.New(\"Could not get supervisor address\")\n}", "func (endpoint *VhostUserEndpoint) HardwareAddr() string {\n\treturn endpoint.HardAddr\n}", "func HostName() (string, error) {\n\t/*\n\t\tSample output of 'wmic computersystem get Name'\n\n\t\tName\n\t\tWIN-GLU9NEPGT1L\n\t*/\n\tresult, err := readAndParseFromCommandLine(hostNameCmd)\n\tif err != nil {\n\t\treturn \"-1\", err\n\t}\n\thostName := \"\"\n\tif len(result) > 1 {\n\t\thostName = result[1]\n\t}\n\treturn hostName, err\n}", "func GetHost(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *HostState, opts ...pulumi.ResourceOption) (*Host, error) {\n\tvar resource Host\n\terr := ctx.ReadResource(\"vsphere:index/host:Host\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsReadinessProbeHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *PrintConnector) GetOperatingSystem()(*string) {\n val, err := m.GetBackingStore().Get(\"operatingSystem\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o CustomDomainGatewayOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainGateway) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (n Node) Hostname() string {\n\tparts := strings.Split(n.Name, \"@\")\n\tif len(parts) >= 2 {\n\t\treturn parts[1]\n\t}\n\treturn \"\"\n}", "func (c *Config) HostNode() *nodewith.Finder {\n\tswitch c.Protocol {\n\tcase HTTP:\n\t\treturn ossettings.HTTPHostTextField\n\tcase HTTPS:\n\t\treturn ossettings.HTTPSHostTextField\n\tcase Socks:\n\t\treturn ossettings.SocksHostTextField\n\t}\n\treturn nil\n}", "func (r *randomLB) Host() (string, error) {\n\thosts, err := r.subscriber.Hosts()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(hosts) <= 0 {\n\t\treturn \"\", ErrNoHosts\n\t}\n\treturn hosts[r.rnd.Intn(len(hosts))], nil\n}", "func (o CustomDomainDeveloperPortalOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainDeveloperPortal) string { return v.HostName }).(pulumi.StringOutput)\n}", "func GetName() string {\n\treturn routerName\n}", "func (r Virtual_Guest) GetFrontendRouters() (resp datatypes.Hardware, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getFrontendRouters\", nil, &r.Options, &resp)\n\treturn\n}", "func (node *Node) Host() string {\n\treturn node.IP().String() + fmt.Sprintf(\":%d\", node.Port())\n}", "func (o *ShowSystem) GetHostname() string {\n\tif o == nil || IsNil(o.Hostname) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func (o CustomDomainManagementOutput) HostName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomDomainManagement) string { return v.HostName }).(pulumi.StringOutput)\n}", "func (o *V0037Node) GetOperatingSystem() string {\n\tif o == nil || o.OperatingSystem == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.OperatingSystem\n}", "func (o *HyperflexSoftwareVersionPolicy) GetHypervisorVersionOk() (*string, bool) {\n\tif o == nil || o.HypervisorVersion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.HypervisorVersion, true\n}", "func getEndpointHostName(ep string, exec executor.Executor) (string, error) {\n\tres, err := exec.Exec(\"wget\", \"-O-\", \"-q\", fmt.Sprintf(\"http://%s/hostname\", ep))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func getEndpointHostName(ep string, exec executor.Executor) (string, error) {\n\tres, err := exec.Exec(\"wget\", \"-O-\", \"-q\", fmt.Sprintf(\"http://%s/hostname\", ep))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func (nd *Node) GetHost() *Host {\n\treturn nd.host\n}", "func (o *SmartstackBackend) GetHostname() string {\n\tif o == nil || o.Hostname == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Hostname\n}", "func GetVirtualGuestService(sess *session.Session) Virtual_Guest {\n\treturn Virtual_Guest{Session: sess}\n}", "func (rr *roundRobinLB) Host() (string, error) {\n\thosts, err := rr.subscriber.Hosts()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(hosts) <= 0 {\n\t\treturn \"\", ErrNoHosts\n\t}\n\toffset := (atomic.AddUint64(&rr.counter, 1) - 1) % uint64(len(hosts))\n\treturn hosts[offset], nil\n}", "func (d *Driver) GetSSHHostname() (string, error) {\n\treturn d.GetIP()\n}", "func (d *Driver) GetSSHHostname() (string, error) {\n\treturn d.GetIP()\n}", "func (d *Driver) GetSSHHostname() (string, error) {\n\treturn d.GetIP()\n}", "func (b *Backend) Hostname() string {\n\treturn b.hostaddress\n}", "func GetHostname(hostnameOverride string) (string, error) {\n\thostName := hostnameOverride\n\tif len(hostName) == 0 {\n\t\tnodeName, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't determine hostname: %v\", err)\n\t\t}\n\t\thostName = nodeName\n\t}\n\n\t// Trim whitespaces first to avoid getting an empty hostname\n\t// For linux, the hostname is read from file /proc/sys/kernel/hostname directly\n\thostName = strings.TrimSpace(hostName)\n\tif len(hostName) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty hostname is invalid\")\n\t}\n\treturn strings.ToLower(hostName), nil\n}", "func GetHostname(hostnameOverride string) (string, error) {\n\thostName := hostnameOverride\n\tif len(hostName) == 0 {\n\t\tnodeName, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"couldn't determine hostname: %w\", err)\n\t\t}\n\t\thostName = nodeName\n\t}\n\n\t// Trim whitespaces first to avoid getting an empty hostname\n\t// For linux, the hostname is read from file /proc/sys/kernel/hostname directly\n\thostName = strings.TrimSpace(hostName)\n\tif len(hostName) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty hostname is invalid\")\n\t}\n\n\treturn strings.ToLower(hostName), nil\n}", "func (a *HyperflexApiService) GetHyperflexHypervisorHostByMoidExecute(r ApiGetHyperflexHypervisorHostByMoidRequest) (*HyperflexHypervisorHost, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexHypervisorHost\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexHypervisorHostByMoid\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/HypervisorHosts/{Moid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"Moid\"+\"}\", url.PathEscape(parameterToString(r.moid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (o BuildStrategySpecBuildStepsLifecyclePostStartHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLifecyclePostStartHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}", "func (o WorkerDomainOutput) Hostname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *WorkerDomain) pulumi.StringOutput { return v.Hostname }).(pulumi.StringOutput)\n}", "func (in *ActionLocationIndexInput) SetHasHypervisor(value bool) *ActionLocationIndexInput {\n\tin.HasHypervisor = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"HasHypervisor\"] = nil\n\treturn in\n}", "func GetHostname() (string, error) {\n\thostnameData, err := GetHostnameData()\n\treturn hostnameData.Hostname, err\n}", "func (client *NpmClient) getAgentName() string {\n\treturn \"netagent-\" + client.agent.GetAgentID()\n}", "func (client *Client) GetHost(hostParam interface{}) (*model.Host, error) {\n\treturn client.feclt.GetHost(hostParam)\n}", "func GetHostname() string {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn name\n}", "func (m *Message) GetHostname() string {\n\tif m.Lambda != nil {\n\t\treturn m.Lambda.ARN\n\t}\n\thname, err := hostname.Get(context.TODO())\n\tif err != nil {\n\t\t// this scenario is not likely to happen since\n\t\t// the agent cannot start without a hostname\n\t\thname = \"unknown\"\n\t}\n\treturn hname\n}", "func GetIngressHost(ctx context.Context, proxyName, proxyNamespace, proxyPort string, localCluster bool, clusterName string) (string, error) {\n\trestCfg, err := kubeutils.GetConfig(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"getting kube rest config\")\n\t}\n\tkube, err := kubernetes.NewForConfig(restCfg)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"starting kube client\")\n\t}\n\tsvc, err := kube.CoreV1().Services(proxyNamespace).Get(ctx, proxyName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"could not detect '%v' service in %v namespace. \"+\n\t\t\t\"Check that Gloo has been installed properly and is running with 'kubectl get pod -n gloo-system'\",\n\t\t\tproxyName, proxyNamespace)\n\t}\n\tvar svcPort *v1.ServicePort\n\tswitch len(svc.Spec.Ports) {\n\tcase 0:\n\t\treturn \"\", errors.Errorf(\"service %v is missing ports\", proxyName)\n\tcase 1:\n\t\tsvcPort = &svc.Spec.Ports[0]\n\tdefault:\n\t\tfor _, p := range svc.Spec.Ports {\n\t\t\tif p.Name == proxyPort {\n\t\t\t\tsvcPort = &p\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif svcPort == nil {\n\t\t\treturn \"\", errors.Errorf(\"named port %v not found on service %v\", proxyPort, proxyName)\n\t\t}\n\t}\n\n\tvar host, port string\n\tserviceType := svc.Spec.Type\n\tif localCluster {\n\t\tserviceType = v1.ServiceTypeNodePort\n\t}\n\tswitch serviceType {\n\tcase v1.ServiceTypeClusterIP:\n\t\t// There are a few edge cases where glooctl could be run in an environment where this is not a fatal error\n\t\t// However the service type ClusterIP does not accept incoming traffic which doesnt work as a ingress\n\t\tlogger := GetLogger()\n\t\tlogger.Write([]byte(\"Warning: Potentially invalid proxy configuration, proxy may not accepting incoming connections\"))\n\t\thost = svc.Spec.ClusterIP\n\t\tport = fmt.Sprintf(\"%v\", svcPort.Port)\n\tcase v1.ServiceTypeNodePort:\n\t\t// TODO: support more types of NodePort services\n\t\thost, err = getNodeIp(ctx, svc, kube, clusterName)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"\")\n\t\t}\n\t\tport = fmt.Sprintf(\"%v\", svcPort.NodePort)\n\tcase v1.ServiceTypeLoadBalancer:\n\t\tif len(svc.Status.LoadBalancer.Ingress) == 0 {\n\t\t\treturn \"\", errors.Errorf(\"load balancer ingress not found on service %v\", proxyName)\n\t\t}\n\t\thost = svc.Status.LoadBalancer.Ingress[0].Hostname\n\t\tif host == \"\" {\n\t\t\thost = svc.Status.LoadBalancer.Ingress[0].IP\n\t\t}\n\t\tport = fmt.Sprintf(\"%v\", svcPort.Port)\n\t}\n\treturn host + \":\" + port, nil\n}", "func (o ClusterBuildStrategySpecBuildStepsLifecyclePostStartHttpGetPtrOutput) Host() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterBuildStrategySpecBuildStepsLifecyclePostStartHttpGet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Host\n\t}).(pulumi.StringPtrOutput)\n}" ]
[ "0.6069008", "0.5980366", "0.54064214", "0.53660136", "0.5365084", "0.5310516", "0.52834", "0.5210815", "0.5186667", "0.5132685", "0.5097898", "0.509749", "0.50615424", "0.4995323", "0.4980722", "0.49395666", "0.49015778", "0.4867946", "0.48673707", "0.48556107", "0.48120072", "0.48086178", "0.47985443", "0.47824582", "0.47730002", "0.47694278", "0.47655305", "0.4759348", "0.47476834", "0.47391832", "0.47206175", "0.47032407", "0.4698156", "0.46938932", "0.46910602", "0.4657933", "0.46539962", "0.46539706", "0.4653601", "0.46489477", "0.46424082", "0.46386206", "0.46196443", "0.46181864", "0.46093136", "0.46005055", "0.45887154", "0.4570642", "0.45600188", "0.45554805", "0.45425582", "0.45371673", "0.4534767", "0.45312726", "0.45304996", "0.45173988", "0.45170283", "0.45165583", "0.4508396", "0.45068365", "0.45055524", "0.4495432", "0.4492785", "0.44911945", "0.4490508", "0.44855365", "0.44755846", "0.44728878", "0.44598472", "0.44582012", "0.4456551", "0.44547278", "0.44467565", "0.4446631", "0.4444649", "0.4438729", "0.4438308", "0.44347957", "0.44347957", "0.4426487", "0.44207895", "0.44206497", "0.44182283", "0.44179466", "0.44179466", "0.44179466", "0.44160682", "0.44140938", "0.4408211", "0.44069445", "0.44041145", "0.44039154", "0.44035596", "0.4402397", "0.44015276", "0.4400557", "0.44002104", "0.43990275", "0.4398891", "0.43955028" ]
0.759946
0
GPUs returns the list of available GPUs as PCI devices
func (r *ResourceOracle) GPUs() ([]PCI, error) { return ListPCI(GPU) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func detectGPUs(visibleGPUs string) ([]device.Device, error) {\n\tflags := detectGPUsArgs[1:]\n\tif visibleGPUs != \"\" {\n\t\tflags = append(flags, fmt.Sprintf(detectGPUsIDFlagTpl, visibleGPUs))\n\t}\n\n\t// #nosec G204\n\tcmd := exec.Command(detectGPUsArgs[0], flags...)\n\tout, err := cmd.Output()\n\n\tif execError, ok := err.(*exec.Error); ok && execError.Err == exec.ErrNotFound {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\tlog.WithError(err).WithField(\"output\", string(out)).Warnf(\"error while executing nvidia-smi\")\n\t\treturn nil, nil\n\t}\n\n\tdevices := make([]device.Device, 0)\n\n\tr := csv.NewReader(strings.NewReader(string(out)))\n\tfor {\n\t\trecord, err := r.Read()\n\t\tswitch {\n\t\tcase err == io.EOF:\n\t\t\treturn devices, nil\n\t\tcase err != nil:\n\t\t\treturn nil, errors.Wrap(err, \"error parsing output of nvidia-smi as CSV\")\n\t\tcase len(record) != 3:\n\t\t\treturn nil, errors.New(\n\t\t\t\t\"error parsing output of nvidia-smi; GPU record should have exactly 3 fields\")\n\t\t}\n\n\t\tindex, err := strconv.Atoi(strings.TrimSpace(record[0]))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(\n\t\t\t\terr, \"error parsing output of nvidia-smi; index of GPU cannot be converted to int\")\n\t\t}\n\n\t\tbrand := strings.TrimSpace(record[1])\n\t\tuuid := strings.TrimSpace(record[2])\n\n\t\tdevices = append(devices, device.Device{ID: index, Brand: brand, UUID: uuid, Type: device.GPU})\n\t}\n}", "func detectDevices(visibleGPUs string) ([]device.Device, error) {\n\tswitch devices, err := detectGPUs(visibleGPUs); {\n\tcase err != nil:\n\t\treturn nil, errors.Wrap(err, \"error while gathering GPU info through nvidia-smi command\")\n\tcase len(devices) != 0:\n\t\treturn devices, nil\n\t}\n\n\treturn detectCPUs()\n}", "func (cfg *Config) CheckAvailableGPUs(kubeClientset kubernetes.Interface) {\n\tnodes, err := kubeClientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{LabelSelector: \"!node-role.kubernetes.io/control-plane,!node-role.kubernetes.io/master\"})\n\tif err != nil {\n\t\tlog.Printf(\"Error getting list of nodes: %v\\n\", err)\n\t}\n\tfor _, node := range nodes.Items {\n\t\tgpu := node.Status.Allocatable[\"nvidia.com/gpu\"]\n\t\tif gpu.Value() > 0 {\n\t\t\tcfg.GPUAvailable = true\n\t\t\treturn\n\t\t}\n\t}\n}", "func (provider *cloudStackCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn availableGPUTypes\n}", "func (k *kamateraCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn nil\n}", "func (d *HetznerCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn nil\n}", "func GPUVendors() [2]string {\n\treturn [...]string{\n\t\t\"amd.com/gpu\",\n\t\t\"nvidia.com/gpu\",\n\t}\n}", "func (tencentcloud *tencentCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn availableGPUTypes\n}", "func showGPU(cmd *cobra.Command, args []string) error {\n\tgpu, err := ghw.GPU()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error getting GPU info\")\n\t}\n\n\tswitch outputFormat {\n\tcase outputFormatHuman:\n\t\tfmt.Printf(\"%v\\n\", gpu)\n\n\t\tfor _, card := range gpu.GraphicsCards {\n\t\t\tfmt.Printf(\" %v\\n\", card)\n\t\t}\n\tcase outputFormatJSON:\n\t\tfmt.Printf(\"%s\\n\", gpu.JSONString(pretty))\n\tcase outputFormatYAML:\n\t\tfmt.Printf(\"%s\", gpu.YAMLString())\n\t}\n\treturn nil\n}", "func (s *MultipassServer) GetAvailableGPUTypes(ctx context.Context, request *apigrpc.CloudProviderServiceRequest) (*apigrpc.GetAvailableGPUTypesReply, error) {\n\tglog.V(5).Infof(\"Call server GetAvailableGPUTypes: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(constantes.ErrMismatchingProvider)\n\t\treturn nil, fmt.Errorf(constantes.ErrMismatchingProvider)\n\t}\n\n\tgpus := make(map[string]string)\n\n\treturn &apigrpc.GetAvailableGPUTypesReply{\n\t\tAvailableGpuTypes: gpus,\n\t}, nil\n}", "func EnumGpuDevicesNV(hGpu unsafe.Pointer, iDeviceIndex unsafe.Pointer, lpGpuDevice unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpEnumGpuDevicesNV, 3, uintptr(hGpu), uintptr(iDeviceIndex), uintptr(lpGpuDevice))\n\treturn (unsafe.Pointer)(ret)\n}", "func (client *XenClient) VGPUGetAll() (result []string, err error) {\n\tobj, err := client.APICall(\"VGPU.get_all\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult = make([]string, len(obj.([]interface{})))\n\tfor i, value := range obj.([]interface{}) {\n\t\tresult[i] = value.(string)\n\t}\n\n\treturn\n}", "func getAllDevices(t *testing.T) []*goscaleio.Device {\n\tpool := getStoragePool(t)\n\tassert.NotNil(t, pool)\n\tif pool == nil {\n\t\treturn nil\n\t}\n\n\tvar allDevice []*goscaleio.Device\n\tdevices, err := pool.GetDevice()\n\tassert.Nil(t, err)\n\tassert.NotZero(t, len(devices))\n\tfor _, d := range devices {\n\t\t// create a device to return to the caller\n\t\toutDevice := goscaleio.NewDeviceEx(C, &d)\n\t\tallDevice = append(allDevice, outDevice)\n\t\t// create a device via NewDevice for testing purposes\n\t\ttempDevice := goscaleio.NewDevice(C)\n\t\ttempDevice.Device = &d\n\t\tassert.Equal(t, outDevice.Device.ID, tempDevice.Device.ID)\n\t}\n\treturn allDevice\n\n}", "func (s SchedulerServer) ListGpuModels(\n\tctx context.Context,\n\tr *scheduler_proto.ListGpuModelsRequest,\n) (*scheduler_proto.ListGpuModelsResponse, error) {\n\tq := s.db.Table(\"nodes\").\n\t\tSelect(\"gpu_model, gpu_class, SUM(gpu_capacity) AS gpu_capacity, SUM(gpu_available) AS gpu_available, \" +\n\t\t\t\"COUNT(id) AS nodes_count\").\n\t\tWhere(\"status = ?\", utils.Enum(scheduler_proto.Node_STATUS_ONLINE)).\n\t\tGroup(\"gpu_class, gpu_model\").\n\t\tOrder(\"gpu_class, gpu_model\")\n\n\tif r.GpuClass != 0 {\n\t\tq = q.Where(\"gpu_class = ?\", utils.Enum(r.GpuClass))\n\t}\n\n\tresponse := &scheduler_proto.ListGpuModelsResponse{}\n\n\tif err := utils.HandleDBError(q.Scan(&response.GpuModels)); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, nil\n\n}", "func detectCPUs() ([]device.Device, error) {\n\tswitch cpuInfo, err := cpu.Info(); {\n\tcase err != nil:\n\t\treturn nil, errors.Wrap(err, \"error while gathering CPU info\")\n\tcase len(cpuInfo) == 0:\n\t\treturn nil, errors.New(\"no CPUs detected\")\n\tdefault:\n\t\tbrand := fmt.Sprintf(\"%s x %d physical cores\", cpuInfo[0].ModelName, cpuInfo[0].Cores)\n\t\tuuid := cpuInfo[0].VendorID\n\t\treturn []device.Device{{ID: 0, Brand: brand, UUID: uuid, Type: device.CPU}}, nil\n\t}\n}", "func getAllDevices() ([]C.nvmlDevice_t, error) {\n\tvar devices []C.nvmlDevice_t\n\n\tdeviceCount, err := nvmlDeviceGetCount()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor i := 0; i < deviceCount; i++ {\n\t\tvar device C.nvmlDevice_t\n\t\tresult := C.bridge_nvmlDeviceGetHandleByIndex(C.uint(i), &device)\n\t\tif result != C.NVML_SUCCESS {\n\t\t\treturn devices, errors.New(\"nvmlDeviceGetHandleByIndex returns error\")\n\t\t}\n\n\t\tdevices = append(devices, device)\n\t}\n\n\tif len(devices) == 0 {\n\t\treturn devices, errors.New(\"No devices found\")\n\t}\n\n\treturn devices, nil\n}", "func (*GetAvailableGPUTypesRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{12}\n}", "func (s *gPUQuotaLister) GPUQuotas(namespace string) GPUQuotaNamespaceLister {\n\treturn gPUQuotaNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (this *i2c) Devices() []gopi.I2CBus {\n\tvar devices []gopi.I2CBus\n\tfor bus := uint(minBus); bus <= uint(maxBus); bus++ {\n\t\tif _, err := os.Stat(linux.I2CDevice(bus)); err == nil {\n\t\t\tdevices = append(devices, gopi.I2CBus(bus))\n\t\t}\n\t}\n\treturn devices\n}", "func (ng *NodeGroup) isGpu() bool {\n\tflavor, err := ng.Manager.getFlavorByName(ng.Flavor)\n\tif err != nil {\n\t\t// Fallback when we are unable to get the flavor: refer to the only category\n\t\t// known to be a GPU flavor category\n\t\treturn strings.HasPrefix(ng.Flavor, GPUMachineCategory)\n\t}\n\n\treturn flavor.GPUs > 0\n}", "func gpuCapacity(self *core_v1.ResourceList) *resource.Quantity {\n\tif val, ok := (*self)[ResourceGPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{Format: resource.DecimalSI}\n}", "func GetDevices() []*devicepluginapi.Device {\n\tsizeMB := GetEPCSize() / 1024 / 1024\n\tdevs := make([]*devicepluginapi.Device, 0, sizeMB)\n\n\tfor i := uint64(0); i < sizeMB; i++ {\n\t\tdevs = append(devs, &devicepluginapi.Device{\n\t\t\tID: strconv.FormatUint(i, 10),\n\t\t\tHealth: devicepluginapi.Healthy,\n\t\t})\n\t}\n\n\treturn devs\n}", "func (computersystem *ComputerSystem) PCIeDevices() ([]*PCIeDevice, error) {\n\tvar result []*PCIeDevice\n\n\tcollectionError := common.NewCollectionError()\n\tfor _, pciedeviceLink := range computersystem.pcieDevices {\n\t\tpciedevice, err := GetPCIeDevice(computersystem.GetClient(), pciedeviceLink)\n\t\tif err != nil {\n\t\t\tcollectionError.Failures[pciedeviceLink] = err\n\t\t} else {\n\t\t\tresult = append(result, pciedevice)\n\t\t}\n\t}\n\n\tif collectionError.Empty() {\n\t\treturn result, nil\n\t}\n\n\treturn result, collectionError\n}", "func (m *MockCandidatePropertyGetter) UnusedGpuDevices() []*core.IsolatedDeviceDesc {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UnusedGpuDevices\")\n\tret0, _ := ret[0].([]*core.IsolatedDeviceDesc)\n\treturn ret0\n}", "func (b *MonopAmpBridge) AvailableDevices(ctx context.Context) ([]*pb.Device, error) {\n\treturn nil, nil\n}", "func TestGPUWithoutNUMANodeInfo(t *testing.T) {\n\tif _, ok := os.LookupEnv(\"GHW_TESTING_SKIP_GPU\"); ok {\n\t\tt.Skip(\"Skipping PCI tests.\")\n\t}\n\n\ttestdataPath, err := testdata.SnapshotsDirectory()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected nil err, but got %v\", err)\n\t}\n\n\tworkstationSnapshot := filepath.Join(testdataPath, \"linux-amd64-amd-ryzen-1600.tar.gz\")\n\t// from now on we use constants reflecting the content of the snapshot we requested,\n\t// which we reviewed beforehand. IOW, you need to know the content of the\n\t// snapshot to fully understand this test. Inspect it using\n\t// GHW_SNAPSHOT_PATH=\"/path/to/linux-amd64-amd-ryzen-1600.tar.gz\" ghwc gpu\n\n\ttmpRoot, err := os.MkdirTemp(\"\", \"ghw-gpu-testing-*\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to create temporary directory: %v\", err)\n\t}\n\n\t_, err = snapshot.UnpackInto(workstationSnapshot, tmpRoot, 0)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to unpack %q into %q: %v\", workstationSnapshot, tmpRoot, err)\n\t}\n\tdefer func() {\n\t\t_ = snapshot.Cleanup(tmpRoot)\n\t}()\n\n\terr = os.Remove(filepath.Join(tmpRoot, \"/sys/class/drm/card0/device/numa_node\"))\n\tif err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\tt.Fatalf(\"Cannot remove the NUMA node info: %v\", err)\n\t}\n\n\tinfo, err := gpu.New(option.WithChroot(tmpRoot))\n\tif err != nil {\n\t\tt.Fatalf(\"Expected nil err, but got %v\", err)\n\t}\n\tif info == nil {\n\t\tt.Fatalf(\"Expected non-nil GPUInfo, but got nil\")\n\t}\n\tif len(info.GraphicsCards) == 0 {\n\t\tt.Fatalf(\"Expected >0 GPU cards, but found 0.\")\n\t}\n}", "func ListDevices() ([]image.Device, error) {\n\tcmd := exec.Command(\"gst-device-monitor-1.0\")\n\tbuf, err := cmd.Output()\n\tif err != nil {\n\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\terr = errInstallHint\n\t\t}\n\t\treturn nil, fmt.Errorf(\"listing devices using gst-device-monitor-1.0: %v\", err)\n\t}\n\n\tvar r []device\n\tvar d *device\n\tb := bufio.NewScanner(bytes.NewReader(buf))\n\tfor b.Scan() {\n\t\ts := strings.TrimSpace(b.Text())\n\t\tif s == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif s == \"Device found:\" {\n\t\t\tif d != nil {\n\t\t\t\tr = append(r, *d)\n\t\t\t}\n\t\t\td = &device{RawCaps: []string{}, Caps: []image.DeviceCap{}}\n\t\t\tcontinue\n\t\t}\n\n\t\tif d == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(s, \"name :\") {\n\t\t\td.Name = strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"class :\") {\n\t\t\td.DeviceClass = strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"caps :\") {\n\t\t\tcap := strings.TrimSpace(strings.SplitN(s, \":\", 2)[1])\n\t\t\td.RawCaps = append(d.RawCaps, cap)\n\t\t\td.inCapMode = true\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(s, \"properties:\") {\n\t\t\td.inCapMode = false\n\t\t\tcontinue\n\t\t}\n\t\tif d.inCapMode {\n\t\t\td.RawCaps = append(d.RawCaps, s)\n\t\t}\n\t\tif strings.HasPrefix(s, \"device.path =\") {\n\t\t\td.ID = strings.TrimSpace(strings.SplitN(s, \"=\", 2)[1])\n\t\t}\n\t}\n\tif err := b.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif d != nil && d.ID != \"\" {\n\t\tr = append(r, *d)\n\t}\n\n\tvar devs []image.Device\n\tfor _, d := range r {\n\t\tif d.DeviceClass != \"Video/Source\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, rc := range d.RawCaps {\n\t\t\tif !strings.HasPrefix(rc, \"video/x-raw\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmw := widthRegexp.FindStringSubmatch(rc)\n\t\t\tmh := heightRegexp.FindStringSubmatch(rc)\n\t\t\tmf := framerateRegexp.FindStringSubmatch(rc)\n\t\t\tif mw == nil || mh == nil || mf == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twidth, werr := strconv.ParseInt(mw[1], 10, 32)\n\t\t\theight, herr := strconv.ParseInt(mh[1], 10, 32)\n\t\t\tframerate, ferr := strconv.ParseInt(mf[1], 10, 32)\n\t\t\tif werr != nil || herr != nil || ferr != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif width != 0 && height != 0 && framerate != 0 {\n\t\t\t\td.Caps = append(d.Caps, image.DeviceCap{\n\t\t\t\t\tWidth: int(width),\n\t\t\t\t\tHeight: int(height),\n\t\t\t\t\tFramerate: int(framerate),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif len(d.Caps) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdistance := func(a image.DeviceCap) int {\n\t\t\treturn abs(a.Width-640)*abs(a.Height-480) + abs(a.Width-640) + abs(a.Height-480)\n\t\t}\n\n\t\tsort.Slice(d.Caps, func(i, j int) bool {\n\t\t\treturn distance(d.Caps[i]) < distance(d.Caps[j])\n\t\t})\n\n\t\tdevs = append(devs, image.Device{\n\t\t\tID: d.ID,\n\t\t\tName: d.Name,\n\t\t\tCaps: d.Caps,\n\t\t})\n\t}\n\tif len(devs) == 0 {\n\t\treturn nil, fmt.Errorf(\"no devices found\")\n\t}\n\n\treturn devs, nil\n}", "func (*GetAvailableGPUTypesResponse) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{13}\n}", "func CalculateGpuSummary() string {\n\tvar GpuFreeMemorys []string\n\tfor _, g := range GPUs {\n\t\telement := strings.Join(\n\t\t\t[]string{\n\t\t\t\tstrconv.FormatInt(int64(g.ID), 10),\n\t\t\t\tstrconv.FormatInt(int64(g.FreeMemory), 10)},\n\t\t\t\"_\")\n\t\tGpuFreeMemorys = append(GpuFreeMemorys, element)\n\t}\n\treturn strings.Join(GpuFreeMemorys, \".\")\n}", "func (r Virtual_Guest) GetGpuCount() (resp int, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getGpuCount\", nil, &r.Options, &resp)\n\treturn\n}", "func (rp *ResourcePoolImpl) GetDevices() map[string]*pluginapi.Device {\n\tdevices := make(map[string]*pluginapi.Device)\n\tfor id, dev := range rp.devicePool {\n\t\tdevices[id] = dev.GetAPIDevice()\n\t}\n\treturn devices\n}", "func (m *User) GetManagedDevices()([]ManagedDeviceable) {\n return m.managedDevices\n}", "func (r *Resources) GetGPU() float64 {\n\treturn r.GPU\n}", "func getDeviceList() *[]device {\n\tdevices := make([]device, 0)\n\n\tfor _, group := range Conf.DevGroups {\n\n\t\t// for current group, append devices to the list\n\t\tfor i := 1; i <= group.DeviceNum; i++ {\n\t\t\tdevices = append(devices, device{group.Prefix + strconv.Itoa(i), group.Firmware, false, group.IoTHub})\n\t\t}\n\t}\n\n\treturn &devices\n}", "func (r Virtual_DedicatedHost) GetPciDevices() (resp []datatypes.Virtual_Host_PciDevice, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_DedicatedHost\", \"getPciDevices\", nil, &r.Options, &resp)\n\treturn\n}", "func (b *Benchmark) SelectGPU(gpuIDs []int) {\n\tif len(gpuIDs) > 1 {\n\t\tpanic(\"multi-GPU is not supported by DNN workloads\")\n\t}\n}", "func setGPUEngine(clock, device int, name string) {\n\trequest := RpcRequest{(fmt.Sprintf(\"{\\\"command\\\":\\\"gpuengine\\\",\\\"parameter\\\":\\\"%v,%v\\\"}\", device, clock)), make(chan []byte), name}\n\trequest.Send()\n}", "func TestGetDevices(t *testing.T) {\n\tgetAllDevices(t)\n\tgetAllDevicesFromSystem(t)\n\tTestGetDeviceByField(t)\n}", "func (t *Topology) AllDevices() map[string]*PCIDevice {\n\tdevsByName := make(map[string]*PCIDevice)\n\tif t == nil {\n\t\treturn devsByName\n\t}\n\n\tfor _, numaNode := range t.NUMANodes {\n\t\tfor _, devs := range numaNode.PCIDevices {\n\t\t\tfor _, dev := range devs {\n\t\t\t\tdevsByName[dev.Name] = dev\n\t\t\t}\n\t\t}\n\t}\n\treturn devsByName\n}", "func setGPUMemory(clock, device int, name string) {\n\trequest := RpcRequest{(fmt.Sprintf(\"{\\\"command\\\":\\\"gpumem\\\",\\\"parameter\\\":\\\"%v,%v\\\"}\", device, clock)), make(chan []byte), name}\n\trequest.Send()\n}", "func (h *DeviceHandler) DeviceList(ctx context.Context, sessionID int) ([]keybase1.Device, error) {\n\tuis := libkb.UIs{\n\t\tLogUI: h.getLogUI(sessionID),\n\t\tSessionID: sessionID,\n\t}\n\teng := engine.NewDevList(h.G())\n\tm := libkb.NewMetaContext(ctx, h.G()).WithUIs(uis)\n\tif err := engine.RunEngine2(m, eng); err != nil {\n\t\treturn nil, err\n\t}\n\treturn eng.List(), nil\n}", "func AvailableDevices(budgetDataPath string) DeviceList {\n\tdevicePaths, _ := filepath.Glob(\n\t\tfilepath.Join(budgetDataPath, \"devices\", \"*.ydevice\"),\n\t)\n\tdevices := make(DeviceList, 0)\n\tfor _, path := range devicePaths {\n\t\tdevice := Device{}\n\t\tfile, _ := os.Open(path)\n\t\tjsonDecoder := json.NewDecoder(file)\n\t\tjsonDecoder.Decode(&device)\n\t\tdevices = append(devices, device)\n\t}\n\treturn devices\n}", "func (am *Antman) GetGpusInfoFromEtcd(nodeName string) (gpuUtils []float64, gpuMems []float64) {\n\tklog.Infof(\"in GetGpusInfoFromEtcd for nodeName : %v\", nodeName)\n\tvar utils []float64\n\tvar mems []float64\n\tconst (\n\t\tPeriodInSeconds = 30\n\t)\n\tvar count, nowIndex, nowTime int\n\tvar err error\n\t// TODO # GPU from k8s api\n\tnodeInfo, err := am.frameworkHandle.SnapshotSharedLister().NodeInfos().Get(nodeName)\n\tnum_gpus := int(nodeInfo.AllocatableResource().ScalarResources[\"nvidia.com/gpu\"])\n\tfor gpu_id := 0; gpu_id < num_gpus; gpu_id++ {\n\t\t// the number of gpu statistics maintained\n\t\tcountKey := nodeName + \"/\" + strconv.Itoa(gpu_id) + \"/cnt\"\n\t\tcountStr := am.etcdWrapper.ReadEtcd(&countKey)\n\t\tif count, err = strconv.Atoi(*countStr); err == nil {\n\t\t\tklog.Infof(\"[%v] count: %v\", gpu_id, count)\n\t\t}\n\n\t\t// the index of the last statistic\n\t\tnowIndexKey := nodeName + \"/\" + strconv.Itoa(gpu_id) + \"/nowIndex\"\n\t\tnowIndexStr := am.etcdWrapper.ReadEtcd(&nowIndexKey)\n\t\tif nowIndex, err = strconv.Atoi(*nowIndexStr); err == nil {\n\t\t\tklog.Infof(\"[%v] nowIndex: %v\", gpu_id, nowIndex)\n\t\t}\n\n\t\t// the timestamp of the last index\n\t\tnowTimeKey := nodeName + \"/\" + strconv.Itoa(gpu_id) + \"/nowTime\"\n\t\tnowTimeStr := am.etcdWrapper.ReadEtcd(&nowTimeKey)\n\t\tif nowTime, err = strconv.Atoi(*nowTimeStr); err == nil {\n\t\t\tklog.Infof(\"[%v] nowTime: %v\", gpu_id, nowTime)\n\t\t}\n\n\t\t// the statistics are stored in [0, count) using a Circular Queue\n\t\t// make sure that PeriodInSeconds is smaller than count\n\t\tif PeriodInSeconds > count {\n\t\t\tklog.Errorf(\"PeriodInSeconds[%v] should smaller than count[%v]\", PeriodInSeconds, count)\n\t\t}\n\n\t\t// ave gpu util in PeriodInSeconds\n\t\t// peak gpu mem in PeriodInSeconds\n\t\taveUtil := 0.0\n\t\tpeakMem := 0.0\n\t\tfor index := 0; index < PeriodInSeconds; index++ {\n\t\t\ti := (index - (PeriodInSeconds - nowIndex) + count) % count\n\t\t\tutilKey := nodeName + \"/\" + strconv.Itoa(gpu_id) + \"/util\" + \"/\" + strconv.Itoa(i)\n\t\t\tmemKey := nodeName + \"/\" + strconv.Itoa(gpu_id) + \"/mem\" + \"/\" + strconv.Itoa(i)\n\t\t\tgpuUtilStr := am.etcdWrapper.ReadEtcd(&utilKey)\n\t\t\tgpuMemStr := am.etcdWrapper.ReadEtcd(&memKey)\n\t\t\tif gpuUtil, err := strconv.ParseFloat(*gpuUtilStr, 64); err == nil {\n\t\t\t\taveUtil += gpuUtil\n\t\t\t}\n\t\t\tif gpuMem, err := strconv.ParseFloat(*gpuMemStr, 64); err == nil {\n\t\t\t\tpeakMem = math.Max(peakMem, gpuMem)\n\t\t\t}\n\t\t}\n\t\taveUtil = aveUtil / PeriodInSeconds\n\n\t\tutils = append(utils, aveUtil)\n\t\tmems = append(mems, peakMem)\n\t}\n\treturn utils, mems\n}", "func (o *KubernetesNodeGroupProfile) GetGpuConfig() []InfraBaseGpuConfiguration {\n\tif o == nil {\n\t\tvar ret []InfraBaseGpuConfiguration\n\t\treturn ret\n\t}\n\treturn o.GpuConfig\n}", "func hasMIGCapableGPU(labels map[string]string) bool {\n\tif value, exists := labels[vgpuHostDriverLabelKey]; exists && value != \"\" {\n\t\t// vGPU node\n\t\treturn false\n\t}\n\n\tif value, exists := labels[migCapableLabelKey]; exists {\n\t\treturn value == migCapableLabelValue\n\t}\n\n\t// check product label if mig.capable label does not exist\n\tif value, exists := labels[gpuProductLabelKey]; exists {\n\t\tif strings.Contains(strings.ToLower(value), \"h100\") ||\n\t\t\tstrings.Contains(strings.ToLower(value), \"a100\") ||\n\t\t\tstrings.Contains(strings.ToLower(value), \"a30\") {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func GetDevices() (devices []storage.Device, err error) {\n\tvar out []byte\n\tout, err = exec.Command(\"lsblk\", \"--output=NAME,TYPE,SIZE,FSTYPE,PKNAME\", \"-P\", \"--bytes\", \"-I\",\n\t\tstrings.Join(supportedDeviceTypes, \",\")).Output()\n\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\terr = trace.Wrap(err, \"lsblk error=%v, stderr=%q, out=%q\", exitErr, exitErr.Stderr, out)\n\t\treturn nil, err\n\t} else if err != nil {\n\t\treturn nil, trace.Wrap(err, \"failed to list block devices: error=%v, output=%s\", err, out)\n\t}\n\n\tdevices, err = parseDevices(bytes.NewReader(out))\n\tif err != nil {\n\t\terr = trace.Wrap(err, \"error parsing block device list: lsblk=%q : error=%v\", out, err)\n\t}\n\n\treturn devices, err\n}", "func (a *cpuAccumulator) freeCPUs() []int {\n\treturn a.sortAvailableCPUs()\n}", "func main() {\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tif err := dcgm.Init(dcgm.Embedded); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer func() {\n\t\tif err := dcgm.Shutdown(); err != nil {\n\t\t\tlog.Panicln(err)\n\t\t}\n\t}()\n\n\tgpus, err := dcgm.GetSupportedDevices()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tticker := time.NewTicker(time.Second * 1)\n\tdefer ticker.Stop()\n\n\tfmt.Println(header)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tfor _, gpu := range gpus {\n\t\t\t\tst, err := dcgm.GetDeviceStatus(gpu)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Panicln(err)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%5d %5d %5d %5d %5d %5d %5d %5d %5d\\n\",\n\t\t\t\t\tgpu, int64(*st.Power), *st.Temperature, *st.Utilization.GPU, *st.Utilization.Memory,\n\t\t\t\t\t*st.Utilization.Encoder, *st.Utilization.Decoder, *st.Clocks.Memory, *st.Clocks.Cores)\n\t\t\t}\n\n\t\tcase <-sigs:\n\t\t\treturn\n\t\t}\n\t}\n}", "func Devices() ([]*DeviceInfo, error) {\n\t_, devs, err := hostsAndDevices()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn devs, nil\n}", "func NewGPUQuotaLister(indexer cache.Indexer) GPUQuotaLister {\n\treturn &gPUQuotaLister{indexer: indexer}\n}", "func discoverManagedDevices() ([]string, []string) {\n\tstdErr.Println(\"Discovering managed devices...\")\n\n\tbody, bodyErr := client.QueryAPI(gqlDeviceListQuery)\n\tif bodyErr != nil {\n\t\tstdErr.Fatalf(\"Could not fetch device list: %s\\n\", bodyErr)\n\t}\n\tproactiveTokenRefresh()\n\n\tdevices := deviceList{}\n\tjsonErr := json.Unmarshal(body, &devices)\n\tif jsonErr != nil {\n\t\tstdErr.Fatalf(\"Could not decode JSON: %s\\n\", jsonErr)\n\t}\n\n\tvar upDevices []string\n\tvar downDevices []string\n\tfor _, d := range devices.Data.Network.Devices {\n\t\tif d.Up {\n\t\t\tupDevices = append(upDevices, d.IP)\n\t\t} else {\n\t\t\tdownDevices = append(downDevices, d.IP)\n\t\t}\n\t}\n\tsort.Strings(upDevices)\n\tstdErr.Println(\"Finished discovering managed devices.\")\n\n\treturn upDevices, downDevices\n}", "func (client *XenClient) VGPUGetDevice(self string) (result string, err error) {\n\tobj, err := client.APICall(\"VGPU.get_device\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}", "func ScanDevices() []FoundDevice {\n\tctx := gousb.NewContext()\n\tctx.Debug(0)\n\tdefer ctx.Close()\n\t// Get the list of device that match TMK's vendor id\n\tdevs, _ := ctx.OpenDevices(isSupported)\n\tvar devices = []FoundDevice{}\n\tfor _, dev := range devs {\n\n\t\tmetadata, _ := getMetdata(dev.Desc)\n\t\tdevices = append(devices, FoundDevice{\n\t\t\tStatus: &DeviceStatus{isDfu: metadata.Name == \"dfu\"},\n\t\t\tDescription: dev.Desc,\n\t\t\tMetadata: metadata,\n\t\t})\n\t}\n\tfor _, d := range devs {\n\t\td.Close()\n\t}\n\treturn devices\n}", "func (e *Engine) ListDevices() ([]*portaudio.DeviceInfo, error) {\n\tif !e.initialized {\n\t\treturn nil, errorEngineNotInitialized\n\t}\n\treturn portaudio.Devices()\n}", "func (db *MongoDB) GetDevices(c echo.Context) (err error) {\n\td := db.PipeDevice(c, \"\")\n\treturn c.JSON(http.StatusOK, &d)\n}", "func (m *User) GetRegisteredDevices()([]DirectoryObjectable) {\n return m.registeredDevices\n}", "func (r *GpuReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\tr.Logger = ctrl.Log.WithName(\"gpu-controller\")\n\tr.Logger.V(1).Info(\"starting gpu controller\")\n\n\t// use clientSet to get resources from the API Server, not from Informer's cache\n\tclientSet, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tr.Logger.Error(err, \"failed to init\")\n\t\treturn nil\n\t}\n\n\t// init node-gpu-info configmap\n\tr.Logger.V(1).Info(\"initializing node-gpu-info configmap\")\n\tif err := r.initGPUInfoCM(context.Background(), clientSet); err != nil {\n\t\treturn err\n\t}\n\n\t// build index for node which have GPU\n\tif err := mgr.GetFieldIndexer().IndexField(context.Background(), &corev1.Node{}, NodeIndexKey, func(rawObj client.Object) []string {\n\t\tnode := rawObj.(*corev1.Node)\n\t\tif _, ok := node.Labels[NvidiaGPUProduct]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn []string{GPU}\n\t}); err != nil {\n\t\treturn err\n\t}\n\t// build index for pod which use GPU\n\tif err := mgr.GetFieldIndexer().IndexField(context.Background(), &corev1.Pod{}, PodIndexKey, func(rawObj client.Object) []string {\n\t\tpod := rawObj.(*corev1.Pod)\n\t\tif _, ok := pod.Spec.NodeSelector[NvidiaGPUProduct]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\tif pod.Status.Phase == corev1.PodSucceeded {\n\t\t\treturn nil\n\t\t}\n\t\treturn []string{GPU}\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&corev1.Pod{}, builder.WithPredicates(predicate.Funcs{\n\t\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\t\treturn useGPU(event.Object)\n\t\t\t},\n\t\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\t\t_, ok := event.ObjectNew.(*corev1.Pod).Spec.NodeSelector[NvidiaGPUProduct]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tphaseOld := event.ObjectOld.(*corev1.Pod).Status.Phase\n\t\t\t\tphaseNew := event.ObjectNew.(*corev1.Pod).Status.Phase\n\t\t\t\treturn phaseOld != phaseNew\n\t\t\t},\n\t\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\t\treturn useGPU(event.Object)\n\t\t\t},\n\t\t})).\n\t\tWatches(&source.Kind{Type: &corev1.Node{}}, &handler.EnqueueRequestForObject{}, builder.WithPredicates(predicate.Funcs{\n\t\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\t\treturn hasGPU(event.Object)\n\t\t\t},\n\t\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\t\toldVal, oldOk := event.ObjectOld.(*corev1.Node).Status.Allocatable[NvidiaGPU]\n\t\t\t\tnewVal, newOk := event.ObjectNew.(*corev1.Node).Status.Allocatable[NvidiaGPU]\n\n\t\t\t\treturn oldOk && newOk && oldVal != newVal\n\t\t\t},\n\t\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\t\treturn hasGPU(event.Object)\n\t\t\t},\n\t\t})).\n\t\tComplete(r)\n}", "func (r Virtual_Guest) GetGpuType() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getGpuType\", nil, &r.Options, &resp)\n\treturn\n}", "func GetGPUInfoAMD(id unsafe.Pointer, property unsafe.Pointer, dataType uint32, size unsafe.Pointer, data unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall6(gpGetGPUInfoAMD, 5, uintptr(id), uintptr(property), uintptr(dataType), uintptr(size), uintptr(data), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func CalculateGPUFreeMemorySum() uint64 {\n\tvar Sum uint64 = 0\n\tfor _, g := range GPUs {\n\t\tSum += g.FreeMemory\n\t}\n\tif Sum == 0 {\n\t\tlog.ErrPrint(\"CalculateGPUFreeMemorySum\", errors.New(\"The Sum of the GPU memory is 0. \"))\n\t\treturn 0\n\t}\n\treturn Sum\n}", "func (m MinerInfo) StuckGPUs() int {\n\tvar total int\n\tfor _, gpu := range m.GPUS {\n\t\tif gpu.IsStuck() {\n\t\t\ttotal++\n\t\t}\n\t}\n\treturn total\n}", "func DeviceTypesPSurfaceHub() *DeviceTypes {\n\tv := DeviceTypesVSurfaceHub\n\treturn &v\n}", "func DeviceTypesPSurfaceHub() *DeviceTypes {\n\tv := DeviceTypesVSurfaceHub\n\treturn &v\n}", "func (backend *Backend) DevicesRegistered() map[string]device.Interface {\n\treturn backend.devices\n}", "func (al *LinuxOutOfBand) GetPlatformCapabilities(requests []RequestDescription, host []string) map[string][]RequestDescription {\n\tvalidRequests := make(map[string][]RequestDescription, 0)\n\tvar wg sync.WaitGroup\n\n\ta := time.Now()\n\tfor _, addr := range host {\n\t\tvalidRequests[addr] = make([]RequestDescription, 0)\n\t\twg.Add(len(requests))\n\n\t\tfor _, req := range requests {\n\t\t\tgo func(req RequestDescription, addr string) {\n\t\t\t\tal.mutex.Lock()\n\t\t\t\tdefer al.mutex.Unlock()\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tvar a []byte\n\t\t\t\tif al.Protocol == \"node_manager\" {\n\t\t\t\t\ta = ExecIpmiToolRemote(req.Request.Data, al, addr, true)\n\t\t\t\t} else {\n\t\t\t\t\ta = ExecIpmiToolRemote(req.Request.Data, al, addr, false)\n\t\t\t\t}\n\n\t\t\t\tj := 0\n\n\t\t\t\tfor i := range a {\n\t\t\t\t\tif a[i] == 0 {\n\t\t\t\t\t\tj++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif j != len(a) {\n\t\t\t\t\tvalidRequests[addr] = append(validRequests[addr], req)\n\t\t\t\t}\n\n\t\t\t}(req, addr)\n\t\t}\n\n\t\tif al.Protocol == \"dcmi\" {\n\t\t\twg.Add(1)\n\t\t\t// check thermal capability\n\t\t\tgo func(req []byte, addr string) {\n\t\t\t\tal.mutex.Lock()\n\t\t\t\tdefer al.mutex.Lock()\n\t\t\t\tdefer wg.Done()\n\t\t\t\ta := ExecIpmiToolRemote(CmdDCMIThermalCap, al, addr, false)\n\n\t\t\t\tif len(a) > 5 {\n\t\t\t\t\tdata := a[1:]\n\t\t\t\t\t//sdrId := data[4] + uint16(data[5])<<8\n\t\t\t\t\tCmdSDR[4] = data[3]\n\t\t\t\t\tCmdSDR[5] = data[4]\n\t\t\t\t\tresp := ExecIpmiToolRemote(CmdSDR, al, addr, false)\n\n\t\t\t\t\tif len(resp) > 10 {\n\t\t\t\t\t\tdata = resp[1:]\n\t\t\t\t\t\tDcmiThermal.Request.Data[2] = data[9]\n\t\t\t\t\t\tvalidRequests[addr] = append(validRequests[addr], DcmiThermal)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}(CmdDCMIThermalCap, addr)\n\t\t}\n\n\t\twg.Wait()\n\t\tb := time.Now()\n\t\tc := (b.Second() - a.Second())\n\t\tlog.Debug(\"[INIT] Initialization took: \", c)\n\t}\n\n\treturn validRequests\n\n}", "func (h *Hub) Devices() []*pb.Device {\n\th.bridgesLock.RLock()\n\tdefer h.bridgesLock.RUnlock()\n\n\tvar ret []*pb.Device\n\tfor _, b := range h.bridges {\n\t\tfor _, d := range b.devices {\n\t\t\tret = append(ret, d)\n\t\t}\n\t}\n\treturn ret\n}", "func (d *cudaDevice) GetMigDevices() ([]Device, error) {\n\treturn nil, fmt.Errorf(\"GetMigDevices is unsupported for CUDA devices\")\n}", "func getAllSdsDevices(t *testing.T) []*goscaleio.Device {\n\tsds := getAllSds(t)[0]\n\tassert.NotNil(t, sds)\n\tif sds == nil {\n\t\treturn nil\n\t}\n\n\tvar allDevice []*goscaleio.Device\n\tdevices, err := sds.GetDevice()\n\tassert.Nil(t, err)\n\tassert.NotZero(t, len(devices))\n\tfor _, d := range devices {\n\t\t// create a device to return to the caller\n\t\toutDevice := goscaleio.NewDeviceEx(C, &d)\n\t\tallDevice = append(allDevice, outDevice)\n\t\t// create a device via NewDevice for testing purposes\n\t\ttempDevice := goscaleio.NewDevice(C)\n\t\ttempDevice.Device = &d\n\t\tassert.Equal(t, outDevice.Device.ID, tempDevice.Device.ID)\n\t}\n\treturn allDevice\n\n}", "func (c *myClient) getStorageDevices() (devices []string, err error) {\n\n\tresults, err := c.listObjects(\"storage/device\") //grab the query results\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results) == 0 {\n\t\terr = fmt.Errorf(\"No devices available for assignment into the domain\")\n\t\treturn nil, err\n\t}\n\tlogger.Info(\"The following devices are available:\")\n\tfor _, result := range results { //loop through the results\n\t\tif result.(map[string]interface{})[\"configured\"] != true { //if the device is not already configured\n\t\t\tlogger.Info(result.(map[string]interface{})[\"reference\"]) //grab the device reference\n\t\t\tdevices = append(devices, result.(map[string]interface{})[\"reference\"].(string))\n\t\t}\n\t}\n\treturn devices, nil\n}", "func GetNetDevicesFromPci(pciAddress string) ([]string, error) {\n\tpciDir := filepath.Join(PciSysDir, pciAddress, \"net\")\n\treturn getFileNamesFromPath(pciDir)\n}", "func ListDevices() {\n\tledger.ListOasisDevices(ListingDerivationPath)\n}", "func (ctx *Context) NumDevices() int {\n\treturn int(C.freenect_num_devices(ctx.ptr()))\n}", "func PossibleGPUInstanceProfileValues() []GPUInstanceProfile {\n\treturn []GPUInstanceProfile{\n\t\tGPUInstanceProfileMIG1G,\n\t\tGPUInstanceProfileMIG2G,\n\t\tGPUInstanceProfileMIG3G,\n\t\tGPUInstanceProfileMIG4G,\n\t\tGPUInstanceProfileMIG7G,\n\t}\n}", "func (sys *Sys) GetInUseDeviceList() ([]string, error) {\n\tlog.Debugln(\"GetInUseDeviceList ENTER\")\n\n\tlist := []string{}\n\n\toutputCmd := \"blkid\"\n\toutput, err := sys.run.CommandOutput(outputCmd)\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to get blkid list. Err:\", err)\n\t\tlog.Debugln(\"GetInUseDeviceList LEAVE\")\n\t\treturn list, err\n\t}\n\n\tbuffer := bytes.NewBufferString(output)\n\tfor {\n\t\tstr, err := buffer.ReadString('\\n')\n\n\t\tneedles, errRegex := sys.str.RegexMatch(str, \"(/dev/.*):\")\n\t\tif errRegex != nil {\n\t\t\tlog.Errorln(\"RegexMatch Failed. Err:\", err)\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif len(needles) != 2 {\n\t\t\tfmt.Println(\"Incorrect output size:\", len(needles))\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tdevice := needles[1]\n\t\tlog.Debugln(\"Device Found:\", device)\n\n\t\tlist = append(list, device)\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Debugln(\"GetInUseDeviceList Succeeded. Device Count:\", len(list))\n\tlog.Debugln(\"GetInUseDeviceList LEAVE\")\n\n\treturn list, nil\n}", "func (d *DeviceProp) IsMultiGpuBoard() int32 {\n\treturn (int32)(d.isMultiGpuBoard)\n}", "func (t *SpotifyDevice) ListDevices() {\n\tif t.client == nil {\n\t\treturn\n\t}\n\tdevices, err := t.client.PlayerDevices()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfor _, device := range devices {\n\t\tfmt.Printf(\"%s %s\\n\", device.ID, device.Name)\n\t}\n}", "func ListDevices() {\n\tuserDetails := User{}\n\tnewConfig := NewConfig()\n\tconfigDetails, err := newConfig.ReadConfig(userDetails)\n\tif err != nil {\n\t\tlog.Fatal(\"\", err)\n\t}\n\terr = json.Unmarshal(configDetails, &userDetails)\n\tif err != nil {\n\t\tlog.Fatal(\"\", err)\n\t}\n\n\theaderRequestOpt := make(map[string]string)\n\tresponse, err := util.ProcessAPIRequest(\"GET\", util.DevicesAPIURL, userDetails.Token, headerRequestOpt)\n\tif err != nil {\n\t\tlog.Fatal(\"\", err)\n\t}\n\n\tdeviceList := &DeviceList{}\n\terr = json.Unmarshal(response, &deviceList)\n\tif err != nil {\n\t\tlog.Fatal(\"\", err)\n\t}\n\n\tfor _, device := range deviceList.Devices {\n\t\tlog.Info(\"The devices: %#v\", device)\n\t}\n\n}", "func EnumerateVideoDevicesNV(hDC unsafe.Pointer, phDeviceList unsafe.Pointer) unsafe.Pointer {\n\tret, _, _ := syscall.Syscall(gpEnumerateVideoDevicesNV, 2, uintptr(hDC), uintptr(phDeviceList), 0)\n\treturn (unsafe.Pointer)(ret)\n}", "func (r Virtual_Guest) GetBlockDevices() (resp []datatypes.Virtual_Guest_Block_Device, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBlockDevices\", nil, &r.Options, &resp)\n\treturn\n}", "func subsystems_linux() []*Subsystem {\n\tvar _9p, ac100, accelerators, acpi, acpi4asus, acpica, acrn, actions, afs, alpha, alsa, amdgfx, amlogic, apparmor, arch, arm, armmsm, asahi, aspeed, ath10k, ath11k, ath12k, atm, audit, autofs, axis, b43, batman, bcache, bfs, block, bluetooth, bpf, brcm80211, bridge, btrfs, cachefs, can, ceph, cgroups, chrome, cifs, cirrus, clk, coda, coresight, crypto, csky, cxl, damon, dccp, dell, devicetree, dm, dmaengine, drbd, dri, ecryptfs, edac, efi, erofs, etnaviv, ext4, f2fs, fat, fbdev, fpga, freedreno, fs, fscrypt, fsi, fsverity, fuse, geode, gfs2, gpio, greybus, hams, hardening, hexagon, hfs, hippi, hwmon, hyperv, i2c, i3c, ia64, ide, iio, imx, input, integrity, intelgfx, intelgvt, intelwiredlan, iouring, iommu, ipack, isdn4linux, isofs, jfs, karma, kasan, kernel, kernfs, kexec, keyrings, kgdb, kunit, kvm, kvmriscv, kvmarm, leds, libertas, lima, linux1394, linuxppc, linuxpps, livepatching, llvm, loongarch, lsm, lvs, m68k, malidp, media, mediatek, megaraid, mhi, mips, mjpeg, mm, mmc, modules, mpi3, mptfusion, mptcp, mtd, nbd, net, netfilter, nfc, nfs, nilfs, nitro, nouveau, ntb, ntfs, ntfs3, nvdimm, nvme, ocfs2, omap, optee, openiscsi, openbmc, openipmi, openrisc, openvswitch, openwrt, orangefs, ossdrivers, overlayfs, oxnas, parisc, parport, pci, perf, phy, pm, ppp, pvrusb2, pwm, qat, raid, rcu, rdma, rds, reiserfs, remoteproc, renesassoc, riscv, rockchip, rpi, rttools, rtc, rust, s390, samsungsoc, scsi, sctp, selinux, serial, sgx, sh, snpsarc, sof, sparclinux, speakup, spi, spice, squashfs, staging, stm32, sunxi, target, tegra, tipc, tomoyo, trace, uclinux, udf, um, unisoc, usb, usbstorage, video, virt, watchdog, wcn36xx, wireguard, wireless, wpan, x25, x86, x86drivers, xen, xfs, xtensa, zd1211 Subsystem\n\n\t_9p = Subsystem{\n\t\tName: \"9p\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/9p/|^include/net/9p/|^include/trace/events/9p\\\\.h$|^include/uapi/linux/virtio_9p\\\\.h$|^net/9p/\"},\n\t\t},\n\t}\n\n\tac100 = Subsystem{\n\t\tName: \"ac100\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&staging, &tegra},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/staging/nvec/\"},\n\t\t},\n\t}\n\n\taccelerators = Subsystem{\n\t\tName: \"accelerators\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/misc/uacce/|^include/linux/uacce\\\\.h$|^include/uapi/misc/uacce/\"},\n\t\t},\n\t}\n\n\tacpi = Subsystem{\n\t\tName: \"acpi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/acpi/|^arch/x86/pci/acpi\\\\.c$|^drivers/acpi/|^drivers/pci/[^/]*/[^/]*acpi[^/]*$|^drivers/pci/[^/]*acpi[^/]*$|^drivers/pnp/pnpacpi/|^include/acpi/|^include/linux/acpi\\\\.h$|^include/linux/fwnode\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/[^/]*thermal[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/acpica/|^include/acpi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/apei/\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/arm64$\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/pmic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/viot\\\\.c$|^include/linux/acpi_viot\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/property\\\\.c$|^drivers/base/swnode\\\\.c$|^include/linux/fwnode\\\\.h$|^include/linux/property\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpiolib-acpi\\\\.c$|^drivers/gpio/gpiolib-acpi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/i2c-core-acpi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mailbox/pcc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pnp/|^include/linux/pnp\\\\.h$\"},\n\t\t},\n\t}\n\n\tacpi4asus = Subsystem{\n\t\tName: \"acpi4asus\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&x86drivers},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/asus[^/]*\\\\.c$|^drivers/platform/x86/eeepc[^/]*\\\\.c$\"},\n\t\t},\n\t}\n\n\tacpica = Subsystem{\n\t\tName: \"acpica\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&acpi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/acpi/acpica/|^include/acpi/\"},\n\t\t},\n\t}\n\n\tacrn = Subsystem{\n\t\tName: \"acrn\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/virt/acrn/|^include/uapi/linux/acrn\\\\.h$\"},\n\t\t},\n\t}\n\n\tactions = Subsystem{\n\t\tName: \"actions\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/owl-[^/]*$|^arch/arm/mach-actions/|^arch/arm64/boot/dts/actions/|^drivers/clk/actions/|^drivers/clocksource/timer-owl[^/]*$|^drivers/dma/owl-dma\\\\.c$|^drivers/i2c/busses/i2c-owl\\\\.c$|^drivers/irqchip/irq-owl-sirq\\\\.c$|^drivers/mmc/host/owl-mmc\\\\.c$|^drivers/net/ethernet/actions/|^drivers/pinctrl/actions/|^drivers/soc/actions/|^include/dt-bindings/power/owl-[^/]*$|^include/dt-bindings/reset/actions,[^/]*$|^include/linux/soc/actions/|owl\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/misc/atc260x-onkey\\\\.c$|^drivers/mfd/atc260[^/]*$|^drivers/power/reset/atc260x-poweroff\\\\.c$|^drivers/regulator/atc260x-regulator\\\\.c$|^include/linux/mfd/atc260x/\"},\n\t\t},\n\t}\n\n\tafs = Subsystem{\n\t\tName: \"afs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/afs/|^include/trace/events/afs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/keys/rxrpc-type\\\\.h$|^include/net/af_rxrpc\\\\.h$|^include/trace/events/rxrpc\\\\.h$|^include/uapi/linux/rxrpc\\\\.h$|^net/rxrpc/\"},\n\t\t},\n\t}\n\n\talpha = Subsystem{\n\t\tName: \"alpha\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/alpha/\"},\n\t\t},\n\t}\n\n\talsa = Subsystem{\n\t\tName: \"alsa\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-madera[^/]*$|^drivers/irqchip/irq-madera[^/]*$|^drivers/mfd/cs47l[^/]*$|^drivers/mfd/madera[^/]*$|^drivers/pinctrl/cirrus/|^include/dt-bindings/sound/madera[^/]*$|^include/linux/irqchip/irq-madera[^/]*$|^include/linux/mfd/madera/|^include/sound/madera[^/]*$|^sound/soc/codecs/cs47l[^/]*$|^sound/soc/codecs/madera[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/slimbus/|^include/linux/slimbus\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/qcom/apr\\\\.c$|^include/dt-bindings/sound/qcom,wcd9335\\\\.h$|^sound/soc/codecs/lpass-rx-macro\\\\.[^/]*$|^sound/soc/codecs/lpass-tx-macro\\\\.[^/]*$|^sound/soc/codecs/lpass-va-macro\\\\.c$|^sound/soc/codecs/lpass-wsa-macro\\\\.[^/]*$|^sound/soc/codecs/msm8916-wcd-analog\\\\.c$|^sound/soc/codecs/msm8916-wcd-digital\\\\.c$|^sound/soc/codecs/wcd9335\\\\.[^/]*$|^sound/soc/codecs/wcd934x\\\\.c$|^sound/soc/codecs/wcd-clsh-v2\\\\.[^/]*$|^sound/soc/codecs/wcd-mbhc-v2\\\\.[^/]*$|^sound/soc/codecs/wsa881x\\\\.c$|^sound/soc/codecs/wsa883x\\\\.c$|^sound/soc/qcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/soundwire/|^include/linux/soundwire/\"},\n\t\t\t{IncludeRegexp: \"^include/dt-bindings/sound/cs[^/]*$|^sound/pci/hda/cs[^/]*$|^sound/pci/hda/hda_cs_dsp_ctl\\\\.[^/]*$|^sound/soc/codecs/cs[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/dt-bindings/sound/|^include/sound/soc[^/]*$|^sound/soc/\"},\n\t\t\t{IncludeRegexp: \"^include/sound/compress_driver\\\\.h$|^include/uapi/sound/compress_[^/]*$|^sound/core/compress_offload\\\\.c$|^sound/soc/soc-compress\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/sound/|^include/uapi/sound/|^sound/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/virtio_snd\\\\.h$|^sound/virtio/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/sound/firewire\\\\.h$|^sound/firewire/\"},\n\t\t\t{IncludeRegexp: \"^sound/aoa/\"},\n\t\t\t{IncludeRegexp: \"^sound/drivers/opl4/\"},\n\t\t\t{IncludeRegexp: \"^sound/pci/bt87x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/pci/oxygen/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/apple/|^sound/soc/codecs/cs42l83-i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/atmel$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/atmel/tse850-pcm5142\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/ad1[^/]*$|^sound/soc/codecs/ad7[^/]*$|^sound/soc/codecs/adau[^/]*$|^sound/soc/codecs/adav[^/]*$|^sound/soc/codecs/sigmadsp\\\\.[^/]*$|^sound/soc/codecs/ssm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/idt821034\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/isabelle[^/]*$|^sound/soc/codecs/lm49453[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/max9860\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/pcm3060[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/peb2466\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/sgtl5000[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/sma[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/tas571x[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/tfa9879[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/tfa989x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/twl4030[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/fsl/fsl[^/]*$|^sound/soc/fsl/imx[^/]*$|^sound/soc/fsl/mpc8610_hpcd\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/intel/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/meson/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/samsung/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/sti/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/stm/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/sunxi/sun50i-dmic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/ti/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/ti/n810\\\\.c$|^sound/soc/ti/omap[^/]*$|^sound/soc/ti/rx51\\\\.c$|^sound/soc/ti/sdma-pcm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/uniphier/\"},\n\t\t\t{IncludeRegexp: \"^sound/usb/caiaq/\"},\n\t\t\t{IncludeRegexp: \"^sound/usb/midi\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/usb/misc/ua101\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/usb/mixer_scarlett_gen2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^sound/xen/\"},\n\t\t},\n\t}\n\n\tamdgfx = Subsystem{\n\t\tName: \"amd-gfx\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd[^/]*\\\\.\\\\[ch\\\\]$|^drivers/gpu/drm/amd/amdkfd/|^drivers/gpu/drm/amd/include/cik_structs\\\\.h$|^drivers/gpu/drm/amd/include/kgd_kfd_interface\\\\.h$|^drivers/gpu/drm/amd/include/v9_structs\\\\.h$|^drivers/gpu/drm/amd/include/vi_structs\\\\.h$|^include/uapi/linux/kfd_ioctl\\\\.h$|^include/uapi/linux/kfd_sysfs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/amd/display/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/amd/pm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/amd/|^drivers/gpu/drm/radeon/|^include/uapi/drm/amdgpu_drm\\\\.h$|^include/uapi/drm/radeon_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tamlogic = Subsystem{\n\t\tName: \"amlogic\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/meson[^/]*$|^arch/arm/mach-meson/|^arch/arm64/boot/dts/amlogic/|^drivers/mmc/host/meson[^/]*$|^drivers/pinctrl/meson/|^drivers/rtc/rtc-meson[^/]*$|^drivers/soc/amlogic/|meson\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/meson/|^include/dt-bindings/clock/gxbb[^/]*$|^include/dt-bindings/clock/meson[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/amlogic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/meson/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/meson/ao-cec-g12a\\\\.c$|^drivers/media/cec/platform/meson/ao-cec\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/amlogic/meson-ge2d/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mfd/khadas-mcu\\\\.c$|^include/linux/mfd/khadas-mcu\\\\.h$|^drivers/thermal/khadas_mcu_fan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pci-meson\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/perf/amlogic/|^include/soc/amlogic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/meson/vdec/\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/amlogic_thermal\\\\.c$\"},\n\t\t},\n\t}\n\n\tapparmor = Subsystem{\n\t\tName: \"apparmor\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&lsm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^security/apparmor/\"},\n\t\t},\n\t}\n\n\tarch = Subsystem{\n\t\tName: \"arch\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/tlb\\\\.h$|^include/asm-generic/tlb\\\\.h$|^mm/mmu_gather\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/|^include/uapi/asm-generic/\"},\n\t\t},\n\t}\n\n\tarm = Subsystem{\n\t\tName: \"arm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^[^/]*/[^/]*/[^/]*/vexpress[^/]*$|^[^/]*/[^/]*/vexpress[^/]*$|^arch/arm/boot/dts/vexpress[^/]*$|^arch/arm/mach-versatile/|^arch/arm64/boot/dts/arm/|^drivers/clk/versatile/clk-vexpress-osc\\\\.c$|^drivers/clocksource/timer-versatile\\\\.c$|mps2\"},\n\t\t\t{\"^arch/arm/\", \"^arch/arm/boot/dts/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/compressed/misc-ep93xx\\\\.h$|^arch/arm/mach-ep93xx/|^drivers/iio/adc/ep93xx_adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/alpine[^/]*$|^arch/arm/mach-alpine/|^arch/arm64/boot/dts/amazon/|^drivers/[^/]*/[^/]*alpine[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/arm-realview-[^/]*$|^arch/arm/boot/dts/integrator[^/]*$|^arch/arm/boot/dts/versatile[^/]*$|^arch/arm/mach-versatile/|^drivers/bus/arm-integrator-lm\\\\.c$|^drivers/clk/versatile/|^drivers/i2c/busses/i2c-versatile\\\\.c$|^drivers/irqchip/irq-versatile-fpga\\\\.c$|^drivers/mtd/maps/physmap-versatile\\\\.[^/]*$|^drivers/power/reset/arm-versatile-reboot\\\\.c$|^drivers/soc/versatile/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/armada[^/]*$|^arch/arm/boot/dts/kirkwood[^/]*$|^arch/arm/configs/mvebu_[^/]*_defconfig$|^arch/arm/mach-mvebu/|^arch/arm64/boot/dts/marvell/armada[^/]*$|^arch/arm64/boot/dts/marvell/cn913[^/]*$|^drivers/cpufreq/armada-37xx-cpufreq\\\\.c$|^drivers/cpufreq/armada-8k-cpufreq\\\\.c$|^drivers/cpufreq/mvebu-cpufreq\\\\.c$|^drivers/irqchip/irq-armada-370-xp\\\\.c$|^drivers/irqchip/irq-mvebu-[^/]*$|^drivers/pinctrl/mvebu/|^drivers/rtc/rtc-armada38x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/aspeed-[^/]*$|^arch/arm/mach-aspeed/|aspeed\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/at91-linea\\\\.dtsi$|^arch/arm/boot/dts/at91-natte\\\\.dtsi$|^arch/arm/boot/dts/at91-nattis-2-natte-2\\\\.dts$|^arch/arm/boot/dts/at91-tse850-3\\\\.dts$\"},\n\t\t\t{\"^arch/arm/boot/dts/at91[^/]*\\\\.dts$|^arch/arm/boot/dts/at91[^/]*\\\\.dtsi$|^arch/arm/boot/dts/sama[^/]*\\\\.dts$|^arch/arm/boot/dts/sama[^/]*\\\\.dtsi$|^arch/arm/include/debug/at91\\\\.S$|^arch/arm/mach-at91/|^drivers/memory/atmel[^/]*$|^drivers/watchdog/sama5d4_wdt\\\\.c$|^include/soc/at91/|at91|atmel\", \"^drivers/input/touchscreen/atmel_mxt_ts\\\\.c$|^drivers/net/wireless/atmel/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/bcm470[^/]*$|^arch/arm/boot/dts/bcm5301[^/]*$|^arch/arm/boot/dts/bcm953012[^/]*$|^arch/arm/mach-bcm/bcm_5301x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/bcm47189[^/]*$|^arch/arm/boot/dts/bcm53573[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/bcm7[^/]*\\\\.dts[^/]*$|^arch/arm/include/asm/hardware/cache-b15-rac\\\\.h$|^arch/arm/mach-bcm/[^/]*brcmstb[^/]*$|^arch/arm/mm/cache-b15-rac\\\\.c$|^drivers/bus/brcmstb_gisb\\\\.c$|^drivers/pci/controller/pcie-brcmstb\\\\.c$|brcmstb|bcm7038|bcm7120\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/berlin[^/]*$|^arch/arm/mach-berlin/|^arch/arm64/boot/dts/synaptics/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/cx92755[^/]*$|digicolor\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/da850[^/]*$|^arch/arm/mach-davinci/|^drivers/i2c/busses/i2c-davinci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/dove[^/]*$|^arch/arm/boot/dts/orion5x[^/]*$|^arch/arm/mach-dove/|^arch/arm/mach-mv78xx0/|^arch/arm/mach-orion5x/|^arch/arm/plat-orion/|^drivers/soc/dove/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/ecx-[^/]*\\\\.dts[^/]*$|^arch/arm/boot/dts/highbank\\\\.dts$|^arch/arm/mach-highbank/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/exynos[^/]*$|^arch/arm/boot/dts/s3c[^/]*$|^arch/arm/boot/dts/s5p[^/]*$|^arch/arm/mach-exynos[^/]*/|^arch/arm/mach-s3c/|^arch/arm/mach-s5p[^/]*/|^arch/arm64/boot/dts/exynos/|^drivers/[^/]*/[^/]*/[^/]*s3c24[^/]*$|^drivers/[^/]*/[^/]*s3c24[^/]*$|^drivers/[^/]*/[^/]*s3c64xx[^/]*$|^drivers/[^/]*/[^/]*s5pv210[^/]*$|^drivers/clocksource/samsung_pwm_timer\\\\.c$|^drivers/memory/samsung/|^drivers/pwm/pwm-samsung\\\\.c$|^drivers/soc/samsung/|^drivers/tty/serial/samsung[^/]*$|^include/clocksource/samsung_pwm\\\\.h$|^include/linux/platform_data/[^/]*s3c[^/]*$|^include/linux/serial_s3c\\\\.h$|^include/linux/soc/samsung/|exynos|s3c64xx|s5pv210\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/gemini[^/]*$|^arch/arm/mach-gemini/|^drivers/crypto/gemini/|^drivers/net/ethernet/cortina/|^drivers/pinctrl/pinctrl-gemini\\\\.c$|^drivers/rtc/rtc-ftrtc010\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/hi3[^/]*$|^arch/arm/boot/dts/hip[^/]*$|^arch/arm/boot/dts/hisi[^/]*$|^arch/arm/mach-hisi/|^arch/arm64/boot/dts/hisilicon/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/intel-ixp[^/]*$|^arch/arm/mach-ixp4xx/|^drivers/bus/intel-ixp4xx-eb\\\\.c$|^drivers/clocksource/timer-ixp4xx\\\\.c$|^drivers/crypto/ixp4xx_crypto\\\\.c$|^drivers/gpio/gpio-ixp4xx\\\\.c$|^drivers/irqchip/irq-ixp4xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/keystone-[^/]*$|^arch/arm/mach-keystone/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/lpc32[^/]*$|^arch/arm/mach-lpc32xx/|^drivers/i2c/busses/i2c-pnx\\\\.c$|^drivers/net/ethernet/nxp/lpc_eth\\\\.c$|^drivers/usb/host/ohci-nxp\\\\.c$|^drivers/watchdog/pnx4008_wdt\\\\.c$|lpc32xx\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/lpc43[^/]*$|^drivers/i2c/busses/i2c-lpc2k\\\\.c$|^drivers/memory/pl172\\\\.c$|^drivers/mtd/spi-nor/controllers/nxp-spifi\\\\.c$|^drivers/rtc/rtc-lpc24xx\\\\.c$|lpc18xx\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/ls1021a[^/]*$|^arch/arm64/boot/dts/freescale/fsl-[^/]*$|^arch/arm64/boot/dts/freescale/qoriq-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/meson[^/]*$|^arch/arm/mach-meson/|^arch/arm64/boot/dts/amlogic/|^drivers/mmc/host/meson[^/]*$|^drivers/pinctrl/meson/|^drivers/rtc/rtc-meson[^/]*$|^drivers/soc/amlogic/|meson\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/milbeaut[^/]*$|^arch/arm/mach-milbeaut/|milbeaut\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/mmp[^/]*$|^arch/arm/mach-mmp/|^include/linux/soc/mmp/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/mstar-[^/]*$|^arch/arm/mach-mstar/|^drivers/clk/mstar/|^drivers/clocksource/timer-msc313e\\\\.c$|^drivers/gpio/gpio-msc313\\\\.c$|^drivers/rtc/rtc-msc313\\\\.c$|^drivers/watchdog/msc313e_wdt\\\\.c$|^include/dt-bindings/clock/mstar-[^/]*$|^include/dt-bindings/gpio/msc313-gpio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/mt2[^/]*$|^arch/arm/boot/dts/mt6[^/]*$|^arch/arm/boot/dts/mt7[^/]*$|^arch/arm/boot/dts/mt8[^/]*$|^arch/arm/mach-mediatek/|^arch/arm64/boot/dts/mediatek/|^drivers/soc/mediatek/|mtk|mt[2678]\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/omap3-igep[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/owl-[^/]*$|^arch/arm/mach-actions/|^arch/arm64/boot/dts/actions/|^drivers/clk/actions/|^drivers/clocksource/timer-owl[^/]*$|^drivers/dma/owl-dma\\\\.c$|^drivers/i2c/busses/i2c-owl\\\\.c$|^drivers/irqchip/irq-owl-sirq\\\\.c$|^drivers/mmc/host/owl-mmc\\\\.c$|^drivers/net/ethernet/actions/|^drivers/pinctrl/actions/|^drivers/soc/actions/|^include/dt-bindings/power/owl-[^/]*$|^include/dt-bindings/reset/actions,[^/]*$|^include/linux/soc/actions/|owl\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/ox8[^/]*\\\\.dts[^/]*$|^arch/arm/mach-oxnas/|^drivers/power/reset/oxnas-restart\\\\.c$|oxnas\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/pxa[^/]*$|^arch/arm/mach-pxa/|^drivers/dma/pxa[^/]*$|^drivers/pcmcia/pxa2xx[^/]*$|^drivers/pinctrl/pxa/|^drivers/spi/spi-pxa2xx[^/]*$|^drivers/usb/gadget/udc/pxa2[^/]*$|^include/sound/pxa2xx-lib\\\\.h$|^sound/arm/pxa[^/]*$|^sound/soc/pxa/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/rda8810pl-[^/]*$|^drivers/clocksource/timer-rda\\\\.c$|^drivers/gpio/gpio-rda\\\\.c$|^drivers/irqchip/irq-rda-intc\\\\.c$|^drivers/tty/serial/rda-uart\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/rk3[^/]*$|^arch/arm/boot/dts/rv11[^/]*$|^arch/arm/mach-rockchip/|^drivers/[^/]*/[^/]*/[^/]*rockchip[^/]*$|^drivers/[^/]*/[^/]*rockchip[^/]*$|^drivers/clk/rockchip/|^drivers/i2c/busses/i2c-rk3x\\\\.c$|^sound/soc/rockchip/|rockchip\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/rtd[^/]*$|^arch/arm/mach-realtek/|^arch/arm64/boot/dts/realtek/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/spear[^/]*$|^arch/arm/mach-spear/|^drivers/clk/spear/|^drivers/pinctrl/spear/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/ste-[^/]*$|^arch/arm/mach-nomadik/|^arch/arm/mach-ux500/|^drivers/clk/clk-nomadik\\\\.c$|^drivers/clocksource/clksrc-dbx500-prcmu\\\\.c$|^drivers/dma/ste_dma40[^/]*$|^drivers/hwspinlock/u8500_hsem\\\\.c$|^drivers/i2c/busses/i2c-nomadik\\\\.c$|^drivers/iio/adc/ab8500-gpadc\\\\.c$|^drivers/mfd/ab8500[^/]*$|^drivers/mfd/abx500[^/]*$|^drivers/mfd/db8500[^/]*$|^drivers/pinctrl/nomadik/|^drivers/rtc/rtc-ab8500\\\\.c$|^drivers/rtc/rtc-pl031\\\\.c$|^drivers/soc/ux500/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/sti[^/]*$|^arch/arm/mach-sti/|^drivers/ata/ahci_st\\\\.c$|^drivers/char/hw_random/st-rng\\\\.c$|^drivers/clocksource/arm_global_timer\\\\.c$|^drivers/clocksource/clksrc_st_lpc\\\\.c$|^drivers/cpufreq/sti-cpufreq\\\\.c$|^drivers/dma/st_fdma[^/]*$|^drivers/i2c/busses/i2c-st\\\\.c$|^drivers/media/platform/st/sti/c8sectpfe/|^drivers/media/rc/st_rc\\\\.c$|^drivers/mmc/host/sdhci-st\\\\.c$|^drivers/phy/st/phy-miphy28lp\\\\.c$|^drivers/phy/st/phy-stih407-usb\\\\.c$|^drivers/pinctrl/pinctrl-st\\\\.c$|^drivers/remoteproc/st_remoteproc\\\\.c$|^drivers/remoteproc/st_slim_rproc\\\\.c$|^drivers/reset/sti/|^drivers/rtc/rtc-st-lpc\\\\.c$|^drivers/tty/serial/st-asc\\\\.c$|^drivers/usb/dwc3/dwc3-st\\\\.c$|^drivers/usb/host/ehci-st\\\\.c$|^drivers/usb/host/ohci-st\\\\.c$|^drivers/watchdog/st_lpc_wdt\\\\.c$|^include/linux/remoteproc/st_slim_rproc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/stm32[^/]*$|^arch/arm/mach-stm32/|^drivers/clocksource/armv7m_systick\\\\.c$|stm32|stm\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/sunplus-sp7021[^/]*\\\\.dts[^/]*$|^arch/arm/configs/sp7021_[^/]*defconfig$|^arch/arm/mach-sunplus/|^drivers/irqchip/irq-sp7021-intc\\\\.c$|^drivers/reset/reset-sunplus\\\\.c$|^include/dt-bindings/clock/sunplus,sp7021-clkc\\\\.h$|^include/dt-bindings/reset/sunplus,sp7021-reset\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/uniphier[^/]*$|^arch/arm/include/asm/hardware/cache-uniphier\\\\.h$|^arch/arm/mach-uniphier/|^arch/arm/mm/cache-uniphier\\\\.c$|^arch/arm64/boot/dts/socionext/uniphier[^/]*$|^drivers/bus/uniphier-system-bus\\\\.c$|^drivers/clk/uniphier/|^drivers/dma/uniphier-mdmac\\\\.c$|^drivers/gpio/gpio-uniphier\\\\.c$|^drivers/i2c/busses/i2c-uniphier[^/]*$|^drivers/irqchip/irq-uniphier-aidet\\\\.c$|^drivers/mmc/host/uniphier-sd\\\\.c$|^drivers/pinctrl/uniphier/|^drivers/reset/reset-uniphier\\\\.c$|^drivers/tty/serial/8250/8250_uniphier\\\\.c$|uniphier\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/vf[^/]*$|^arch/arm/mach-imx/[^/]*vf610[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/include/asm/arch_timer\\\\.h$|^arch/arm64/include/asm/arch_timer\\\\.h$|^drivers/clocksource/arm_arch_timer\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/include/asm/hardware/dec21285\\\\.h$|^arch/arm/mach-footbridge/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/include/asm/hardware/ioc\\\\.h$|^arch/arm/include/asm/hardware/iomd\\\\.h$|^arch/arm/include/asm/hardware/memc\\\\.h$|^arch/arm/mach-rpc/|^drivers/net/ethernet/8390/etherh\\\\.c$|^drivers/net/ethernet/i825xx/ether1[^/]*$|^drivers/net/ethernet/seeq/ether3[^/]*$|^drivers/scsi/arm/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-[^/]*/|^arch/arm/plat-[^/]*/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-ep93xx/ts72xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-orion5x/ts78xx-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-sunxi/|^arch/arm64/boot/dts/allwinner/|^drivers/clk/sunxi-ng/|^drivers/pinctrl/sunxi/|^drivers/soc/sunxi/|allwinner|sun[x456789]i|sun[25]0i\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-vt8500/|^drivers/clocksource/timer-vt8500\\\\.c$|^drivers/i2c/busses/i2c-wmt\\\\.c$|^drivers/mmc/host/wmt-sdmmc\\\\.c$|^drivers/pwm/pwm-vt8500\\\\.c$|^drivers/rtc/rtc-vt8500\\\\.c$|^drivers/tty/serial/vt8500_serial\\\\.c$|^drivers/usb/host/ehci-platform\\\\.c$|^drivers/usb/host/uhci-platform\\\\.c$|^drivers/video/fbdev/vt8500lcdfb\\\\.[^/]*$|^drivers/video/fbdev/wm8505fb[^/]*$|^drivers/video/fbdev/wmt_ge_rops\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-zynq/|^drivers/clocksource/timer-cadence-ttc\\\\.c$|^drivers/cpuidle/cpuidle-zynq\\\\.c$|^drivers/edac/synopsys_edac\\\\.c$|^drivers/i2c/busses/i2c-cadence\\\\.c$|^drivers/i2c/busses/i2c-xiic\\\\.c$|^drivers/mmc/host/sdhci-of-arasan\\\\.c$|zynq|xilinx\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mm/[^/]*-fa[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/vfp/\"},\n\t\t\t{\"^arch/arm64/\", \"^arch/arm64/boot/dts/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/apple/|^drivers/bluetooth/hci_bcm4377\\\\.c$|^drivers/clk/clk-apple-nco\\\\.c$|^drivers/cpufreq/apple-soc-cpufreq\\\\.c$|^drivers/dma/apple-admac\\\\.c$|^drivers/i2c/busses/i2c-pasemi-core\\\\.c$|^drivers/i2c/busses/i2c-pasemi-platform\\\\.c$|^drivers/iommu/apple-dart\\\\.c$|^drivers/iommu/io-pgtable-dart\\\\.c$|^drivers/irqchip/irq-apple-aic\\\\.c$|^drivers/mailbox/apple-mailbox\\\\.c$|^drivers/nvme/host/apple\\\\.c$|^drivers/nvmem/apple-efuses\\\\.c$|^drivers/pinctrl/pinctrl-apple-gpio\\\\.c$|^drivers/soc/apple/|^drivers/watchdog/apple_wdt\\\\.c$|^include/dt-bindings/interrupt-controller/apple-aic\\\\.h$|^include/dt-bindings/pinctrl/apple\\\\.h$|^include/linux/apple-mailbox\\\\.h$|^include/linux/soc/apple/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/bitmain/|^drivers/clk/clk-bm1880\\\\.c$|^drivers/pinctrl/pinctrl-bm1880\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/broadcom/bcmbca/|bcmbca|bcm[9]?47622|bcm[9]?4912|bcm[9]?63138|bcm[9]?63146|bcm[9]?63148|bcm[9]?63158|bcm[9]?63178|bcm[9]?6756|bcm[9]?6813|bcm[9]?6846|bcm[9]?6855|bcm[9]?6856|bcm[9]?6858|bcm[9]?6878\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/broadcom/northstar2/|^arch/arm64/boot/dts/broadcom/stingray/|^drivers/clk/bcm/clk-ns[^/]*$|^drivers/clk/bcm/clk-sr[^/]*$|^drivers/pinctrl/bcm/pinctrl-ns[^/]*$|^include/dt-bindings/clock/bcm-sr[^/]*$|iproc|cygnus|bcm[-_]nsp|bcm9113*|bcm9583*|bcm9585*|bcm9586*|bcm988312|bcm113*|bcm583*|bcm585*|bcm586*|bcm88312|hr2|stingray\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/cavium/thunder2-99xx[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/freescale/s32g[^/]*\\\\.dts[^/]*$\"},\n\t\t\t{\"^arch/arm64/boot/dts/freescale/|imx|mxs\", \"^drivers/media/i2c/|^arch/arm64/boot/dts/freescale/fsl-[^/]*$|^arch/arm64/boot/dts/freescale/qoriq-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/lg/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/marvell/armada-8040-mcbin\\\\.dts$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/microchip/|^drivers/net/ethernet/microchip/vcap/|^drivers/pinctrl/pinctrl-microchip-sgpio\\\\.c$|sparx5\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/tesla/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/ti/k3-[^/]*$|^include/dt-bindings/pinctrl/k3\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/toshiba/|^drivers/clk/visconti/|^drivers/net/ethernet/stmicro/stmmac/dwmac-visconti\\\\.c$|^drivers/gpio/gpio-visconti\\\\.c$|^drivers/pci/controller/dwc/pcie-visconti\\\\.c$|^drivers/pinctrl/visconti/|^drivers/watchdog/visconti_wdt\\\\.c$|visconti\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/include/asm/kvm[^/]*$|^arch/arm64/include/uapi/asm/kvm[^/]*$|^arch/arm64/kvm/|^include/kvm/arm_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm[^/]*/include/asm/hw_breakpoint\\\\.h$|^arch/arm[^/]*/include/asm/perf_event\\\\.h$|^arch/arm[^/]*/kernel/hw_breakpoint\\\\.c$|^arch/arm[^/]*/kernel/perf_[^/]*$|^drivers/perf/|^include/linux/perf/arm_pmu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/arm64$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/clk-sc\\\\[mp\\\\]i\\\\.c$|^drivers/cpufreq/sc\\\\[mp\\\\]i-cpufreq\\\\.c$|^drivers/firmware/arm_scmi/|^drivers/firmware/arm_scpi\\\\.c$|^drivers/powercap/arm_scmi_powercap\\\\.c$|^drivers/regulator/scmi-regulator\\\\.c$|^drivers/reset/reset-scmi\\\\.c$|^include/linux/sc\\\\[mp\\\\]i_protocol\\\\.h$|^include/trace/events/scmi\\\\.h$|^include/uapi/linux/virtio_scmi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/clkdev\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/keystone/sci-clk\\\\.c$|^drivers/firmware/ti_sci[^/]*$|^drivers/irqchip/irq-ti-sci-inta\\\\.c$|^drivers/irqchip/irq-ti-sci-intr\\\\.c$|^drivers/reset/reset-ti-sci\\\\.c$|^drivers/soc/ti/ti_sci_inta_msi\\\\.c$|^drivers/soc/ti/ti_sci_pm_domains\\\\.c$|^include/dt-bindings/soc/ti,sci_pm_domain\\\\.h$|^include/linux/soc/ti/ti_sci_inta_msi\\\\.h$|^include/linux/soc/ti/ti_sci_protocol\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/ux500/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clocksource/timer-keystone\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/microchip-tcb-capture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-big_little\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-psci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-psci\\\\.h$|^drivers/cpuidle/cpuidle-psci-domain\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/at_hdmac\\\\.c$|^drivers/dma/at_xdmac\\\\.c$|^include/dt-bindings/dma/at91\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/qcom/hidma[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/arm_ffa/|^include/linux/arm_ffa\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/arm_sdei\\\\.c$|^include/linux/arm_sdei\\\\.h$|^include/uapi/linux/arm_sdei\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/psci/|^include/linux/psci\\\\.h$|^include/uapi/linux/psci\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/smccc/|^include/linux/arm-smccc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-sama5d2-piobu\\\\.c$|^drivers/pinctrl/pinctrl-at91[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwtracing/coresight/|^include/dt-bindings/arm/coresight-cti-dt\\\\.h$|^include/linux/coresight[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/arm/|^drivers/iommu/io-pgtable-arm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/irqchip/irq-mchp-eic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/irqchip/irq-vic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-g2d/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-jpeg/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-mfc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/brcmstb_dpfe\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/pl353-smc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/atmel-ssc\\\\.c$|^include/linux/atmel-ssc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/cavium/thunder/\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvmem/microchip-otpc\\\\.c$|^include/dt-bindings/nvmem/microchip,sama7g5-otpc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*mvebu[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/cadence/pci-j721e\\\\.c$|^drivers/pci/controller/dwc/pci-dra7xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*imx6[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*layerscape[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pci-exynos\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-armada8k\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/mobiveil/pcie-layerscape-gen4\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-aardvark\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-host-common\\\\.c$|^drivers/pci/controller/pci-host-generic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-thunder-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-versatile\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-xgene-msi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-xgene\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-brcmstb\\\\.c$|^drivers/staging/vc04_services$|bcm2711|bcm283*|raspberrypi\"},\n\t\t\t{IncludeRegexp: \"^drivers/perf/fsl_imx8_ddr_perf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/marvell/phy-mmp3-usb\\\\.c$|^drivers/phy/marvell/phy-pxa-usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-single\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/samsung/|^include/dt-bindings/pinctrl/samsung\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/sunplus/|^include/dt-bindings/pinctrl/sppctl[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pwm/pwm-atmel\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/regulator/mcp16502\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-mt2712\\\\.c$|^drivers/rtc/rtc-mt6397\\\\.c$|^drivers/rtc/rtc-mt7622\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/fsl/|^include/linux/fsl/|^include/soc/fsl/\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/ti/\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-pl022\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/atmel_usba_udc\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/xhci-mtk[^/]*$|^drivers/usb/mtu3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/cyber2000fb\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/imxfb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"clps711x\"},\n\t\t},\n\t}\n\n\tarmmsm = Subsystem{\n\t\tName: \"arm-msm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/qcom-[^/]*\\\\.dts$|^arch/arm/boot/dts/qcom-[^/]*\\\\.dtsi$|^arch/arm/configs/qcom_defconfig$|^arch/arm/mach-qcom/|^arch/arm64/boot/dts/qcom/|^drivers/[^/]*/[^/]*/qcom[^/]*$|^drivers/[^/]*/[^/]*/qcom/|^drivers/[^/]*/pm8...-[^/]*$|^drivers/[^/]*/qcom[^/]*$|^drivers/[^/]*/qcom/|^drivers/bluetooth/btqcomsmd\\\\.c$|^drivers/clocksource/timer-qcom\\\\.c$|^drivers/cpuidle/cpuidle-qcom-spm\\\\.c$|^drivers/extcon/extcon-qcom[^/]*$|^drivers/i2c/busses/i2c-qcom-geni\\\\.c$|^drivers/i2c/busses/i2c-qup\\\\.c$|^drivers/iommu/msm[^/]*$|^drivers/mfd/ssbi\\\\.c$|^drivers/mmc/host/mmci_qcom[^/]*$|^drivers/mmc/host/sdhci-msm\\\\.c$|^drivers/pci/controller/dwc/pcie-qcom\\\\.c$|^drivers/phy/qualcomm/|^drivers/power/[^/]*/msm[^/]*$|^drivers/reset/reset-qcom-[^/]*$|^drivers/ufs/host/ufs-qcom[^/]*$|^drivers/spi/spi-geni-qcom\\\\.c$|^drivers/spi/spi-qcom-qspi\\\\.c$|^drivers/spi/spi-qup\\\\.c$|^drivers/tty/serial/msm_serial\\\\.c$|^drivers/usb/dwc3/dwc3-qcom\\\\.c$|^include/dt-bindings/[^/]*/qcom[^/]*$|^include/linux/[^/]*/qcom[^/]*$|^include/linux/soc/qcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/bus/mhi/|^include/linux/mhi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/qcom/|^include/dt-bindings/clock/qcom,[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/qce/\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/qcom/hidma[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/qcom_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/msm/|^include/uapi/drm/msm_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-qcom-cci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/arm/arm-smmu/qcom_iommu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mailbox/qcom-ipcc\\\\.c$|^include/dt-bindings/mailbox/qcom-ipcc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/qcom/venus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/fastrpc\\\\.c$|^include/uapi/misc/fastrpc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/qcom_nandc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/qcom_bam_dmux\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-qcom-ep\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-qcom\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/qualcomm/phy-qcom-ipq4019-usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/qcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/regulator/vqmmc-ipq4019-regulator\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/qcom/cpr\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/qcom/icc-bwmon\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/qcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-qcom[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/qcom_eud\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/trace/events/qrtr\\\\.h$|^include/uapi/linux/qrtr\\\\.h$|^net/qrtr/\"},\n\t\t},\n\t}\n\n\tasahi = Subsystem{\n\t\tName: \"asahi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/apple/|^drivers/bluetooth/hci_bcm4377\\\\.c$|^drivers/clk/clk-apple-nco\\\\.c$|^drivers/cpufreq/apple-soc-cpufreq\\\\.c$|^drivers/dma/apple-admac\\\\.c$|^drivers/i2c/busses/i2c-pasemi-core\\\\.c$|^drivers/i2c/busses/i2c-pasemi-platform\\\\.c$|^drivers/iommu/apple-dart\\\\.c$|^drivers/iommu/io-pgtable-dart\\\\.c$|^drivers/irqchip/irq-apple-aic\\\\.c$|^drivers/mailbox/apple-mailbox\\\\.c$|^drivers/nvme/host/apple\\\\.c$|^drivers/nvmem/apple-efuses\\\\.c$|^drivers/pinctrl/pinctrl-apple-gpio\\\\.c$|^drivers/soc/apple/|^drivers/watchdog/apple_wdt\\\\.c$|^include/dt-bindings/interrupt-controller/apple-aic\\\\.h$|^include/dt-bindings/pinctrl/apple\\\\.h$|^include/linux/apple-mailbox\\\\.h$|^include/linux/soc/apple/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/apple/|^sound/soc/codecs/cs42l83-i2c\\\\.c$\"},\n\t\t},\n\t}\n\n\taspeed = Subsystem{\n\t\tName: \"aspeed\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/aspeed-[^/]*$|^arch/arm/mach-aspeed/|aspeed\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/irqchip/irq-aspeed-scu-ic\\\\.c$|^include/dt-bindings/interrupt-controller/aspeed-scu-ic\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-of-aspeed[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/peci/controller/peci-aspeed\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-aspeed-smc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/aspeed_udc\\\\.c$\"},\n\t\t},\n\t}\n\n\tath10k = Subsystem{\n\t\tName: \"ath10k\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath10k/\"},\n\t\t},\n\t}\n\n\tath11k = Subsystem{\n\t\tName: \"ath11k\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath11k/\"},\n\t\t},\n\t}\n\n\tath12k = Subsystem{\n\t\tName: \"ath12k\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath12k/\"},\n\t\t},\n\t}\n\n\tatm = Subsystem{\n\t\tName: \"atm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/atm/|^include/linux/atm[^/]*$|^include/uapi/linux/atm[^/]*$\"},\n\t\t},\n\t}\n\n\taudit = Subsystem{\n\t\tName: \"audit\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/asm-generic/audit_[^/]*\\\\.h$|^include/linux/audit\\\\.h$|^include/linux/audit_arch\\\\.h$|^include/uapi/linux/audit\\\\.h$|^kernel/audit[^/]*$|^lib/[^/]*audit\\\\.c$\"},\n\t\t},\n\t}\n\n\tautofs = Subsystem{\n\t\tName: \"autofs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/autofs/\"},\n\t\t},\n\t}\n\n\taxis = Subsystem{\n\t\tName: \"axis\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/artpec6[^/]*$|^arch/arm/mach-artpec$|^drivers/clk/axis$|^drivers/crypto/axis$|^drivers/mmc/host/usdhi6rol0\\\\.c$|^drivers/pinctrl/pinctrl-artpec[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*artpec[^/]*$\"},\n\t\t},\n\t}\n\n\tb43 = Subsystem{\n\t\tName: \"b43\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/b43/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/b43legacy/\"},\n\t\t},\n\t}\n\n\tbatman = Subsystem{\n\t\tName: \"batman\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/batadv_packet\\\\.h$|^include/uapi/linux/batman_adv\\\\.h$|^net/batman-adv/\"},\n\t\t},\n\t}\n\n\tbcache = Subsystem{\n\t\tName: \"bcache\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/md/bcache/\"},\n\t\t},\n\t}\n\n\tbfs = Subsystem{\n\t\tName: \"bfs\",\n\t\tSyscalls: []string{\"syz_mount_image$bfs\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/bfs/|^include/uapi/linux/bfs_fs\\\\.h$\"},\n\t\t},\n\t}\n\n\tblock = Subsystem{\n\t\tName: \"block\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^block/bfq-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^block/bfq-cgroup\\\\.c$|^block/blk-cgroup\\\\.c$|^block/blk-iocost\\\\.c$|^block/blk-iolatency\\\\.c$|^block/blk-throttle\\\\.c$|^include/linux/blk-cgroup\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^block/opal_proto\\\\.h$|^block/sed[^/]*$|^include/linux/sed[^/]*$|^include/uapi/linux/sed[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^block/|^drivers/block/|^include/linux/bio\\\\.h$|^include/linux/blk[^/]*$|^kernel/trace/blktrace\\\\.c$|^lib/sbitmap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/floppy\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/nbd\\\\.c$|^include/trace/events/nbd\\\\.h$|^include/uapi/linux/nbd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/rnbd/\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/ublk_drv\\\\.c$|^include/uapi/linux/ublk_cmd\\\\.h$\"},\n\t\t},\n\t}\n\n\tbluetooth = Subsystem{\n\t\tName: \"bluetooth\",\n\t\tSyscalls: []string{\"syz_emit_vhci\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/bluetooth/\"},\n\t\t\t{IncludeRegexp: \"^drivers/bluetooth/btmtkuart\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/6lowpan\\\\.h$|^net/6lowpan/\"},\n\t\t\t{IncludeRegexp: \"^include/net/bluetooth/|^net/bluetooth/\"},\n\t\t},\n\t}\n\n\tbpf = Subsystem{\n\t\tName: \"bpf\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/net/|^include/linux/bpf[^/]*$|^include/linux/btf[^/]*$|^include/linux/filter\\\\.h$|^include/trace/events/xdp\\\\.h$|^include/uapi/linux/bpf[^/]*$|^include/uapi/linux/btf[^/]*$|^include/uapi/linux/filter\\\\.h$|^kernel/bpf/|^kernel/trace/bpf_trace\\\\.c$|^lib/test_bpf\\\\.c$|^net/bpf/|^net/core/filter\\\\.c$|^net/sched/act_bpf\\\\.c$|^net/sched/cls_bpf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/net/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/net/\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/net/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/net/\"},\n\t\t\t{\"^arch/riscv/net/\", \"^arch/riscv/net/bpf_jit_comp32\\\\.c$\"},\n\t\t\t{\"^arch/riscv/net/\", \"^arch/riscv/net/bpf_jit_comp64\\\\.c$\"},\n\t\t\t{\"^arch/s390/net/\", \"^arch/s390/net/pnet\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/sparc/net/\"},\n\t\t\t{\"^arch/x86/net/\", \"^arch/x86/net/bpf_jit_comp32\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/net/bpf_jit_comp32\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/netronome/nfp/bpf/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/bpf_lsm\\\\.h$|^kernel/bpf/bpf_lsm\\\\.c$|^security/bpf/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/skmsg\\\\.h$|^net/core/skmsg\\\\.c$|^net/core/sock_map\\\\.c$|^net/ipv4/tcp_bpf\\\\.c$|^net/ipv4/udp_bpf\\\\.c$|^net/unix/unix_bpf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/xdp\\\\.h$|^include/net/xdp_priv\\\\.h$|^include/trace/events/xdp\\\\.h$|^kernel/bpf/cpumap\\\\.c$|^kernel/bpf/devmap\\\\.c$|^net/core/xdp\\\\.c$|^drivers/net/ethernet/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*xdp[^/]*$|^drivers/net/ethernet/[^/]*/[^/]*/[^/]*xdp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/net/xdp_sock[^/]*$|^include/net/xsk_buff_pool\\\\.h$|^include/uapi/linux/if_xdp\\\\.h$|^include/uapi/linux/xdp_diag\\\\.h$|^include/net/netns/xdp\\\\.h$|^net/xdp/\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/[^/]*iter\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/bpf_struct[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/btf\\\\.c$|^include/linux/btf[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/cgroup\\\\.c$|^kernel/bpf/[^/]*storage\\\\.c$|^kernel/bpf/bpf_lru[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/disasm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/ringbuf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/verifier\\\\.c$|^kernel/bpf/tnum\\\\.c$|^kernel/bpf/core\\\\.c$|^kernel/bpf/syscall\\\\.c$|^kernel/bpf/dispatcher\\\\.c$|^kernel/bpf/trampoline\\\\.c$|^include/linux/bpf[^/]*$|^include/linux/filter\\\\.h$|^include/linux/tnum\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^kernel/trace/bpf_trace\\\\.c$|^kernel/bpf/stackmap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^net/core/filter\\\\.c$|^net/sched/act_bpf\\\\.c$|^net/sched/cls_bpf\\\\.c$\"},\n\t\t},\n\t}\n\n\tbrcm80211 = Subsystem{\n\t\tName: \"brcm80211\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/brcm80211/\"},\n\t\t},\n\t}\n\n\tbridge = Subsystem{\n\t\tName: \"bridge\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/netfilter_bridge/|^net/bridge/\"},\n\t\t},\n\t}\n\n\tbtrfs = Subsystem{\n\t\tName: \"btrfs\",\n\t\tSyscalls: []string{\"syz_mount_image$btrfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/btrfs/|^include/linux/btrfs[^/]*$|^include/trace/events/btrfs\\\\.h$|^include/uapi/linux/btrfs[^/]*$\"},\n\t\t},\n\t}\n\n\tcachefs = Subsystem{\n\t\tName: \"cachefs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/cachefiles/\"},\n\t\t\t{IncludeRegexp: \"^fs/fscache/|^include/linux/fscache[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\tcan = Subsystem{\n\t\tName: \"can\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/can/can327\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/ctucanfd/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/m_can/m_can\\\\.c$|^drivers/net/can/m_can/m_can\\\\.h$|^drivers/net/can/m_can/m_can_platform\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/slcan/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/spi/mcp251xfd/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/usb/esd_usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/usb/etas_es58x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/usb/mcba_usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/xilinx_can\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/can/|^drivers/phy/phy-can-transceiver\\\\.c$|^include/linux/can/bittiming\\\\.h$|^include/linux/can/dev\\\\.h$|^include/linux/can/length\\\\.h$|^include/linux/can/platform/|^include/linux/can/rx-offload\\\\.h$|^include/uapi/linux/can/error\\\\.h$|^include/uapi/linux/can/netlink\\\\.h$|^include/uapi/linux/can/vxcan\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/can/can-ml\\\\.h$|^include/linux/can/core\\\\.h$|^include/linux/can/skb\\\\.h$|^include/net/netns/can\\\\.h$|^include/uapi/linux/can\\\\.h$|^include/uapi/linux/can/bcm\\\\.h$|^include/uapi/linux/can/gw\\\\.h$|^include/uapi/linux/can/isotp\\\\.h$|^include/uapi/linux/can/raw\\\\.h$|^net/can/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/can/j1939\\\\.h$|^net/can/j1939/\"},\n\t\t},\n\t}\n\n\tceph = Subsystem{\n\t\tName: \"ceph\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/block/rbd\\\\.c$|^drivers/block/rbd_types\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/ceph/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/ceph/|^include/linux/crush/|^net/ceph/\"},\n\t\t},\n\t}\n\n\tcgroups = Subsystem{\n\t\tName: \"cgroups\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^block/bfq-cgroup\\\\.c$|^block/blk-cgroup\\\\.c$|^block/blk-iocost\\\\.c$|^block/blk-iolatency\\\\.c$|^block/blk-throttle\\\\.c$|^include/linux/blk-cgroup\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/cgroup[^/]*$|^kernel/cgroup/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/cpuset\\\\.h$|^kernel/cgroup/cpuset\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/memcontrol\\\\.c$|^mm/swap_cgroup\\\\.c$\"},\n\t\t},\n\t}\n\n\tchrome = Subsystem{\n\t\tName: \"chrome\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/platform/chrome/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/chrome/cros_ec_typec\\\\.[^/]*$|^drivers/platform/chrome/cros_typec_switch\\\\.c$|^drivers/platform/chrome/cros_typec_vdm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/chrome/cros_usbpd_notify\\\\.c$|^include/linux/platform_data/cros_usbpd_notify\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/cros_usbpd-charger\\\\.c$|cros_ec|cros-ec\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/codecs/cros_ec_codec\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\tcifs = Subsystem{\n\t\tName: \"cifs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/cifs/|^fs/smbfs_common/|^include/uapi/linux/cifs$\"},\n\t\t\t{IncludeRegexp: \"^fs/ksmbd/|^fs/smbfs_common/\"},\n\t\t},\n\t}\n\n\tcirrus = Subsystem{\n\t\tName: \"cirrus\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&alsa},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-s3c/mach-crag6410[^/]*$|^drivers/clk/clk-wm83[^/]*\\\\.c$|^drivers/gpio/gpio-[^/]*wm[^/]*\\\\.c$|^drivers/gpio/gpio-arizona\\\\.c$|^drivers/hwmon/wm83..-hwmon\\\\.c$|^drivers/input/misc/wm831x-on\\\\.c$|^drivers/input/touchscreen/wm831x-ts\\\\.c$|^drivers/input/touchscreen/wm97[^/]*\\\\.c$|^drivers/leds/leds-wm83[^/]*\\\\.c$|^drivers/mfd/arizona[^/]*$|^drivers/mfd/cs47l24[^/]*$|^drivers/mfd/wm[^/]*\\\\.c$|^drivers/power/supply/wm83[^/]*\\\\.c$|^drivers/regulator/arizona[^/]*$|^drivers/regulator/wm8[^/]*\\\\.c$|^drivers/rtc/rtc-wm83[^/]*\\\\.c$|^drivers/video/backlight/wm83[^/]*_bl\\\\.c$|^drivers/watchdog/wm83[^/]*_wdt\\\\.c$|^include/linux/mfd/arizona/|^include/linux/mfd/wm831x/|^include/linux/mfd/wm8350/|^include/linux/mfd/wm8400[^/]*$|^include/linux/regulator/arizona[^/]*$|^include/linux/wm97xx\\\\.h$|^include/sound/wm....\\\\.h$|^sound/soc/codecs/arizona[^/]*$|^sound/soc/codecs/cs47l24[^/]*$|^sound/soc/codecs/wm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/clk-lochnagar\\\\.c$|^drivers/hwmon/lochnagar-hwmon\\\\.c$|^drivers/mfd/lochnagar-i2c\\\\.c$|^drivers/pinctrl/cirrus/pinctrl-lochnagar\\\\.c$|^drivers/regulator/lochnagar-regulator\\\\.c$|^include/dt-bindings/clock/lochnagar\\\\.h$|^include/dt-bindings/pinctrl/lochnagar\\\\.h$|^include/linux/mfd/lochnagar[^/]*$|^sound/soc/codecs/lochnagar-sc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/cirrus/|^include/linux/firmware/cirrus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-madera[^/]*$|^drivers/irqchip/irq-madera[^/]*$|^drivers/mfd/cs47l[^/]*$|^drivers/mfd/madera[^/]*$|^drivers/pinctrl/cirrus/|^include/dt-bindings/sound/madera[^/]*$|^include/linux/irqchip/irq-madera[^/]*$|^include/linux/mfd/madera/|^include/sound/madera[^/]*$|^sound/soc/codecs/cs47l[^/]*$|^sound/soc/codecs/madera[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/dt-bindings/sound/cs[^/]*$|^sound/pci/hda/cs[^/]*$|^sound/pci/hda/hda_cs_dsp_ctl\\\\.[^/]*$|^sound/soc/codecs/cs[^/]*$\"},\n\t\t},\n\t}\n\n\tclk = Subsystem{\n\t\tName: \"clk\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/clk/imx/|^include/dt-bindings/clock/imx[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/ux500/\"},\n\t\t\t{\"^drivers/clk/|^include/dt-bindings/clock/|^include/linux/clk-pr[^/]*$|^include/linux/clk/|^include/linux/of_clk\\\\.h$\", \"^drivers/clk/clkdev\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/dt-bindings/clock/loongson,ls2k-clk\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/clk\\\\.h$\"},\n\t\t},\n\t}\n\n\tcoda = Subsystem{\n\t\tName: \"coda\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/coda/|^include/linux/coda[^/]*\\\\.h$|^include/uapi/linux/coda[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\tcoresight = Subsystem{\n\t\tName: \"coresight\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/hwtracing/coresight/|^include/dt-bindings/arm/coresight-cti-dt\\\\.h$|^include/linux/coresight[^/]*$\"},\n\t\t},\n\t}\n\n\tcrypto = Subsystem{\n\t\tName: \"crypto\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/crypto/|^crypto/|^drivers/crypto/|^include/crypto/|^include/linux/crypto[^/]*$|^lib/crypto/\"},\n\t\t\t{IncludeRegexp: \"^crypto/ansi_cprng\\\\.c$|^crypto/rng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^crypto/pcrypt\\\\.c$|^include/crypto/pcrypt\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/hw_random/cctrng\\\\.c$|^drivers/char/hw_random/cctrng\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/hw_random/|^include/linux/hw_random\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/allwinner/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/amlogic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/atmel-ecc\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/caam/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/cavium/cpt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/ccp/sev[^/]*$|^include/uapi/linux/psp-sev\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/ccp/|^include/linux/ccp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/ccree/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/chelsio$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/exynos-rng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/gemini/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/hisilicon/Kconfig$|^drivers/crypto/hisilicon/qm\\\\.c$|^drivers/crypto/hisilicon/sgl\\\\.c$|^include/linux/hisi_acc_qm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/hisilicon/hpre/hpre\\\\.h$|^drivers/crypto/hisilicon/hpre/hpre_crypto\\\\.c$|^drivers/crypto/hisilicon/hpre/hpre_main\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/hisilicon/sec2/sec\\\\.h$|^drivers/crypto/hisilicon/sec2/sec_crypto\\\\.c$|^drivers/crypto/hisilicon/sec2/sec_crypto\\\\.h$|^drivers/crypto/hisilicon/sec2/sec_main\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/hisilicon/zip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/inside-secure/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/ixp4xx_crypto\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/marvell/|^include/linux/soc/marvell/octeontx2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/nx/Kconfig$|^drivers/crypto/nx/nx-aes[^/]*$|^drivers/crypto/nx/nx-sha[^/]*$|^drivers/crypto/nx/nx\\\\.[^/]*$|^drivers/crypto/nx/nx_csbcpb\\\\.h$|^drivers/crypto/nx/nx_debugfs\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/qce/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/rockchip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/s5p-sss\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/virtio/|^include/uapi/linux/virtio_crypto\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/vmx/Kconfig$|^drivers/crypto/vmx/aes[^/]*$|^drivers/crypto/vmx/ghash[^/]*$|^drivers/crypto/vmx/ppc-xlate\\\\.pl$|^drivers/crypto/vmx/vmx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/padata\\\\.h$|^kernel/padata\\\\.c$\"},\n\t\t},\n\t}\n\n\tcsky = Subsystem{\n\t\tName: \"csky\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/csky/|^drivers/clocksource/timer-gx6605s\\\\.c$|^drivers/clocksource/timer-mp-csky\\\\.c$|^drivers/irqchip/irq-csky-[^/]*$|csky\"},\n\t\t},\n\t}\n\n\tcxl = Subsystem{\n\t\tName: \"cxl\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/cxl/|^include/uapi/linux/cxl_mem\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dax/\"},\n\t\t},\n\t}\n\n\tdamon = Subsystem{\n\t\tName: \"damon\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&mm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/damon\\\\.h$|^include/trace/events/damon\\\\.h$|^mm/damon/\"},\n\t\t},\n\t}\n\n\tdccp = Subsystem{\n\t\tName: \"dccp\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/dccp\\\\.h$|^include/linux/tfrc\\\\.h$|^include/uapi/linux/dccp\\\\.h$|^net/dccp/\"},\n\t\t},\n\t}\n\n\tdell = Subsystem{\n\t\tName: \"dell\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&x86drivers},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/alienware-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios-smm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-wmi-descriptor\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-wmi-privacy\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-wmi-sysman/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/wmi/thunderbolt\\\\.c$\"},\n\t\t},\n\t}\n\n\tdevicetree = Subsystem{\n\t\tName: \"devicetree\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/boot/dts/|^include/dt-bindings/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/[^/]*am3[^/]*$|^arch/arm/boot/dts/[^/]*am4[^/]*$|^arch/arm/boot/dts/[^/]*am5[^/]*$|^arch/arm/boot/dts/[^/]*dra7[^/]*$|^arch/arm/boot/dts/[^/]*omap[^/]*$|^arch/arm/boot/dts/logicpd-som-lv[^/]*$|^arch/arm/boot/dts/logicpd-torpedo[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/of/|^include/linux/of[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\tdm = Subsystem{\n\t\tName: \"dm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/md/Kconfig$|^drivers/md/dm[^/]*$|^drivers/md/persistent-data/|^include/linux/device-mapper\\\\.h$|^include/linux/dm-[^/]*\\\\.h$|^include/uapi/linux/dm-[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\tdmaengine = Subsystem{\n\t\tName: \"dmaengine\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/dma/altera-msgdma\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/at_hdmac\\\\.c$|^drivers/dma/at_xdmac\\\\.c$|^include/dt-bindings/dma/at91\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/dw-edma/|^include/linux/dma/edma\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/hisi_dma\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/idxd/|^include/uapi/linux/idxd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/ioat[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/ptdma/\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/qcom/hidma[^/]*$\"},\n\t\t\t{\"^drivers/dma/ti/|^include/linux/dma/k3-udma-glue\\\\.h$|^include/linux/dma/ti-cppi5\\\\.h$|^include/linux/dma/k3-psil\\\\.h$\", \"^drivers/dma/ti/cppi41\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/xilinx/xdma-regs\\\\.h$|^drivers/dma/xilinx/xdma\\\\.c$|^include/linux/dma/amd_xdma\\\\.h$|^include/linux/platform_data/amd_xdma\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/xilinx/xilinx_dpdma\\\\.c$|^include/dt-bindings/dma/xlnx-zynqmp-dpdma\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/|^include/dt-bindings/dma/|^include/linux/dma/|^include/linux/dmaengine\\\\.h$|^include/linux/of_dma\\\\.h$\"},\n\t\t},\n\t}\n\n\tdrbd = Subsystem{\n\t\tName: \"drbd\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&block},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/block/drbd/|^include/linux/drbd[^/]*$|^lib/lru_cache\\\\.c$\"},\n\t\t},\n\t}\n\n\tdri = Subsystem{\n\t\tName: \"dri\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/accel/habanalabs/|^include/trace/events/habanalabs\\\\.h$|^include/uapi/drm/habanalabs_accel\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/accel/ivpu/|^include/uapi/drm/ivpu_accel\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/accel/|^include/drm/drm_accel\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/component\\\\.c$|^include/linux/component\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/agp/|^include/linux/agp[^/]*$|^include/uapi/linux/agp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/dma-fence[^/]*$|^drivers/dma-buf/sw_sync\\\\.c$|^drivers/dma-buf/sync_[^/]*$|^include/linux/sync_file\\\\.h$|^include/uapi/linux/sync_file\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/dma-heap\\\\.c$|^drivers/dma-buf/heaps/|^include/linux/dma-heap\\\\.h$|^include/uapi/linux/dma-heap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/udmabuf\\\\.c$|^include/uapi/linux/udmabuf\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/|^include/linux/[^/]*fence\\\\.h$|^include/linux/dma-buf\\\\.h$|^include/linux/dma-resv\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/ast/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/atmel-hlcdc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/bridge/imx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/drm_aperture\\\\.c$|^drivers/gpu/drm/tiny/ofdrm\\\\.c$|^drivers/gpu/drm/tiny/simpledrm\\\\.c$|^drivers/video/aperture\\\\.c$|^drivers/video/nomodeset\\\\.c$|^include/drm/drm_aperture\\\\.h$|^include/linux/aperture\\\\.h$|^include/video/nomodeset\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/drm_panel\\\\.c$|^drivers/gpu/drm/panel/|^include/drm/drm_panel\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/drm_privacy_screen[^/]*$|^include/drm/drm_privacy_screen[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/etnaviv/|^include/uapi/drm/etnaviv_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/exynos/exynos_dp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/exynos/|^include/uapi/drm/exynos_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/fsl-dcu/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/gma500/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/hisilicon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/hyperv$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/imx/dcss/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/imx/ipuv3/|^drivers/gpu/ipu-v3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/lima/|^include/uapi/drm/lima_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/mediatek/|^drivers/phy/mediatek/phy-mtk-dp\\\\.c$|^drivers/phy/mediatek/phy-mtk-hdmi[^/]*$|^drivers/phy/mediatek/phy-mtk-mipi[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/meson/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/mgag200/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/msm/|^include/uapi/drm/msm_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/mxsfb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/nouveau/|^include/uapi/drm/nouveau_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/omapdrm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/panel/panel-lvds\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/panfrost/|^include/uapi/drm/panfrost_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/rcar-du/|^drivers/gpu/drm/shmobile/|^include/linux/platform_data/shmob_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/rockchip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/scheduler/|^include/drm/gpu_scheduler\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/sti$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/stm$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/sun4i/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/sun4i/sun8i[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tegra/|^drivers/gpu/host1x/|^include/linux/host1x\\\\.h$|^include/uapi/drm/tegra_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tidss/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tilcdc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/ttm/|^include/drm/ttm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/udl/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/vboxvideo/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/virtio/|^include/uapi/linux/virtio_gpu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/vkms/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/vmwgfx/|^include/uapi/drm/vmwgfx_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/xen/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/xlnx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/|^include/drm/|^include/linux/vga[^/]*$|^include/uapi/drm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/fbtft/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/backlight/|^include/linux/backlight\\\\.h$|^include/linux/pwm_backlight\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/|^include/linux/fb\\\\.h$|^include/uapi/linux/fb\\\\.h$|^include/uapi/video/|^include/video/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/iosys-map\\\\.h$\"},\n\t\t},\n\t}\n\n\tecryptfs = Subsystem{\n\t\tName: \"ecryptfs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/ecryptfs/\"},\n\t\t},\n\t}\n\n\tedac = Subsystem{\n\t\tName: \"edac\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/cpu/mce/\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/amd64_edac[^/]*$|^drivers/edac/mce_amd[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/armada_xp_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/dmc520_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/e752x_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/e7xxx_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/fsl_ddr_edac\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/ghes_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/highbank[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i10nm_base\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i3000_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i5000_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i5400_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i7300_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i7core_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i82443bxgx_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/i82975x_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/ie31200_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/igen6_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/mpc85xx_edac\\\\.\\\\[ch\\\\]$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/octeon_edac[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/pasemi_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/pnd2_edac\\\\.\\\\[ch\\\\]$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/qcom_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/r82600_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/sb_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/skx_[^/]*\\\\.\\\\[ch\\\\]$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/thunderx_edac[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/ti_edac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/|^include/linux/edac\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ras/|^include/linux/ras\\\\.h$|^include/ras/ras_event\\\\.h$\"},\n\t\t},\n\t}\n\n\tefi = Subsystem{\n\t\tName: \"efi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/efi\\\\.h$|^arch/[^/]*/kernel/efi\\\\.c$|^arch/arm/boot/compressed/efi-header\\\\.S$|^arch/x86/platform/efi/|^drivers/firmware/efi/|^include/linux/efi[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^block/partitions/efi\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/efi/test/\"},\n\t\t\t{IncludeRegexp: \"^fs/efivarfs/\"},\n\t\t},\n\t}\n\n\terofs = Subsystem{\n\t\tName: \"erofs\",\n\t\tSyscalls: []string{\"syz_mount_image$erofs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/erofs/|^include/trace/events/erofs\\\\.h$\"},\n\t\t},\n\t}\n\n\tetnaviv = Subsystem{\n\t\tName: \"etnaviv\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/etnaviv/|^include/uapi/drm/etnaviv_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\text4 = Subsystem{\n\t\tName: \"ext4\",\n\t\tSyscalls: []string{\"syz_mount_image$ext4\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/ext2/|^include/linux/ext2[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^fs/ext4/|^include/trace/events/ext4\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/jbd2/|^include/linux/jbd2\\\\.h$\"},\n\t\t},\n\t}\n\n\tf2fs = Subsystem{\n\t\tName: \"f2fs\",\n\t\tSyscalls: []string{\"syz_mount_image$f2fs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/f2fs/|^include/linux/f2fs_fs\\\\.h$|^include/trace/events/f2fs\\\\.h$|^include/uapi/linux/f2fs\\\\.h$\"},\n\t\t},\n\t}\n\n\tfat = Subsystem{\n\t\tName: \"fat\",\n\t\tSyscalls: []string{\"syz_mount_image$msdos\", \"syz_mount_image$vfat\", \"syz_mount_image$exfat\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/exfat/\"},\n\t\t\t{IncludeRegexp: \"^fs/fat/\"},\n\t\t},\n\t}\n\n\tfbdev = Subsystem{\n\t\tName: \"fbdev\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/staging/fbtft/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/fbtft/fb_seps525\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/sm750fb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/atmel_lcdfb\\\\.c$|^include/video/atmel_lcdc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/aty/aty128fb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/aty/radeon[^/]*$|^include/uapi/linux/radeonfb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/efifb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/fsl-diu-fb\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/i810/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/imsttfb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/imxfb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/intelfb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/matrox/matroxfb_[^/]*$|^include/uapi/linux/matroxfb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/nvidia/|^drivers/video/fbdev/riva/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/omap/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/omap2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/s3c-fb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/savage/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/simplefb\\\\.c$|^include/linux/platform_data/simplefb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/sm712[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/smscufx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/udlfb\\\\.c$|^include/video/udlfb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/uvesafb\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/via/|^include/linux/via-core\\\\.h$|^include/linux/via-gpio\\\\.h$|^include/linux/via_i2c\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/|^include/linux/fb\\\\.h$|^include/uapi/linux/fb\\\\.h$|^include/uapi/video/|^include/video/\"},\n\t\t},\n\t}\n\n\tfpga = Subsystem{\n\t\tName: \"fpga\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/fpga/dfl[^/]*$|^drivers/uio/uio_dfl\\\\.c$|^include/linux/dfl\\\\.h$|^include/uapi/linux/fpga-dfl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/fpga/intel-m10-bmc-sec-update\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/fpga/microchip-spi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/fpga/|^include/linux/fpga/\"},\n\t\t},\n\t}\n\n\tfreedreno = Subsystem{\n\t\tName: \"freedreno\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&armmsm, &dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/msm/|^include/uapi/drm/msm_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tfs = Subsystem{\n\t\tName: \"fs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/affs/\"},\n\t\t\t{IncludeRegexp: \"^fs/dax\\\\.c$|^include/linux/dax\\\\.h$|^include/trace/events/fs_dax\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/exfat/\"},\n\t\t\t{IncludeRegexp: \"^fs/fcntl\\\\.c$|^fs/locks\\\\.c$|^include/linux/fcntl\\\\.h$|^include/uapi/linux/fcntl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/fuse/virtio_fs\\\\.c$|^include/uapi/linux/virtio_fs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/fuse/|^include/uapi/linux/fuse\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/hfs/\"},\n\t\t\t{IncludeRegexp: \"^fs/hfsplus/\"},\n\t\t\t{IncludeRegexp: \"^fs/iomap/|^include/linux/iomap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/isofs/\"},\n\t\t\t{IncludeRegexp: \"^fs/notify/dnotify/|^include/linux/dnotify\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/notify/fanotify/|^include/linux/fanotify\\\\.h$|^include/uapi/linux/fanotify\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/notify/inotify/|^include/linux/inotify\\\\.h$|^include/uapi/linux/inotify\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/notify/|^include/linux/fsnotify[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/proc/proc_sysctl\\\\.c$|^include/linux/sysctl\\\\.h$|^kernel/sysctl-test\\\\.c$|^kernel/sysctl\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/proc/|^include/linux/proc_fs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/unicode/\"},\n\t\t\t{IncludeRegexp: \"^fs/vboxsf/\"},\n\t\t\t{IncludeRegexp: \"^fs/zonefs/\"},\n\t\t\t{IncludeRegexp: \"^fs/|^include/linux/fs\\\\.h$|^include/linux/fs_types\\\\.h$|^include/uapi/linux/fs\\\\.h$|^include/uapi/linux/openat2\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/idr\\\\.h$|^include/linux/xarray\\\\.h$|^lib/idr\\\\.c$|^lib/xarray\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/mnt_idmapping\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/pagemap\\\\.h$|^mm/filemap\\\\.c$|^mm/page-writeback\\\\.c$|^mm/readahead\\\\.c$|^mm/truncate\\\\.c$\"},\n\t\t},\n\t}\n\n\tfscrypt = Subsystem{\n\t\tName: \"fscrypt\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/crypto/|^include/linux/fscrypt\\\\.h$|^include/uapi/linux/fscrypt\\\\.h$\"},\n\t\t},\n\t}\n\n\tfsi = Subsystem{\n\t\tName: \"fsi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/fsi/|^include/linux/fsi[^/]*\\\\.h$|^include/trace/events/fsi[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\tfsverity = Subsystem{\n\t\tName: \"fsverity\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/verity/|^include/linux/fsverity\\\\.h$|^include/uapi/linux/fsverity\\\\.h$\"},\n\t\t},\n\t}\n\n\tfuse = Subsystem{\n\t\tName: \"fuse\",\n\t\tSyscalls: []string{\"syz_fuse_handle_req\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/fuse/|^include/uapi/linux/fuse\\\\.h$\"},\n\t\t},\n\t}\n\n\tgeode = Subsystem{\n\t\tName: \"geode\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fbdev},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/geode\\\\.h$|^drivers/char/hw_random/geode-rng\\\\.c$|^drivers/crypto/geode[^/]*$|^drivers/video/fbdev/geode/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/amd5536udc\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\tgfs2 = Subsystem{\n\t\tName: \"gfs2\",\n\t\tSyscalls: []string{\"syz_mount_image$gfs2\", \"syz_mount_image$gfs2meta\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/dlm/\"},\n\t\t\t{IncludeRegexp: \"^fs/gfs2/|^include/uapi/linux/gfs2_ondisk\\\\.h$\"},\n\t\t},\n\t}\n\n\tgpio = Subsystem{\n\t\tName: \"gpio\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-104-dio-48e\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-104-idi-48\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-104-idio-16\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-aggregator\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-altera\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-amd-fch\\\\.c$|^include/linux/platform_data/gpio/gpio-amd-fch\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-davinci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-dwapb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-gpio-mm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-hisi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-i8255\\\\.c$|^drivers/gpio/gpio-i8255\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-ich\\\\.c$|^drivers/gpio/gpio-merrifield\\\\.c$|^drivers/gpio/gpio-ml-ioh\\\\.c$|^drivers/gpio/gpio-pch\\\\.c$|^drivers/gpio/gpio-sch\\\\.c$|^drivers/gpio/gpio-sodaville\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-idio-16\\\\.c$|^drivers/gpio/gpio-idio-16\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-mockup\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-pci-idio-16\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-pcie-idio-24\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-pxa\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-sama5d2-piobu\\\\.c$|^drivers/pinctrl/pinctrl-at91[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-virtio\\\\.c$|^include/uapi/linux/virtio_gpio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-wcove\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-ws16c48\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-xra1403\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpiolib-acpi\\\\.c$|^drivers/gpio/gpiolib-acpi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/|^include/asm-generic/gpio\\\\.h$|^include/dt-bindings/gpio/|^include/linux/gpio\\\\.h$|^include/linux/gpio/|^include/linux/of_gpio\\\\.h$|^include/uapi/linux/gpio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/mchp_pci1xxxx/mchp_pci1xxxx_gp\\\\.c$|^drivers/misc/mchp_pci1xxxx/mchp_pci1xxxx_gp\\\\.h$|^drivers/misc/mchp_pci1xxxx/mchp_pci1xxxx_gpio\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/bcm/pinctrl-bcm4908\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/freescale/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-cy8c95x0\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-k210\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-loongson2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/starfive/pinctrl-starfive-jh71[^/]*$|^include/dt-bindings/pinctrl/pinctrl-starfive-jh7100\\\\.h$|^include/dt-bindings/pinctrl/starfive,jh7110-pinctrl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/|^include/dt-bindings/pinctrl/|^include/linux/pinctrl/\"},\n\t\t},\n\t}\n\n\tgreybus = Subsystem{\n\t\tName: \"greybus\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&staging},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/greybus/|^drivers/staging/greybus/|^include/linux/greybus\\\\.h$|^include/linux/greybus/\"},\n\t\t},\n\t}\n\n\thams = Subsystem{\n\t\tName: \"hams\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/hamradio/6pack\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/hamradio/[^/]*scc\\\\.c$|^drivers/net/hamradio/z8530\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/hamradio/baycom[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/hamradio/scc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/hamradio/yam[^/]*$|^include/linux/yam\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/net/ax25\\\\.h$|^include/uapi/linux/ax25\\\\.h$|^net/ax25/\"},\n\t\t\t{IncludeRegexp: \"^include/net/netrom\\\\.h$|^include/uapi/linux/netrom\\\\.h$|^net/netrom/\"},\n\t\t\t{IncludeRegexp: \"^include/net/rose\\\\.h$|^include/uapi/linux/rose\\\\.h$|^net/rose/\"},\n\t\t\t{IncludeRegexp: \"^net/ax25/af_ax25\\\\.c$|^net/ax25/ax25_dev\\\\.c$|^net/ax25/ax25_ds_[^/]*$|^net/ax25/ax25_in\\\\.c$|^net/ax25/ax25_out\\\\.c$|^net/ax25/ax25_timer\\\\.c$|^net/ax25/sysctl_net_ax25\\\\.c$\"},\n\t\t},\n\t}\n\n\thardening = Subsystem{\n\t\tName: \"hardening\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/acpi/apei/erst\\\\.c$|^drivers/firmware/efi/efi-pstore\\\\.c$|^fs/pstore/|^include/linux/pstore[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/fortify-string\\\\.h$|^lib/fortify_kunit\\\\.c$|^lib/memcpy_kunit\\\\.c$|^lib/strscpy_kunit\\\\.c$|^lib/test_fortify/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/overflow\\\\.h$|^include/linux/randomize_kstack\\\\.h$|^mm/usercopy\\\\.c$\"},\n\t\t},\n\t}\n\n\thexagon = Subsystem{\n\t\tName: \"hexagon\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/hexagon/\"},\n\t\t},\n\t}\n\n\thfs = Subsystem{\n\t\tName: \"hfs\",\n\t\tSyscalls: []string{\"syz_mount_image$hfs\", \"syz_mount_image$hfsplus\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/hfs/\"},\n\t\t\t{IncludeRegexp: \"^fs/hfsplus/\"},\n\t\t},\n\t}\n\n\thippi = Subsystem{\n\t\tName: \"hippi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/hippi/|^include/linux/hippidevice\\\\.h$|^include/uapi/linux/if_hippi\\\\.h$|^net/802/hippi\\\\.c$\"},\n\t\t},\n\t}\n\n\thwmon = Subsystem{\n\t\tName: \"hwmon\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/abituguru3\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/abituguru\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/adm1025\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/adm1029\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/adm1177\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/adt7475\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/applesmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/aquacomputer_d5next\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/asc7621\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/asus-ec-sensors\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/asus_atk0110\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/asus_wmi_sensors\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/axi-fan-control\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/coretemp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/corsair-cpro\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/corsair-psu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/dme1737\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/emc2103\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/f71805f\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/f75375s\\\\.c$|^include/linux/f75375s\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/fam15h_power\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/ina209\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/ina2xx\\\\.c$|^include/linux/platform_data/ina2xx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/it87\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/jc42\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/k10temp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/k8temp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/lm73\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/lm78\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/lm83\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/lm90\\\\.c$|^include/dt-bindings/thermal/lm90\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/lm95234\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/ltc2947-core\\\\.c$|^drivers/hwmon/ltc2947-i2c\\\\.c$|^drivers/hwmon/ltc2947-spi\\\\.c$|^drivers/hwmon/ltc2947\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/ltc4261\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/max16065\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/max6650\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/max6697\\\\.c$|^include/linux/platform_data/max6697\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/nct6775-core\\\\.c$|^drivers/hwmon/nct6775-platform\\\\.c$|^drivers/hwmon/nct6775\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/nct6775-i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/nzxt-kraken2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/nzxt-smart2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/oxp-sensors\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pc87360\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pc87427\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/peci/\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/delta-ahe50dc-fan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/dps920ab\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/max15301\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/pm6764tr\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/stpddc60\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/tps546d24\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/pmbus/|^include/linux/pmbus\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/sch5627\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/smm665\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/smsc47b397\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/tmp401\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/tmp464\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/tmp513\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/tps23861\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/vt1211\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/vt8231\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/w83791d\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/w83793\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/w83795\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwmon/|^include/linux/hwmon[^/]*\\\\.h$|^include/trace/events/hwmon[^/]*\\\\.h$\"},\n\t\t},\n\t}\n\n\thyperv = Subsystem{\n\t\tName: \"hyperv\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm64/hyperv$|^arch/arm64/include/asm/hyperv-tlfs\\\\.h$|^arch/arm64/include/asm/mshyperv\\\\.h$|^arch/x86/hyperv$|^arch/x86/include/asm/hyperv-tlfs\\\\.h$|^arch/x86/include/asm/mshyperv\\\\.h$|^arch/x86/include/asm/trace/hyperv\\\\.h$|^arch/x86/kernel/cpu/mshyperv\\\\.c$|^drivers/clocksource/hyperv_timer\\\\.c$|^drivers/hid/hid-hyperv\\\\.c$|^drivers/hv/|^drivers/input/serio/hyperv-keyboard\\\\.c$|^drivers/iommu/hyperv-iommu\\\\.c$|^drivers/net/ethernet/microsoft/|^drivers/net/hyperv/|^drivers/pci/controller/pci-hyperv-intf\\\\.c$|^drivers/pci/controller/pci-hyperv\\\\.c$|^drivers/scsi/storvsc_drv\\\\.c$|^drivers/uio/uio_hv_generic\\\\.c$|^drivers/video/fbdev/hyperv_fb\\\\.c$|^include/asm-generic/hyperv-tlfs\\\\.h$|^include/asm-generic/mshyperv\\\\.h$|^include/clocksource/hyperv_timer\\\\.h$|^include/linux/hyperv\\\\.h$|^include/net/mana$|^include/uapi/linux/hyperv\\\\.h$|^net/vmw_vsock/hyperv_transport\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/hyperv$\"},\n\t\t},\n\t}\n\n\ti2c = Subsystem{\n\t\tName: \"i2c\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-ft260\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-mcp2221\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/algos/|^drivers/i2c/busses/|^include/dt-bindings/i2c/\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-ali1535\\\\.c$|^drivers/i2c/busses/i2c-ali1563\\\\.c$|^drivers/i2c/busses/i2c-ali15x3\\\\.c$|^drivers/i2c/busses/i2c-amd756-s4882\\\\.c$|^drivers/i2c/busses/i2c-amd756\\\\.c$|^drivers/i2c/busses/i2c-amd8111\\\\.c$|^drivers/i2c/busses/i2c-i801\\\\.c$|^drivers/i2c/busses/i2c-isch\\\\.c$|^drivers/i2c/busses/i2c-nforce2-s4985\\\\.c$|^drivers/i2c/busses/i2c-nforce2\\\\.c$|^drivers/i2c/busses/i2c-piix4\\\\.c$|^drivers/i2c/busses/i2c-sis5595\\\\.c$|^drivers/i2c/busses/i2c-sis630\\\\.c$|^drivers/i2c/busses/i2c-sis96x\\\\.c$|^drivers/i2c/busses/i2c-via\\\\.c$|^drivers/i2c/busses/i2c-viapro\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-ali1563\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-amd-mp2[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-aspeed\\\\.c$|^drivers/irqchip/irq-aspeed-i2c-ic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-at91-[^/]*\\\\.c$|^drivers/i2c/busses/i2c-at91\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-axxia\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-brcmstb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-cht-wc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-cpm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-designware-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-diolan-u2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-fsi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-hisi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-icy\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-imx-lpi2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-imx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-ismt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-ls2x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mchp-pci1xxxx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mlxbf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mlxcpld\\\\.c$|^drivers/i2c/muxes/i2c-mux-mlxcpld\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mpc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mt65xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mt7621\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-mv64xxx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-nvidia-gpu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-ocores\\\\.c$|^include/linux/platform_data/i2c-ocores\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-omap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-parport\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-qcom-cci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-stm32[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-synquacer\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-taos-evm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-tiny-usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-virtio\\\\.c$|^include/uapi/linux/virtio_i2c\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-xlp9xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/i2c-core-acpi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/i2c-mux\\\\.c$|^drivers/i2c/muxes/|^include/linux/i2c-mux\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/i2c-stub\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/muxes/i2c-mux-gpio\\\\.c$|^include/linux/platform_data/i2c-mux-gpio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/muxes/i2c-mux-ltc4306\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/muxes/i2c-mux-pca9541\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/|^include/dt-bindings/i2c/i2c\\\\.h$|^include/linux/i2c-dev\\\\.h$|^include/linux/i2c-smbus\\\\.h$|^include/linux/i2c\\\\.h$|^include/uapi/linux/i2c-[^/]*\\\\.h$|^include/uapi/linux/i2c\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/eeprom/at24\\\\.c$\"},\n\t\t},\n\t}\n\n\ti3c = Subsystem{\n\t\tName: \"i3c\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/i3c/master/svc-i3c-master\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i3c/|^include/linux/i3c/\"},\n\t\t},\n\t}\n\n\tia64 = Subsystem{\n\t\tName: \"ia64\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/ia64/\"},\n\t\t},\n\t}\n\n\tide = Subsystem{\n\t\tName: \"ide\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/ata/ahci_dwc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/ahci_platform\\\\.c$|^drivers/ata/libahci_platform\\\\.c$|^include/linux/ahci_platform\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/ata_[^/]*\\\\.c$|^drivers/ata/pata_[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/pata_arasan_cf\\\\.c$|^include/linux/pata_arasan_cf_data\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/pata_ftide010\\\\.c$|^drivers/ata/sata_gemini\\\\.c$|^drivers/ata/sata_gemini\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/sata_promise\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/sata_rcar\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/|^include/linux/ata\\\\.h$|^include/linux/libata\\\\.h$\"},\n\t\t},\n\t}\n\n\tiio = Subsystem{\n\t\tName: \"iio\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/counter/104-quad-8\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/ftm-quaddec\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/intel-qep\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/interrupt-cnt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/microchip-tcb-capture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/ti-ecap-capture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/ti-eqep\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/|^include/linux/counter\\\\.h$|^include/uapi/linux/counter\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-sensor-[^/]*$|^drivers/iio/[^/]*/hid-[^/]*$|^include/linux/hid-sensor-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/accel/adxl355\\\\.h$|^drivers/iio/accel/adxl355_core\\\\.c$|^drivers/iio/accel/adxl355_i2c\\\\.c$|^drivers/iio/accel/adxl355_spi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/accel/adxl367[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/accel/bma400[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/accel/kionix-kx022a[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/accel/msa311\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ad4130\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ad7192\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ad7292\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ad7768-1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ad7780\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/at91-sama5d2_adc\\\\.c$|^include/dt-bindings/iio/adc/at91-sama5d2_adc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/envelope-detector\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/hx711\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/imx7d_adc\\\\.c$|^drivers/iio/adc/imx93_adc\\\\.c$|^drivers/iio/adc/vf610_adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/imx8qxp-adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/max11205\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/mcp3911\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/rcar-gyroadc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/rzg2l_adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ti-ads7924\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ti-lmp92064\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/ti-tsc2046\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/xilinx-ams\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/addac/ad74115\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/addac/ad74413r\\\\.c$|^include/dt-bindings/iio/addac/adi,ad74413r\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/addac/stx104\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/afe/iio-rescale\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/amplifiers/ada4250\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/common/scmi_sensors/scmi_iio\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/ad3552r\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/ad7293\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/cio-dac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/dpot-dac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/ltc1660\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/ltc2688\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/dac/ti-dac7612\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/filter/admv8818\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/frequency/adf4377\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/frequency/admv1013\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/frequency/admv1014\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/frequency/adrf6780\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/gyro/adxrs290\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/gyro/fxas21002c\\\\.h$|^drivers/iio/gyro/fxas21002c_core\\\\.c$|^drivers/iio/gyro/fxas21002c_i2c\\\\.c$|^drivers/iio/gyro/fxas21002c_spi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/gyro/mpu3050[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/humidity/hts221[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/imu/adis16460\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/imu/adis16475\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/imu/adis\\\\.c$|^drivers/iio/imu/adis_buffer\\\\.c$|^drivers/iio/imu/adis_trigger\\\\.c$|^include/linux/iio/imu/adis\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/imu/inv_icm42600/\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/imu/st_lsm6dsx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/light/as73211\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/light/gp2ap002\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/magnetometer/ak8974\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/magnetometer/rm3100[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/magnetometer/tmag5273\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/multiplexer/iio-mux\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/potentiometer/ad5110\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/potentiometer/mcp4018\\\\.c$|^drivers/iio/potentiometer/mcp4531\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/pressure/dps310\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/proximity/mb1232\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/proximity/ping\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/proximity/srf[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/proximity/vl53l0x-i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/temperature/ltc2983\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/temperature/max30208\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/temperature/mlx90614\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/temperature/mlx90632\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/temperature/tmp117\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/|^drivers/staging/iio/|^include/dt-bindings/iio/|^include/linux/iio/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/iio/\"},\n\t\t},\n\t}\n\n\timx = Subsystem{\n\t\tName: \"imx\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm, &clk},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/clk/imx/|^include/dt-bindings/clock/imx[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-imx-lpi2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/imx7d_adc\\\\.c$|^drivers/iio/adc/imx93_adc\\\\.c$|^drivers/iio/adc/vf610_adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/imx8qxp-adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-esdhc-imx\\\\.c$\"},\n\t\t},\n\t}\n\n\tinput = Subsystem{\n\t\tName: \"input\",\n\t\tSyscalls: []string{\"syz_usb_connect$hid\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/hid/amd-sfh-hid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-creative-sb0540\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-ft260\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-letsketch\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-lg-g15\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-logitech-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-logitech-hidpp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-mcp2221\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-nintendo[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-picolcd[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-playstation\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-pxrc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-sensor-[^/]*$|^drivers/iio/[^/]*/hid-[^/]*$|^include/linux/hid-sensor-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-udraw-ps3\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-vrc2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/hid-wiimote[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/intel-ish-hid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/surface-hid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/uhid\\\\.c$|^include/uapi/linux/uhid\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/wacom\\\\.h$|^drivers/hid/wacom_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/|^include/linux/hid[^/]*$|^include/uapi/linux/hid[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/input-mt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/joystick/fsia6b\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/joystick/pxrc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/keyboard/cypress-sf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/keyboard/dlink-dir685-touchkeys\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/keyboard/sun4i-lradc-keys\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/misc/ibm-panel\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/misc/ideapad_slidebar\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/mouse/bcm5974\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/mouse/vmmouse\\\\.c$|^drivers/input/mouse/vmmouse\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/tablet/wacom_serial4\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/chipone_icn8318\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/chipone_icn8505\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/cy8ctma140\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/cyttsp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/goodix[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/himax_hx83112b\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/htcpen\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/hycon-hy46xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/resistive-adc-touch\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/silead\\\\.c$|^drivers/platform/x86/touchscreen_dmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/sis_i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/|^include/dt-bindings/input/|^include/linux/input\\\\.h$|^include/linux/input/|^include/uapi/linux/input-event-codes\\\\.h$|^include/uapi/linux/input\\\\.h$\"},\n\t\t},\n\t}\n\n\tintegrity = Subsystem{\n\t\tName: \"integrity\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/char/tpm/\"},\n\t\t\t{IncludeRegexp: \"^include/keys/encrypted-type\\\\.h$|^security/keys/encrypted-keys/\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted-type\\\\.h$|^include/keys/trusted_tpm\\\\.h$|^security/keys/trusted-keys/\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted_caam\\\\.h$|^security/keys/trusted-keys/trusted_caam\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted_tee\\\\.h$|^security/keys/trusted-keys/trusted_tee\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^security/integrity/evm/|^security/integrity/\"},\n\t\t\t{IncludeRegexp: \"^security/integrity/ima/|^security/integrity/\"},\n\t\t\t{IncludeRegexp: \"^security/integrity/platform_certs$\"},\n\t\t},\n\t}\n\n\tintelgfx = Subsystem{\n\t\tName: \"intel-gfx\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/i915/gvt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/i915/|^include/drm/i915[^/]*$|^include/uapi/drm/i915_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tintelgvt = Subsystem{\n\t\tName: \"intel-gvt\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&intelgfx},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/i915/gvt/\"},\n\t\t},\n\t}\n\n\tintelwiredlan = Subsystem{\n\t\tName: \"intel-wired-lan\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/intel/|^drivers/net/ethernet/intel/[^/]*/|^include/linux/avf/virtchnl\\\\.h$|^include/linux/net/intel/iidc\\\\.h$\"},\n\t\t},\n\t}\n\n\tiouring = Subsystem{\n\t\tName: \"io-uring\",\n\t\tSyscalls: []string{\"syz_io_uring_setup\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^io_uring/|^include/linux/io_uring\\\\.h$|^include/linux/io_uring_types\\\\.h$|^include/trace/events/io_uring\\\\.h$|^include/uapi/linux/io_uring\\\\.h$\"},\n\t\t},\n\t}\n\n\tiommu = Subsystem{\n\t\tName: \"iommu\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/xen/swiotlb-xen\\\\.h$|^drivers/xen/swiotlb-xen\\\\.c$|^include/xen/arm/swiotlb-xen\\\\.h$|^include/xen/swiotlb-xen\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/acpi/viot\\\\.c$|^include/linux/acpi_viot\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/amd/|^include/linux/amd-iommu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/arm/arm-smmu/qcom_iommu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/dma-iommu\\\\.c$|^drivers/iommu/dma-iommu\\\\.h$|^drivers/iommu/iova\\\\.c$|^include/linux/iova\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/exynos-iommu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/intel/\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/iommufd/|^include/linux/iommufd\\\\.h$|^include/uapi/linux/iommufd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/mtk_iommu[^/]*$|^include/dt-bindings/memory/mt[^/]*-port\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/|^include/linux/iommu\\\\.h$|^include/linux/iova\\\\.h$|^include/linux/of_iommu\\\\.h$|^include/uapi/linux/iommu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/dma-mapping\\\\.h$|^include/linux/dma-direct\\\\.h$|^include/linux/dma-mapping\\\\.h$|^include/linux/dma-map-ops\\\\.h$|^include/linux/swiotlb\\\\.h$|^kernel/dma/\"},\n\t\t\t{IncludeRegexp: \"^kernel/dma/map_benchmark\\\\.c$\"},\n\t\t},\n\t}\n\n\tipack = Subsystem{\n\t\tName: \"ipack\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/ipack/\"},\n\t\t},\n\t}\n\n\tisdn4linux = Subsystem{\n\t\tName: \"isdn4linux\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/isdn/Kconfig$|^drivers/isdn/hardware/|^drivers/isdn/mISDN/\"},\n\t\t\t{IncludeRegexp: \"^drivers/isdn/capi/|^include/linux/isdn/|^include/uapi/linux/isdn/|^net/bluetooth/cmtp/\"},\n\t\t},\n\t}\n\n\tisofs = Subsystem{\n\t\tName: \"isofs\",\n\t\tSyscalls: []string{\"syz_mount_image$iso9660\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/isofs/\"},\n\t\t},\n\t}\n\n\tjfs = Subsystem{\n\t\tName: \"jfs\",\n\t\tSyscalls: []string{\"syz_mount_image$jfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/jfs/\"},\n\t\t},\n\t}\n\n\tkarma = Subsystem{\n\t\tName: \"karma\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/omfs/\"},\n\t\t},\n\t}\n\n\tkasan = Subsystem{\n\t\tName: \"kasan\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/[^/]*kasan\\\\.h$|^arch/[^/]*/mm/kasan_init[^/]*$|^include/linux/kasan[^/]*\\\\.h$|^lib/Kconfig\\\\.kasan$|^mm/kasan/\"},\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/kfence\\\\.h$|^include/linux/kfence\\\\.h$|^lib/Kconfig\\\\.kfence$|^mm/kfence/\"},\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/kmsan\\\\.h$|^arch/[^/]*/mm/kmsan_[^/]*$|^include/linux/kmsan[^/]*\\\\.h$|^lib/Kconfig\\\\.kmsan$|^mm/kmsan/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/kcov\\\\.h$|^include/uapi/linux/kcov\\\\.h$|^kernel/kcov\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/kcsan[^/]*\\\\.h$|^kernel/kcsan/|^lib/Kconfig\\\\.kcsan$\"},\n\t\t},\n\t}\n\n\tkernel = Subsystem{\n\t\tName: \"kernel\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^[^/]*$|^[^/]*/\"},\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/events/|^arch/[^/]*/events/[^/]*/|^arch/[^/]*/include/asm/perf_event\\\\.h$|^arch/[^/]*/kernel/[^/]*/[^/]*/perf_event[^/]*\\\\.c$|^arch/[^/]*/kernel/[^/]*/perf_event[^/]*\\\\.c$|^arch/[^/]*/kernel/perf_callchain\\\\.c$|^arch/[^/]*/kernel/perf_event[^/]*\\\\.c$|^include/linux/perf_event\\\\.h$|^include/uapi/linux/perf_event\\\\.h$|^kernel/events/\"},\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/atomic[^/]*\\\\.h$|^include/[^/]*/atomic[^/]*\\\\.h$|^include/linux/refcount\\\\.h$\"},\n\t\t\t{\"^arch/[^/]*/include/asm/spinlock[^/]*\\\\.h$|^include/linux/lockdep\\\\.h$|^include/linux/mutex[^/]*\\\\.h$|^include/linux/rwlock[^/]*\\\\.h$|^include/linux/rwsem[^/]*\\\\.h$|^include/linux/seqlock\\\\.h$|^include/linux/spinlock[^/]*\\\\.h$|^kernel/locking/|^lib/locking[^/]*\\\\.\\\\[ch\\\\]$\", \"^kernel/locking/locktorture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/mt2[^/]*$|^arch/arm/boot/dts/mt6[^/]*$|^arch/arm/boot/dts/mt7[^/]*$|^arch/arm/boot/dts/mt8[^/]*$|^arch/arm/mach-mediatek/|^arch/arm64/boot/dts/mediatek/|^drivers/soc/mediatek/|mtk|mt[2678]\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/asm/membarrier\\\\.h$|^include/uapi/linux/membarrier\\\\.h$|^kernel/sched/membarrier\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/entry/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/entry/vdso/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/intel-family\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/resctrl\\\\.h$|^arch/x86/kernel/cpu/resctrl/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/cpu/hygon\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/cpu/zhaoxin\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/mm/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/mm/kmmio\\\\.c$|^arch/x86/mm/mmio-mod\\\\.c$|^arch/x86/mm/testmmiotrace\\\\.c$|^include/linux/mmiotrace\\\\.h$|^kernel/trace/trace_mmiotrace\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/[^/]*/[^/]*max77843\\\\.c$|^drivers/[^/]*/max14577[^/]*\\\\.c$|^drivers/[^/]*/max77686[^/]*\\\\.c$|^drivers/[^/]*/max77693[^/]*\\\\.c$|^drivers/clk/clk-max77686\\\\.c$|^drivers/extcon/extcon-max14577\\\\.c$|^drivers/extcon/extcon-max77693\\\\.c$|^drivers/rtc/rtc-max77686\\\\.c$|^include/linux/mfd/max14577[^/]*\\\\.h$|^include/linux/mfd/max77686[^/]*\\\\.h$|^include/linux/mfd/max77693[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/android/\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/arch_topology\\\\.c$|^include/linux/arch_topology\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/devcoredump\\\\.c$|^include/linux/devcoredump\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/firmware_loader/|^include/linux/firmware\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/regmap/|^include/linux/regmap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/zram/\"},\n\t\t\t{IncludeRegexp: \"^drivers/bus/fsl-mc/|^include/uapi/linux/fsl_mc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/xillybus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/clk-s2mps11\\\\.c$|^drivers/mfd/sec[^/]*\\\\.c$|^drivers/regulator/s2m[^/]*\\\\.c$|^drivers/regulator/s5m[^/]*\\\\.c$|^drivers/rtc/rtc-s5m\\\\.c$|^include/linux/mfd/samsung/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/keystone/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clocksource/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clocksource/timer-keystone\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/extcon/extcon-ptn5150\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/extcon/|^include/linux/extcon\\\\.h$|^include/linux/extcon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/stratix10-rsu\\\\.c$|^drivers/firmware/stratix10-svc\\\\.c$|^include/linux/firmware/intel/stratix10-smc\\\\.h$|^include/linux/firmware/intel/stratix10-svc-client\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-bd9571mwv\\\\.c$|^drivers/mfd/bd9571mwv\\\\.c$|^drivers/regulator/bd9571mwv-regulator\\\\.c$|^include/linux/mfd/bd9571mwv\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-max77650\\\\.c$|^drivers/input/misc/max77650-onkey\\\\.c$|^drivers/leds/leds-max77650\\\\.c$|^drivers/mfd/max77650\\\\.c$|^drivers/power/supply/max77650-charger\\\\.c$|^drivers/regulator/max77650-regulator\\\\.c$|^include/linux/mfd/max77650\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwtracing/ptt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/irqchip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mailbox/arm_mhuv2\\\\.c$|^include/linux/mailbox/arm_mhuv2_message\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mailbox/|^include/linux/mailbox_client\\\\.h$|^include/linux/mailbox_controller\\\\.h$|^include/dt-bindings/mailbox/\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/[^/]*emif[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/|^include/dt-bindings/memory/|^include/memory/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mfd/at91-usart\\\\.c$|^include/dt-bindings/mfd/at91-usart\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mfd/hi6421-spmi-pmic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/hisi_hikey_usb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/mei/|^drivers/watchdog/mei_wdt\\\\.c$|^include/linux/mei_aux\\\\.h$|^include/linux/mei_cl_bus\\\\.h$|^include/uapi/linux/mei\\\\.h$|^include/uapi/linux/uuid\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/uacce/|^include/linux/uacce\\\\.h$|^include/uapi/misc/uacce/\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/vmw_balloon\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/vmw_vmci/|^include/linux/vmw_vmci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/sja1105$|^drivers/net/pcs/pcs-xpcs-nxp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/broadcom/phy-brcm-usb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/samsung/phy-exynos4210-usb2\\\\.c$|^drivers/phy/samsung/phy-exynos4x12-usb2\\\\.c$|^drivers/phy/samsung/phy-exynos5250-usb2\\\\.c$|^drivers/phy/samsung/phy-s5pv210-usb2\\\\.c$|^drivers/phy/samsung/phy-samsung-usb2\\\\.c$|^drivers/phy/samsung/phy-samsung-usb2\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/xilinx/phy-zynqmp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/reset/keystone-reset\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/regulator/max20086-regulator\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/regulator/max77802-regulator\\\\.c$|^include/dt-bindings/[^/]*/[^/]*max77802\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/regulator/|^include/dt-bindings/regulator/|^include/linux/regulator/\"},\n\t\t\t{IncludeRegexp: \"^drivers/reset/reset-k210\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/fsl/dpio$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/ti/\"},\n\t\t\t{IncludeRegexp: \"^drivers/spmi/hisi-spmi-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spmi/|^include/dt-bindings/spmi/spmi\\\\.h$|^include/linux/spmi\\\\.h$|^include/trace/events/spmi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/vme_user/\"},\n\t\t\t{IncludeRegexp: \"^drivers/virt/nitro_enclaves/|^include/linux/nitro_enclaves\\\\.h$|^include/uapi/linux/nitro_enclaves\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/proc/bootconfig\\\\.c$|^include/linux/bootconfig\\\\.h$|^lib/bootconfig-data\\\\.S$|^lib/bootconfig\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/proc/proc_sysctl\\\\.c$|^include/linux/sysctl\\\\.h$|^kernel/sysctl-test\\\\.c$|^kernel/sysctl\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/proc/|^include/linux/proc_fs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/timerfd\\\\.c$|^include/linux/time_namespace\\\\.h$|^include/linux/timer[^/]*$|^kernel/time/[^/]*timer[^/]*$|^kernel/time/namespace\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/tracefs/|^include/linux/trace[^/]*\\\\.h$|^include/trace/|^kernel/trace/\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/futex\\\\.h$|^include/linux/futex\\\\.h$|^include/uapi/linux/futex\\\\.h$|^kernel/futex/\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/kprobes\\\\.h$|^include/linux/kprobes\\\\.h$|^kernel/kprobes\\\\.c$|^lib/test_kprobes\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/vdso/vsyscall\\\\.h$|^include/vdso/|^kernel/time/vsyscall\\\\.c$|^lib/vdso/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/clockchips\\\\.h$|^include/linux/hrtimer\\\\.h$|^kernel/time/clockevents\\\\.c$|^kernel/time/hrtimer\\\\.c$|^kernel/time/timer_[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/clocksource\\\\.h$|^include/linux/time\\\\.h$|^include/linux/timex\\\\.h$|^include/uapi/linux/time\\\\.h$|^include/uapi/linux/timex\\\\.h$|^kernel/time/alarmtimer\\\\.c$|^kernel/time/clocksource\\\\.c$|^kernel/time/ntp\\\\.c$|^kernel/time/time[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/entry-common\\\\.h$|^include/linux/entry-kvm\\\\.h$|^kernel/entry/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/frontswap\\\\.h$|^mm/frontswap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/kmod\\\\.h$|^kernel/kmod\\\\.c$|^lib/test_kmod\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/module\\\\.h$|^kernel/module/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/padata\\\\.h$|^kernel/padata\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/preempt\\\\.h$|^include/linux/sched\\\\.h$|^include/linux/wait\\\\.h$|^include/uapi/linux/sched\\\\.h$|^kernel/sched/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/sched/nohz\\\\.h$|^include/linux/tick\\\\.h$|^kernel/time/tick[^/]*\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/umh\\\\.h$|^kernel/umh\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/uuid\\\\.h$|^lib/test_uuid\\\\.c$|^lib/uuid\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/trace/events/rseq\\\\.h$|^include/uapi/linux/rseq\\\\.h$|^kernel/rseq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/irq/|^include/linux/group_cpus\\\\.h$|^lib/group_cpus\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/locking/locktorture\\\\.c$|^kernel/rcu/rcuscale\\\\.c$|^kernel/rcu/rcutorture\\\\.c$|^kernel/rcu/refscale\\\\.c$|^kernel/torture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/trace/ftrace[^/]*$|^kernel/trace/fgraph\\\\.c$|^arch/[^/]*/[^/]*/[^/]*/[^/]*ftrace[^/]*$|^arch/[^/]*/[^/]*/[^/]*ftrace[^/]*$|^include/[^/]*/ftrace\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^net/vmw_vsock/vmci_transport[^/]*$\"},\n\t\t\t{IncludeRegexp: \"axp[128]\"},\n\t\t},\n\t\tNoReminders: true,\n\t}\n\n\tkernfs = Subsystem{\n\t\tName: \"kernfs\",\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/kernfs/|^include/linux/kernfs\\\\.h$\"},\n\t\t},\n\t}\n\n\tkexec = Subsystem{\n\t\tName: \"kexec\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/proc/vmcore\\\\.c$|^include/linux/crash_core\\\\.h$|^include/linux/crash_dump\\\\.h$|^include/uapi/linux/vmcore\\\\.h$|^kernel/crash_[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/kexec\\\\.h$|^include/uapi/linux/kexec\\\\.h$|^kernel/kexec[^/]*$\"},\n\t\t},\n\t}\n\n\tkeyrings = Subsystem{\n\t\tName: \"keyrings\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^certs/\"},\n\t\t\t{IncludeRegexp: \"^crypto/asymmetric_keys/|^include/crypto/pkcs7\\\\.h$|^include/crypto/public_key\\\\.h$|^include/linux/verification\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/keys/encrypted-type\\\\.h$|^security/keys/encrypted-keys/\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted-type\\\\.h$|^include/keys/trusted_tpm\\\\.h$|^security/keys/trusted-keys/\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted_caam\\\\.h$|^security/keys/trusted-keys/trusted_caam\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/keys/trusted_tee\\\\.h$|^security/keys/trusted-keys/trusted_tee\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/keys/|^include/linux/key-type\\\\.h$|^include/linux/key\\\\.h$|^include/linux/keyctl\\\\.h$|^include/uapi/linux/keyctl\\\\.h$|^security/keys/\"},\n\t\t\t{IncludeRegexp: \"^security/integrity/platform_certs$\"},\n\t\t},\n\t}\n\n\tkgdb = Subsystem{\n\t\tName: \"kgdb\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/misc/kgdbts\\\\.c$|^drivers/tty/serial/kgdboc\\\\.c$|^include/linux/kdb\\\\.h$|^include/linux/kgdb\\\\.h$|^kernel/debug/|^kernel/module/kdb\\\\.c$\"},\n\t\t},\n\t}\n\n\tkunit = Subsystem{\n\t\tName: \"kunit\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/kunit/|^lib/kunit/\"},\n\t\t\t{IncludeRegexp: \"^lib/list-test\\\\.c$\"},\n\t\t},\n\t}\n\n\tkvm = Subsystem{\n\t\tName: \"kvm\",\n\t\tSyscalls: []string{\"syz_kvm_setup_cpu\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/mips/include/asm/kvm[^/]*$|^arch/mips/include/uapi/asm/kvm[^/]*$|^arch/mips/kvm/\"},\n\t\t\t{IncludeRegexp: \"^arch/riscv/include/asm/kvm[^/]*$|^arch/riscv/include/uapi/asm/kvm[^/]*$|^arch/riscv/kvm/\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/include/asm/gmap\\\\.h$|^arch/s390/include/asm/kvm[^/]*$|^arch/s390/include/uapi/asm/kvm[^/]*$|^arch/s390/include/uapi/asm/uvdevice\\\\.h$|^arch/s390/kernel/uv\\\\.c$|^arch/s390/kvm/|^arch/s390/mm/gmap\\\\.c$|^drivers/s390/char/uvdevice\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/include/uapi/asm/virtio-ccw\\\\.h$|^drivers/s390/virtio/\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/kvm/pci[^/]*$|^drivers/vfio/pci/vfio_pci_zdev\\\\.c$|^include/uapi/linux/vfio_zdev\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/kvm[^/]*$|^arch/x86/include/asm/svm\\\\.h$|^arch/x86/include/asm/vmx[^/]*\\\\.h$|^arch/x86/include/uapi/asm/kvm[^/]*$|^arch/x86/include/uapi/asm/svm\\\\.h$|^arch/x86/include/uapi/asm/vmx\\\\.h$|^arch/x86/kvm/|^arch/x86/kvm/[^/]*/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/kvm\\\\.c$|^arch/x86/kernel/kvmclock\\\\.c$|^arch/x86/include/asm/pvclock-abi\\\\.h$|^include/linux/kvm_para\\\\.h$|^include/uapi/linux/kvm_para\\\\.h$|^include/uapi/asm-generic/kvm_para\\\\.h$|^include/asm-generic/kvm_para\\\\.h$|^arch/um/include/asm/kvm_para\\\\.h$|^arch/x86/include/asm/kvm_para\\\\.h$|^arch/x86/include/uapi/asm/kvm_para\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kvm/hyperv\\\\.[^/]*$|^arch/x86/kvm/kvm_onhyperv\\\\.[^/]*$|^arch/x86/kvm/svm/hyperv\\\\.[^/]*$|^arch/x86/kvm/svm/svm_onhyperv\\\\.[^/]*$|^arch/x86/kvm/vmx/hyperv\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kvm/xen\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/cio/vfio_ccw[^/]*$|^include/uapi/linux/vfio_ccw\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/uio/uio_pci_generic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/fsl-mc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/mdev/|^include/linux/mdev\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/pci/[^/]*/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/pci/hisilicon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/pci/mlx5/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/platform/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vfio/|^include/linux/vfio\\\\.h$|^include/linux/vfio_pci_core\\\\.h$|^include/uapi/linux/vfio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/vsock\\\\.c$|^include/linux/virtio_vsock\\\\.h$|^include/uapi/linux/virtio_vsock\\\\.h$|^net/vmw_vsock/virtio_transport\\\\.c$|^net/vmw_vsock/virtio_transport_common\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/|^include/linux/vhost_iotlb\\\\.h$|^include/uapi/linux/vhost\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/kvm[^/]*$|^include/kvm/iodev\\\\.h$|^include/linux/kvm[^/]*$|^include/trace/events/kvm\\\\.h$|^include/uapi/asm-generic/kvm[^/]*$|^include/uapi/linux/kvm[^/]*$|^virt/kvm/\"},\n\t\t\t{IncludeRegexp: \"^virt/lib/\"},\n\t\t},\n\t}\n\n\tkvmriscv = Subsystem{\n\t\tName: \"kvm-riscv\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kvm, &riscv},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/riscv/include/asm/kvm[^/]*$|^arch/riscv/include/uapi/asm/kvm[^/]*$|^arch/riscv/kvm/\"},\n\t\t},\n\t}\n\n\tkvmarm = Subsystem{\n\t\tName: \"kvmarm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm64/include/asm/kvm[^/]*$|^arch/arm64/include/uapi/asm/kvm[^/]*$|^arch/arm64/kvm/|^include/kvm/arm_[^/]*$\"},\n\t\t},\n\t}\n\n\tleds = Subsystem{\n\t\tName: \"leds\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/leds/flash/leds-as3645a\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/leds/leds-mlxcpld\\\\.c$|^drivers/leds/leds-mlxreg\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/leds/|^include/dt-bindings/leds/|^include/linux/leds\\\\.h$\"},\n\t\t},\n\t}\n\n\tlibertas = Subsystem{\n\t\tName: \"libertas\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/marvell/libertas/\"},\n\t\t},\n\t}\n\n\tlima = Subsystem{\n\t\tName: \"lima\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/lima/|^include/uapi/drm/lima_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tlinux1394 = Subsystem{\n\t\tName: \"linux1394\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/firewire/|^include/linux/firewire\\\\.h$|^include/uapi/linux/firewire[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/firewire/\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/sbp/\"},\n\t\t},\n\t}\n\n\tlinuxppc = Subsystem{\n\t\tName: \"linuxppc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/powerpc/boot/ps3[^/]*$|^arch/powerpc/include/asm/lv1call\\\\.h$|^arch/powerpc/include/asm/ps3[^/]*\\\\.h$|^arch/powerpc/platforms/ps3/|^drivers/[^/]*/ps3[^/]*$|^drivers/ps3/|^drivers/rtc/rtc-ps3\\\\.c$|^drivers/usb/host/[^/]*ps3\\\\.c$|^sound/ppc/snd_ps3[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/[^/]*/eeh[^/]*\\\\.h$|^arch/powerpc/kernel/eeh[^/]*\\\\.c$|^arch/powerpc/platforms/[^/]*/eeh[^/]*\\\\.c$|^drivers/pci/pcie/aer\\\\.c$|^drivers/pci/pcie/dpc\\\\.c$|^drivers/pci/pcie/err\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/asm/cell[^/]*\\\\.h$|^arch/powerpc/include/asm/spu[^/]*\\\\.h$|^arch/powerpc/include/uapi/asm/spu[^/]*\\\\.h$|^arch/powerpc/platforms/cell/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/asm/kvm[^/]*$|^arch/powerpc/include/uapi/asm/kvm[^/]*$|^arch/powerpc/kernel/kvm[^/]*$|^arch/powerpc/kvm/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/asm/pnv-ocxl\\\\.h$|^arch/powerpc/platforms/powernv/ocxl\\\\.c$|^drivers/misc/ocxl/|^include/misc/ocxl[^/]*$|^include/uapi/misc/ocxl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/40x/|^arch/powerpc/platforms/44x/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/512x/|^arch/powerpc/platforms/52xx/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/83xx/|^arch/powerpc/platforms/85xx/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/8xx/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/cell/spufs/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/powermac/|^drivers/macintosh/\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/platforms/powernv/pci-cxl\\\\.c$|^drivers/misc/cxl/|^include/misc/cxl[^/]*$|^include/uapi/misc/cxl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/powerpc/|^drivers/[^/]*/[^/]*/[^/]*pasemi[^/]*$|^drivers/[^/]*/[^/]*pasemi[^/]*$|^drivers/char/tpm/tpm_ibmvtpm[^/]*$|^drivers/crypto/nx/|^drivers/crypto/vmx/|^drivers/i2c/busses/i2c-opal\\\\.c$|^drivers/net/ethernet/ibm/ibmveth\\\\.[^/]*$|^drivers/net/ethernet/ibm/ibmvnic\\\\.[^/]*$|^drivers/pci/hotplug/pnv_php\\\\.c$|^drivers/pci/hotplug/rpa[^/]*$|^drivers/rtc/rtc-opal\\\\.c$|^drivers/scsi/ibmvscsi/|^drivers/tty/hvc/hvc_opal\\\\.c$|^drivers/watchdog/wdrtas\\\\.c$|/pmac|powermac|powernv|[^a-z0-9]ps3|pseries\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/ps3vram\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/powernv-op-panel\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/fsldma\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-cpm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/fs_enet/|^include/linux/fs_enet_pd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/ucc_geth[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/toshiba/ps3_gelic_net\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/toshiba/spider_net[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wan/fsl_ucc_hdlc[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*layerscape[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/rpadlpar[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/rpaphp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/fsl/qe/|^include/soc/fsl/qe/\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/fsl/|^include/linux/fsl/|^include/soc/fsl/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/ehv_bytechan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/hvc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/ucc_uart\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/fsl[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/phy/phy-fsl-usb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/aoa/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/fsl/fsl[^/]*$|^sound/soc/fsl/imx[^/]*$|^sound/soc/fsl/mpc8610_hpcd\\\\.c$\"},\n\t\t},\n\t}\n\n\tlinuxpps = Subsystem{\n\t\tName: \"linuxpps\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/pps/|^include/linux/pps[^/]*\\\\.h$|^include/uapi/linux/pps\\\\.h$\"},\n\t\t},\n\t}\n\n\tlivepatching = Subsystem{\n\t\tName: \"live-patching\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/powerpc/include/asm/livepatch\\\\.h$|^include/linux/livepatch\\\\.h$|^kernel/livepatch/|^kernel/module/livepatch\\\\.c$|^lib/livepatch/\"},\n\t\t},\n\t}\n\n\tllvm = Subsystem{\n\t\tName: \"llvm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/cfi\\\\.h$|^kernel/cfi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/compiler-clang\\\\.h$\"},\n\t\t},\n\t}\n\n\tloongarch = Subsystem{\n\t\tName: \"loongarch\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/loongarch/|^drivers/[^/]*/[^/]*loongarch[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/loongson/loongson2_guts\\\\.c$\"},\n\t\t},\n\t}\n\n\tlsm = Subsystem{\n\t\tName: \"lsm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/capability\\\\.h$|^include/uapi/linux/capability\\\\.h$|^kernel/capability\\\\.c$|^security/commoncap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/calipso\\\\.h$|^include/net/cipso_ipv4\\\\.h$|^include/net/netlabel\\\\.h$|^include/uapi/linux/netfilter/xt_CONNSECMARK\\\\.h$|^include/uapi/linux/netfilter/xt_SECMARK\\\\.h$|^net/ipv4/cipso_ipv4\\\\.c$|^net/ipv6/calipso\\\\.c$|^net/netfilter/xt_CONNSECMARK\\\\.c$|^net/netfilter/xt_SECMARK\\\\.c$|^net/netlabel/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/landlock\\\\.h$|^security/landlock/\"},\n\t\t\t{\"^security/\", \"^security/selinux/\"},\n\t\t\t{IncludeRegexp: \"^security/smack/\"},\n\t\t},\n\t}\n\n\tlvs = Subsystem{\n\t\tName: \"lvs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&netfilter},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/net/ip_vs\\\\.h$|^include/uapi/linux/ip_vs\\\\.h$|^net/netfilter/ipvs/\"},\n\t\t},\n\t}\n\n\tm68k = Subsystem{\n\t\tName: \"m68k\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/nubus\\\\.h$|^drivers/nubus/|^include/linux/nubus\\\\.h$|^include/uapi/linux/nubus\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/m68k/[^/]*/[^/]*_no\\\\.[^/]*$|^arch/m68k/68[^/]*/|^arch/m68k/coldfire/|^arch/m68k/include/asm/[^/]*_no\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/m68k/mac/|^drivers/macintosh/adb-iop\\\\.c$|^drivers/macintosh/via-macii\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/m68k/|^drivers/zorro/\"},\n\t\t},\n\t}\n\n\tmalidp = Subsystem{\n\t\tName: \"malidp\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/arm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/arm/display/include/|^drivers/gpu/drm/arm/display/komeda/\"},\n\t\t},\n\t}\n\n\tmedia = Subsystem{\n\t\tName: \"media\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/dma-fence[^/]*$|^drivers/dma-buf/sw_sync\\\\.c$|^drivers/dma-buf/sync_[^/]*$|^include/linux/sync_file\\\\.h$|^include/uapi/linux/sync_file\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/dma-heap\\\\.c$|^drivers/dma-buf/heaps/|^include/linux/dma-heap\\\\.h$|^include/uapi/linux/dma-heap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma-buf/|^include/linux/[^/]*fence\\\\.h$|^include/linux/dma-buf\\\\.h$|^include/linux/dma-resv\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/i2c/ch7322\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/cec-gpio/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/meson/ao-cec-g12a\\\\.c$|^drivers/media/cec/platform/meson/ao-cec\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/s5p/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/tegra/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/usb/pulse8/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/usb/rainshadow/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/|^drivers/media/rc/keymaps/rc-cec\\\\.c$|^include/media/cec-notifier\\\\.h$|^include/media/cec\\\\.h$|^include/uapi/linux/cec-funcs\\\\.h$|^include/uapi/linux/cec\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/common/cx2341x[^/]*$|^include/media/drv-intf/cx2341x\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/common/cypress_firmware[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/common/saa7146/|^drivers/media/pci/saa7146/|^include/media/drv-intf/saa7146[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/common/siano/|^drivers/media/mmc/siano/|^drivers/media/usb/siano/|^drivers/media/usb/siano/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/common/videobuf2/|^include/media/videobuf2-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/a8293[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/af9013[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/af9033[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/ascot2e[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/cx24120[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/cxd2099[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/cxd2820r[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/cxd2841er[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/cxd2880/|^drivers/media/spi/cxd2880[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/ec100[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/helene[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/horus3a[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/ix2505v[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/lg2160\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/lgdt3305\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/lnbh25[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/m88ds3103[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/m88rs2000[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/mn88472[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/mn88473[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/mxl5xx[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/rtl2830[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/rtl2832[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/rtl2832_sdr[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/si2165[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/si2168[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/sp2[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/stv0910[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/stv6111[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/tc90522[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/tda10071[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/dvb-frontends/zd1301_demod[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/firewire/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ad5820\\\\.c$|^drivers/media/i2c/et8ek8$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ad9389b[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adp1653\\\\.c$|^include/media/i2c/adp1653\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adv7180\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adv748x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adv7511[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adv7604[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/adv7842[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ak7375\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/aptina-pll\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ar0521\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ccs-pll\\\\.c$|^drivers/media/i2c/ccs-pll\\\\.h$|^drivers/media/i2c/ccs/|^include/uapi/linux/ccs\\\\.h$|^include/uapi/linux/smiapp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/cs3308\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/dw9714\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/dw9768\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/dw9807-vcm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/hi556\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/hi846\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/hi847\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx208\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx214\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx219\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx258\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx274\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx290\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx296\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx319\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx334\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx335\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx355\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx412\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/imx415\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/isl7998x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/m5mols/|^include/media/i2c/m5mols\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/max2175[^/]*$|^include/uapi/linux/max2175\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/max9271\\\\.c$|^drivers/media/i2c/max9271\\\\.h$|^drivers/media/i2c/rdacm20\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/max9271\\\\.c$|^drivers/media/i2c/max9271\\\\.h$|^drivers/media/i2c/rdacm21\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/max9286\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9m032\\\\.c$|^include/media/i2c/mt9m032\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9p031\\\\.c$|^include/media/i2c/mt9p031\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9t001\\\\.c$|^include/media/i2c/mt9t001\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9t112\\\\.c$|^include/media/i2c/mt9t112\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9v032\\\\.c$|^include/media/i2c/mt9v032\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/mt9v111\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/og01a1b\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov02a10\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov08d10\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov08x40\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov13858\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov13b10\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov2659\\\\.c$|^include/media/i2c/ov2659\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov2680\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov2685\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov2740\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5640\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5647\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5647\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5670\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5675\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5693\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov5695\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov7670\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov772x\\\\.c$|^include/media/i2c/ov772x\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov7740\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov8856\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov8858\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov9282\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov9640\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov9650\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/ov9734\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/rj54n1cb0c\\\\.c$|^include/media/i2c/rj54n1cb0c\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/s5c73m3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/s5k5baf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/saa6588[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/st-mipid02\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/st-vgxy61\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tc358743[^/]*$|^include/media/i2c/tc358743\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tda1997x\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tda9840[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tea6415c[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tea6420[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/tw9910\\\\.c$|^include/media/i2c/tw9910\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/i2c/video-i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/mc/|^include/media/media-[^/]*\\\\.h$|^include/uapi/linux/media\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/bt8xx/bttv[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/cobalt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/cx18/|^include/uapi/linux/ivtv[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/cx88/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/ddbridge/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/dt3155/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/intel/ipu3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/ivtv/|^include/uapi/linux/ivtv[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/netup_unidvb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/pt1/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/pt3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/saa7134/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/solo6x10/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/tw5864/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/tw68/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/tw686x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/zoran/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/allegro-dvt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/amlogic/meson-ge2d/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/amphion/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/atmel/atmel-isi\\\\.c$|^drivers/media/platform/atmel/atmel-isi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/cadence/cdns-csi2[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/chips-media/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/marvell/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/microchip/microchip-csi2dc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nvidia/tegra-vde/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nxp/dw100/|^include/uapi/linux/dw100\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nxp/imx-jpeg$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nxp/imx-mipi-csis\\\\.c$|^drivers/media/platform/nxp/imx7-media-csi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nxp/imx-pxp\\\\.\\\\[ch\\\\]$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/qcom/camss/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/qcom/venus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar-fcp\\\\.c$|^include/media/rcar-fcp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar-isp\\\\.c$|^drivers/media/platform/renesas/rcar-vin/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_drif\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_fdp1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_jpu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/renesas-ceu\\\\.c$|^include/media/drv-intf/renesas-ceu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/sh_vou\\\\.c$|^include/media/drv-intf/sh_vou\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/vsp1/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/rockchip/rga/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/rockchip/rkisp1$|^include/uapi/linux/rkisp1-config\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/exynos4-is/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s3c-camif/|^include/media/drv-intf/s3c_camif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-g2d/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-jpeg/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s5p-mfc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/st/sti/bdisp$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/st/sti/delta$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/st/sti/hva$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/st/stm32/stm32-dcmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/sunxi/sun4i-csi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/sunxi/sun6i-csi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/sunxi/sun6i-mipi-csi2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/sunxi/sun8i-di/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/sunxi/sun8i-rotate/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/ti/am437x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/ti/cal/|^drivers/media/platform/ti/vpe/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/ti/davinci/|^include/media/davinci/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/ti/omap3isp/|^drivers/staging/media/omap4iss/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/verisilicon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/video-mux\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/xilinx/|^include/uapi/linux/xilinx-v4l2-controls\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/dsbr100\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-aimslab[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-aztech[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-cadet[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-gemtek[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-isa[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-keene[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-ma901\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-maxiradio[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-miropcm20[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-mr800\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-raremono\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-shark2\\\\.c$|^drivers/media/radio/radio-tea5777\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/radio-shark\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/si470x/radio-si470x-common\\\\.c$|^drivers/media/radio/si470x/radio-si470x-usb\\\\.c$|^drivers/media/radio/si470x/radio-si470x\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/si470x/radio-si470x-i2c\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/si4713/radio-platform-si4713\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/si4713/radio-usb-si4713\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/radio/si4713/si4713\\\\..$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/gpio-ir-tx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/igorplugusb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/iguanair\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/imon\\\\.c$|^drivers/media/rc/imon_raw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/pwm-ir-tx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/serial_ir\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/ttusbir\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/rc/|^include/media/rc-map\\\\.h$|^include/media/rc-core\\\\.h$|^include/uapi/linux/lirc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/spi/gs1662\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/test-drivers/vicodec/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/test-drivers/vidtv/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/test-drivers/vimc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/test-drivers/visl$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/test-drivers/vivid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/e4000[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/fc0011\\\\.c$|^drivers/media/tuners/fc0011\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/fc2580[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/it913x[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/msi001[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/mxl301rf[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/mxl5007t\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/qm1d1b0004[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/qm1d1c0042[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/qt1010[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/si2157[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda18212[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda18218[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda18250[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda18271[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda8290\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tda8290\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tea5761\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tea5767\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/tua9001[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/tuners/xc2028\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/airspy/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/af9015[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/af9035[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/anysee[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/au6610[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/az6007\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/ce6230[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/dvb_usb[^/]*$|^drivers/media/usb/dvb-usb-v2/usb_urb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/ec168[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/gl861[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/lmedm04[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/mxl111sf[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/rtl28xxu[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb-v2/zd1301[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/dvb-usb/cxusb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/em28xx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/go7007/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/finepix\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/gl860/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/m5602/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/pac207\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/sn9c20x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/gspca/t613\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/hackrf/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/hdpvr/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/msi2500/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/pvrusb2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/pwc/|^include/trace/events/pwc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/stk1160/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/uvc/|^include/uapi/linux/uvcvideo\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/|^drivers/staging/media/|^include/dt-bindings/media/|^include/linux/platform_data/media/|^include/media/|^include/uapi/linux/dvb/|^include/uapi/linux/ivtv[^/]*$|^include/uapi/linux/media\\\\.h$|^include/uapi/linux/uvcvideo\\\\.h$|^include/uapi/linux/v4l2-[^/]*$|^include/uapi/linux/videodev2\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/atomisp/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/deprecated/atmel/atmel-isc[^/]*$|^drivers/staging/media/deprecated/atmel/atmel-sama[^/]*-isc[^/]*$|^drivers/media/platform/microchip/microchip-isc[^/]*$|^drivers/media/platform/microchip/microchip-sama[^/]*-isc[^/]*$|^include/linux/atmel-isc-media\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/imx/|^include/linux/imx-media\\\\.h$|^include/media/imx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/ipu3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/max96712/max96712\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/meson/vdec/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/rkvdec/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/sunxi/cedrus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/sunxi/sun6i-isp/|^drivers/staging/media/sunxi/sun6i-isp/uapi/sun6i-isp-config\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/tegra-video/\"},\n\t\t},\n\t}\n\n\tmediatek = Subsystem{\n\t\tName: \"mediatek\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/mt2[^/]*$|^arch/arm/boot/dts/mt6[^/]*$|^arch/arm/boot/dts/mt7[^/]*$|^arch/arm/boot/dts/mt8[^/]*$|^arch/arm/mach-mediatek/|^arch/arm64/boot/dts/mediatek/|^drivers/soc/mediatek/|mtk|mt[2678]\"},\n\t\t\t{IncludeRegexp: \"^drivers/bluetooth/btmtkuart\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dma/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/mediatek/|^drivers/phy/mediatek/phy-mtk-dp\\\\.c$|^drivers/phy/mediatek/phy-mtk-hdmi[^/]*$|^drivers/phy/mediatek/phy-mtk-mipi[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/mtk_iommu[^/]*$|^include/dt-bindings/memory/mt[^/]*-port\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/mtk-smi\\\\.c$|^include/soc/mediatek/smi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*mediatek[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-mt2712\\\\.c$|^drivers/rtc/rtc-mt6397\\\\.c$|^drivers/rtc/rtc-mt7622\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-mediatek[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/xhci-mtk[^/]*$|^drivers/usb/mtu3/\"},\n\t\t},\n\t}\n\n\tmegaraid = Subsystem{\n\t\tName: \"megaraid\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&scsi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/scsi/megaraid\\\\.[^/]*$|^drivers/scsi/megaraid/\"},\n\t\t},\n\t}\n\n\tmhi = Subsystem{\n\t\tName: \"mhi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&armmsm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/bus/mhi/|^include/linux/mhi\\\\.h$\"},\n\t\t},\n\t}\n\n\tmips = Subsystem{\n\t\tName: \"mips\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/mips/bcm47xx/|^arch/mips/include/asm/mach-bcm47xx/\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/bmips/|^arch/mips/boot/dts/brcm/bcm[^/]*\\\\.dts[^/]*$|^arch/mips/include/asm/mach-bmips/|^arch/mips/kernel/[^/]*bmips[^/]*$|^drivers/soc/bcm/bcm63xx$|^drivers/irqchip/irq-bcm63[^/]*$|^drivers/irqchip/irq-bcm7[^/]*$|^drivers/irqchip/irq-brcmstb[^/]*$|^include/linux/bcm963xx_nvram\\\\.h$|^include/linux/bcm963xx_tag\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/img/boston\\\\.dts$|^arch/mips/configs/generic/board-boston\\\\.config$|^drivers/clk/imgtec/clk-boston\\\\.c$|^include/dt-bindings/clock/boston-clock\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/img/pistachio[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/ingenic/|^arch/mips/generic/board-ingenic\\\\.c$|^arch/mips/include/asm/mach-ingenic/|^arch/mips/ingenic/Kconfig$|^drivers/clk/ingenic/|^drivers/dma/dma-jz4780\\\\.c$|^drivers/gpu/drm/ingenic/|^drivers/i2c/busses/i2c-jz4780\\\\.c$|^drivers/iio/adc/ingenic-adc\\\\.c$|^drivers/irqchip/irq-ingenic\\\\.c$|^drivers/memory/jz4780-nemc\\\\.c$|^drivers/mmc/host/jz4740_mmc\\\\.c$|^drivers/mtd/nand/raw/ingenic/|^drivers/pinctrl/pinctrl-ingenic\\\\.c$|^drivers/power/supply/ingenic-battery\\\\.c$|^drivers/pwm/pwm-jz4740\\\\.c$|^drivers/remoteproc/ingenic_rproc\\\\.c$|^drivers/rtc/rtc-jz4740\\\\.c$|^drivers/tty/serial/8250/8250_ingenic\\\\.c$|^drivers/usb/musb/jz4740\\\\.c$|^drivers/watchdog/jz4740_wdt\\\\.c$|^include/dt-bindings/iio/adc/ingenic,adc\\\\.h$|^include/linux/mfd/ingenic-tcu\\\\.h$|^sound/soc/codecs/jz47[^/]*$|^sound/soc/jz4740/\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/mscc/|^arch/mips/configs/generic/board-ocelot\\\\.config$|^arch/mips/generic/board-ocelot\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/ralink/mt7621[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/ralink/omega2p\\\\.dts$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/boot/dts/ralink/vocore2\\\\.dts$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/configs/generic/board-ranchu\\\\.config$|^arch/mips/generic/board-ranchu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/dec/|^arch/mips/include/asm/dec/|^arch/mips/include/asm/mach-dec/\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/generic/|^arch/mips/tools/generic-board-config\\\\.sh$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/include/asm/kvm[^/]*$|^arch/mips/include/uapi/asm/kvm[^/]*$|^arch/mips/kvm/\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/include/asm/mach-loongson2ef/|^arch/mips/loongson2ef/|^drivers/cpufreq/loongson2_cpufreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/include/asm/mach-loongson32/|^arch/mips/loongson32/|^drivers/[^/]*/[^/]*/[^/]*loongson1[^/]*$|^drivers/[^/]*/[^/]*loongson1[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/include/asm/mach-loongson64/|^arch/mips/loongson64/|^drivers/irqchip/irq-loongson[^/]*$|^drivers/platform/mips/cpu_hwmon\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/lantiq$|^drivers/soc/lantiq$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/math-emu/dp_rint\\\\.c$|^arch/mips/math-emu/sp_rint\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/ralink$\"},\n\t\t\t{IncludeRegexp: \"^arch/mips/|^drivers/platform/mips/|^include/dt-bindings/mips/\"},\n\t\t\t{IncludeRegexp: \"^drivers/bus/mips_cdmm\\\\.c$|^drivers/clocksource/mips-gic-timer\\\\.c$|^drivers/cpuidle/cpuidle-cps\\\\.c$|^drivers/irqchip/irq-mips-cpu\\\\.c$|^drivers/irqchip/irq-mips-gic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/edac/octeon_edac[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/broadcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/ingenic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/sgi/ioc3-eth\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/ralink/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tc/|^include/linux/tc\\\\.h$\"},\n\t\t},\n\t}\n\n\tmjpeg = Subsystem{\n\t\tName: \"mjpeg\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&media},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/media/pci/zoran/\"},\n\t\t},\n\t}\n\n\tmm = Subsystem{\n\t\tName: \"mm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/percpu\\\\.h$|^include/linux/percpu[^/]*\\\\.h$|^lib/percpu[^/]*\\\\.c$|^mm/percpu[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/tlb\\\\.h$|^include/asm-generic/tlb\\\\.h$|^mm/mmu_gather\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/memory\\\\.c$|^include/linux/memory_hotplug\\\\.h$|^mm/memory_hotplug\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/[^/]*binfmt_[^/]*\\\\.c$|^fs/exec\\\\.c$|^include/linux/binfmts\\\\.h$|^include/linux/elf\\\\.h$|^include/uapi/linux/binfmts\\\\.h$|^include/uapi/linux/elf\\\\.h$|asm/elf.h|binfmt\"},\n\t\t\t{IncludeRegexp: \"^fs/hugetlbfs/|^include/linux/hugetlb\\\\.h$|^mm/hugetlb\\\\.c$|^mm/hugetlb_vmemmap\\\\.c$|^mm/hugetlb_vmemmap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/damon\\\\.h$|^include/trace/events/damon\\\\.h$|^mm/damon/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/gfp\\\\.h$|^include/linux/gfp_types\\\\.h$|^include/linux/memory_hotplug\\\\.h$|^include/linux/mm\\\\.h$|^include/linux/mmzone\\\\.h$|^include/linux/pagewalk\\\\.h$|^mm/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/hmm[^/]*$|^lib/test_hmm[^/]*$|^mm/hmm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/maple_tree\\\\.h$|^include/trace/events/maple_tree\\\\.h$|^lib/maple_tree\\\\.c$|^lib/test_maple_tree\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/memblock\\\\.h$|^mm/memblock\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/page_table_check\\\\.h$|^mm/page_table_check\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/shmem_fs\\\\.h$|^mm/shmem\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/sl.b[^/]*\\\\.h$|^mm/sl.b[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/vmalloc\\\\.h$|^mm/vmalloc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/zpool\\\\.h$|^mm/zpool\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/zsmalloc\\\\.h$|^mm/zsmalloc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/hwpoison-inject\\\\.c$|^mm/memory-failure\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/memcontrol\\\\.c$|^mm/swap_cgroup\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/z3fold\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/zbud\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^mm/zswap\\\\.c$\"},\n\t\t},\n\t}\n\n\tmmc = Subsystem{\n\t\tName: \"mmc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/memstick/|^include/linux/memstick\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/cqhci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/dw_mmc[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/omap_hsmmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/renesas_sdhi[^/]*$|^drivers/mmc/host/tmio_mmc[^/]*$|^include/linux/mfd/tmio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-brcmstb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-esdhc-imx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-esdhc-mcf\\\\.c$|^include/linux/platform_data/mmc-esdhc-mcf\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-of-aspeed[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-of-at91\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-omap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-pci-dwc-mshc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-s3c[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-spear\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-xenon[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/vub300\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/|^include/linux/mmc/|^include/uapi/linux/mmc/\"},\n\t\t},\n\t}\n\n\tmodules = Subsystem{\n\t\tName: \"modules\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/kmod\\\\.h$|^kernel/kmod\\\\.c$|^lib/test_kmod\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/module\\\\.h$|^kernel/module/\"},\n\t\t},\n\t}\n\n\tmpi3 = Subsystem{\n\t\tName: \"mpi3\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&scsi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/scsi/mpi3mr/\"},\n\t\t},\n\t}\n\n\tmptfusion = Subsystem{\n\t\tName: \"mpt-fusion\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&scsi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/message/fusion/|^drivers/scsi/mpt3sas/\"},\n\t\t},\n\t}\n\n\tmptcp = Subsystem{\n\t\tName: \"mptcp\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/net/mptcp\\\\.h$|^include/trace/events/mptcp\\\\.h$|^include/uapi/linux/mptcp\\\\.h$|^net/mptcp/\"},\n\t\t},\n\t}\n\n\tmtd = Subsystem{\n\t\tName: \"mtd\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/mtd/devices/block2mtd\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/devices/docg3[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/devices/phram\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/hyperbus/|^include/linux/mtd/hyperbus\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/onenand/|^include/linux/mtd/onenand[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/arasan-nand-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/atmel/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/brcmnand/|^include/linux/platform_data/brcmnand\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/cadence-nand-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/denali[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/gpmi-nand/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/ingenic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/marvell_nand\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/meson_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/mtk_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/pl35x-nand-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/qcom_nandc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/renesas-nand-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/vf610_nfc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/|^include/linux/mtd/[^/]*nand[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/spi-nor/|^include/linux/mtd/spi-nor\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/ubi/|^include/linux/mtd/ubi\\\\.h$|^include/uapi/mtd/ubi-user\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/|^include/linux/mtd/|^include/uapi/mtd/\"},\n\t\t\t{IncludeRegexp: \"^fs/jffs2/|^include/uapi/linux/jffs2\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/ubifs/\"},\n\t\t},\n\t}\n\n\tnbd = Subsystem{\n\t\tName: \"nbd\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&block},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/block/nbd\\\\.c$|^include/trace/events/nbd\\\\.h$|^include/uapi/linux/nbd\\\\.h$\"},\n\t\t},\n\t}\n\n\tnet = Subsystem{\n\t\tName: \"net\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/amd/amd-seattle-xgbe[^/]*\\\\.dtsi$|^drivers/net/ethernet/amd/xgbe/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/net/|^include/linux/ip\\\\.h$|^include/linux/ipv6[^/]*$|^include/net/fib[^/]*$|^include/net/ip[^/]*$|^include/net/route\\\\.h$|^net/ipv4/|^net/ipv6/\"},\n\t\t\t{IncludeRegexp: \"^drivers/atm/|^include/linux/atm[^/]*$|^include/uapi/linux/atm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/connector/|^drivers/net/|^include/dt-bindings/net/|^include/linux/etherdevice\\\\.h$|^include/linux/fcdevice\\\\.h$|^include/linux/fddidevice\\\\.h$|^include/linux/hippidevice\\\\.h$|^include/linux/if_[^/]*$|^include/linux/inetdevice\\\\.h$|^include/linux/netdevice\\\\.h$|^include/uapi/linux/if_[^/]*$|^include/uapi/linux/netdevice\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/firmware/broadcom/tee_bnxt_fw\\\\.c$|^drivers/net/ethernet/broadcom/bnxt/|^include/linux/firmware/broadcom/tee_bnxt_fw\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/isdn/Kconfig$|^drivers/isdn/hardware/|^drivers/isdn/mISDN/\"},\n\t\t\t{IncludeRegexp: \"^drivers/isdn/capi/|^include/linux/isdn/|^include/uapi/linux/isdn/|^net/bluetooth/cmtp/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/amt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/appletalk/|^include/linux/atalk\\\\.h$|^include/uapi/linux/atalk\\\\.h$|^net/appletalk/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/arcnet/|^include/uapi/linux/if_arcnet\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/bonding/|^include/net/bond[^/]*$|^include/uapi/linux/if_bonding\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/caif/|^include/net/caif/|^include/uapi/linux/caif/|^net/caif/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/b53/|^drivers/net/dsa/bcm_sf2[^/]*$|^include/linux/dsa/brcm\\\\.h$|^include/linux/platform_data/b53\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/hirschmann/|^include/linux/platform_data/hirschmann-hellcreek\\\\.h$|^net/dsa/tag_hellcreek\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/lantiq_gswip\\\\.c$|^drivers/net/dsa/lantiq_pce\\\\.h$|^drivers/net/ethernet/lantiq_xrx200\\\\.c$|^net/dsa/tag_gswip\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/microchip/|^include/linux/dsa/ksz_common\\\\.h$|^include/linux/platform_data/microchip-ksz\\\\.h$|^net/dsa/tag_ksz\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/mt7530\\\\.[^/]*$|^net/dsa/tag_mtk\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/mv88e6xxx/|^include/linux/dsa/mv88e6xxx\\\\.h$|^include/linux/platform_data/mv88e6xxx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/ocelot/|^drivers/net/ethernet/mscc/|^include/soc/mscc/ocelot[^/]*$|^net/dsa/tag_ocelot\\\\.c$|^net/dsa/tag_ocelot_8021q\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/rzn1_a5psw[^/]*$|^drivers/net/pcs/pcs-rzn1-miic\\\\.c$|^include/dt-bindings/net/pcs-rzn1-miic\\\\.h$|^include/linux/pcs-rzn1-miic\\\\.h$|^net/dsa/tag_rzn1_a5psw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/xrs700x/|^net/dsa/tag_xrs700x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/3com/3c59x\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/3com/typhoon[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/8390/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/aeroflex/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/altera/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/amazon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/amd/pcnet32\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/aquantia/atlantic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/aquantia/atlantic/aq_ptp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/atheros/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/b44\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/bcm4908_enet\\\\.[^/]*$|^drivers/net/ethernet/broadcom/unimac\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/bcmsysport\\\\.[^/]*$|^drivers/net/ethernet/broadcom/unimac\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/bgmac[^/]*$|^drivers/net/ethernet/broadcom/unimac\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/bnx2\\\\.[^/]*$|^drivers/net/ethernet/broadcom/bnx2_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/bnx2x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/genet/|^drivers/net/ethernet/broadcom/unimac\\\\.h$|^drivers/net/mdio/mdio-bcm-unimac\\\\.c$|^include/linux/platform_data/bcmgenet\\\\.h$|^include/linux/platform_data/mdio-bcm-unimac\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/broadcom/tg3\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/brocade/bna/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/cavium/liquidio/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/chelsio/cxgb3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/chelsio/cxgb4/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/chelsio/cxgb4vf/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/chelsio/inline_crypto/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/cirrus/ep93xx_eth\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/dec/tulip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/dec/tulip/dmfe\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/dlink/sundance\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ec_bhf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/emulex/benet/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/dpaa$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/dpaa2/Kconfig$|^drivers/net/ethernet/freescale/dpaa2/dpaa2-eth[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dpaa2-mac[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dpaa2-xsk[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dpkg\\\\.h$|^drivers/net/ethernet/freescale/dpaa2/dpmac[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dpni[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/dpaa2/dpaa2-ptp[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dprtc[^/]*$|^drivers/net/ethernet/freescale/enetc/enetc_ptp\\\\.c$|^drivers/ptp/ptp_qoriq\\\\.c$|^drivers/ptp/ptp_qoriq_debugfs\\\\.c$|^include/linux/fsl/ptp_qoriq\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/dpaa2/dpaa2-switch[^/]*$|^drivers/net/ethernet/freescale/dpaa2/dpsw[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/enetc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/fec\\\\.h$|^drivers/net/ethernet/freescale/fec_main\\\\.c$|^drivers/net/ethernet/freescale/fec_ptp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/fman$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/fs_enet/|^include/linux/fs_enet_pd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/gianfar[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/freescale/ucc_geth[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/fungible/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/google$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/hisilicon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/hisilicon/hns3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/huawei/hinic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ibm/ehea/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ibm/ibmveth\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ibm/ibmvnic\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/jme\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/mv643xx_eth\\\\.[^/]*$|^include/linux/mv643xx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/mvneta\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/mvpp2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/octeon_ep$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/octeontx2/af/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/octeontx2/nic/|^include/linux/soc/marvell/octeontx2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/marvell/sk[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mediatek/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx4/en_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx4/|^include/linux/mlx4/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx5/core/en_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx5/core/en_accel/|^drivers/net/ethernet/mellanox/mlx5/core/fpga/|^include/linux/mlx5/mlx5_ifc_fpga\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx5/core/|^include/linux/mlx5/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlxfw/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlxsw/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/microchip/lan743x_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/microchip/lan966x/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/myricom/myri10ge/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/natsemi/sonic\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/neterion/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/nvidia/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/pensando/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qlogic/netxen/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qlogic/qed/|^drivers/net/ethernet/qlogic/qede/|^include/linux/qed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qlogic/qla3xxx\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qlogic/qlcnic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qualcomm/emac/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/qualcomm/rmnet/|^include/linux/if_rmnet\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/rdc/r6040\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/realtek/r8169[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/renesas/|^include/linux/sh_eth\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/rocker/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/samsung/sxgbe/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/sfc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/sis/sis190\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/sis/sis900\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/smsc/smsc911x\\\\.[^/]*$|^include/linux/smsc911x\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/smsc/smsc9420\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/socionext/netsec\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/socionext/sni_ave\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/stmicro/stmmac/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/stmicro/stmmac/dwmac-qcom-ethqos\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/sunplus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/synopsys/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/tehuti/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ti/cpmac\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ti/cpsw[^/]*$|^drivers/net/ethernet/ti/davinci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/toshiba/ps3_gelic_net\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/toshiba/spider_net[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/via/via-velocity\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/wangxun/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ipa/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/mctp/|^include/net/mctp\\\\.h$|^include/net/mctpdevice\\\\.h$|^include/net/netns/mctp\\\\.h$|^net/mctp/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/mdio/mdio-mvusb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/mdio/|^drivers/net/mdio/acpi_mdio\\\\.c$|^drivers/net/mdio/fwnode_mdio\\\\.c$|^drivers/net/mdio/of_mdio\\\\.c$|^drivers/net/pcs/|^drivers/net/phy/|^include/dt-bindings/net/qca-ar803x\\\\.h$|^include/linux/linkmode\\\\.h$|^include/linux/[^/]*mdio[^/]*\\\\.h$|^include/linux/mdio/[^/]*\\\\.h$|^include/linux/mii\\\\.h$|^include/linux/of_net\\\\.h$|^include/linux/phy\\\\.h$|^include/linux/phy_fixed\\\\.h$|^include/linux/platform_data/mdio-bcm-unimac\\\\.h$|^include/linux/platform_data/mdio-gpio\\\\.h$|^include/trace/events/mdio\\\\.h$|^include/uapi/linux/mdio\\\\.h$|^include/uapi/linux/mii\\\\.h$|^net/core/of_net\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/net_failover\\\\.c$|^include/net/net_failover\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/pcs/pcs-altera-tse\\\\.c$|^include/linux/pcs-altera-tse\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/pcs/pcs-lynx\\\\.c$|^include/linux/pcs-lynx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/pcs/pcs-xpcs\\\\.c$|^drivers/net/pcs/pcs-xpcs\\\\.h$|^include/linux/pcs/pcs-xpcs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/adin\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/bcm[^/]*\\\\.\\\\[ch\\\\]$|^drivers/net/phy/broadcom\\\\.c$|^include/linux/brcmphy\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/dp83640[^/]*$|^drivers/ptp/|^include/linux/ptp_cl[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/marvell10g\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/mdio-open-alliance\\\\.h$|^net/ethtool/plca\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/microchip_t1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/motorcomm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/mxl-gpy\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/ncn[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/nxp-c45-tja11xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/phy/phylink\\\\.c$|^drivers/net/phy/sfp[^/]*$|^include/linux/mdio/mdio-i2c\\\\.h$|^include/linux/phylink\\\\.h$|^include/linux/sfp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ppp/pptp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/team/|^include/linux/if_team\\\\.h$|^include/uapi/linux/if_team\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/thunderbolt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/dm9601\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/lan78xx\\\\.[^/]*$|^include/dt-bindings/net/microchip-lan78xx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/pegasus\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/qmi_wwan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/rtl8150\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/smsc75xx\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/smsc95xx\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/usbnet\\\\.c$|^include/linux/usb/usbnet\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/vmxnet3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/vrf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/vsockmon\\\\.c$|^include/net/af_vsock\\\\.h$|^include/uapi/linux/vm_sockets\\\\.h$|^include/uapi/linux/vm_sockets_diag\\\\.h$|^include/uapi/linux/vsockmon\\\\.h$|^net/vmw_vsock/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wan/fsl_ucc_hdlc[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireguard/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/iosm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/qcom_bam_dmux\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/rpmsg_wwan_ctrl\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/t7xx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/|^include/linux/wwan\\\\.h$|^include/uapi/linux/wwan\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/xen-netback/\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/virtual_ncidev\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/|^include/linux/platform_data/nfcmrvl\\\\.h$|^include/net/nfc/|^include/uapi/linux/nfc\\\\.h$|^net/nfc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/freescale/phy-fsl-lynx-28g\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ptp/ptp_ocp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ptp/ptp_vclock\\\\.c$|^net/ethtool/phc_vclocks\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ptp/ptp_vmw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/net/\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/net/[^/]*iucv[^/]*$|^include/net/iucv/|^net/iucv/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/qlge/\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/vsock\\\\.c$|^include/linux/virtio_vsock\\\\.h$|^include/uapi/linux/virtio_vsock\\\\.h$|^net/vmw_vsock/virtio_transport\\\\.c$|^net/vmw_vsock/virtio_transport_common\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/|^include/linux/vhost_iotlb\\\\.h$|^include/uapi/linux/vhost\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/in\\\\.h$|^include/linux/net\\\\.h$|^include/linux/netdevice\\\\.h$|^include/net/|^include/uapi/linux/in\\\\.h$|^include/uapi/linux/net\\\\.h$|^include/uapi/linux/net_namespace\\\\.h$|^include/uapi/linux/netdevice\\\\.h$|^lib/net_utils\\\\.c$|^lib/random32\\\\.c$|^net/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/llc\\\\.h$|^include/net/llc[^/]*$|^include/uapi/linux/llc\\\\.h$|^net/llc/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/netfilter_bridge/|^net/bridge/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/objagg\\\\.h$|^lib/objagg\\\\.c$|^lib/test_objagg\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/packing\\\\.h$|^lib/packing\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/parman\\\\.h$|^lib/parman\\\\.c$|^lib/test_parman\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/rhashtable-types\\\\.h$|^include/linux/rhashtable\\\\.h$|^lib/rhashtable\\\\.c$|^lib/test_rhashtable\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/skmsg\\\\.h$|^net/core/skmsg\\\\.c$|^net/core/sock_map\\\\.c$|^net/ipv4/tcp_bpf\\\\.c$|^net/ipv4/udp_bpf\\\\.c$|^net/unix/unix_bpf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/tcp\\\\.h$|^include/net/tcp\\\\.h$|^include/trace/events/tcp\\\\.h$|^include/uapi/linux/tcp\\\\.h$|^net/ipv4/syncookies\\\\.c$|^net/ipv4/tcp[^/]*\\\\.c$|^net/ipv6/syncookies\\\\.c$|^net/ipv6/tcp[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/calipso\\\\.h$|^include/net/cipso_ipv4\\\\.h$|^include/net/netlabel\\\\.h$|^include/uapi/linux/netfilter/xt_CONNSECMARK\\\\.h$|^include/uapi/linux/netfilter/xt_SECMARK\\\\.h$|^net/ipv4/cipso_ipv4\\\\.c$|^net/ipv6/calipso\\\\.c$|^net/netfilter/xt_CONNSECMARK\\\\.c$|^net/netfilter/xt_SECMARK\\\\.c$|^net/netlabel/\"},\n\t\t\t{IncludeRegexp: \"^include/net/devlink\\\\.h$|^include/uapi/linux/devlink\\\\.h$|^net/devlink/\"},\n\t\t\t{IncludeRegexp: \"^include/net/failover\\\\.h$|^net/core/failover\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/gre\\\\.h$|^net/ipv4/gre_demux\\\\.c$|^net/ipv4/gre_offload\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/ip_vs\\\\.h$|^include/uapi/linux/ip_vs\\\\.h$|^net/netfilter/ipvs/\"},\n\t\t\t{IncludeRegexp: \"^include/net/l3mdev\\\\.h$|^net/l3mdev$\"},\n\t\t\t{IncludeRegexp: \"^include/net/mptcp\\\\.h$|^include/trace/events/mptcp\\\\.h$|^include/uapi/linux/mptcp\\\\.h$|^net/mptcp/\"},\n\t\t\t{IncludeRegexp: \"^include/net/netns/nexthop\\\\.h$|^include/net/nexthop\\\\.h$|^include/uapi/linux/nexthop\\\\.h$|^net/ipv4/nexthop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/page_pool\\\\.h$|^include/trace/events/page_pool\\\\.h$|^net/core/page_pool\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/net/pkt_cls\\\\.h$|^include/net/pkt_sched\\\\.h$|^include/net/tc_act/|^include/uapi/linux/pkt_cls\\\\.h$|^include/uapi/linux/pkt_sched\\\\.h$|^include/uapi/linux/tc_act/|^include/uapi/linux/tc_ematch/|^net/sched/\"},\n\t\t\t{IncludeRegexp: \"^include/net/switchdev\\\\.h$|^net/switchdev/\"},\n\t\t\t{IncludeRegexp: \"^include/net/tls\\\\.h$|^include/uapi/linux/tls\\\\.h$|^net/tls/\"},\n\t\t\t{IncludeRegexp: \"^include/net/xdp\\\\.h$|^include/net/xdp_priv\\\\.h$|^include/trace/events/xdp\\\\.h$|^kernel/bpf/cpumap\\\\.c$|^kernel/bpf/devmap\\\\.c$|^net/core/xdp\\\\.c$|^drivers/net/ethernet/[^/]*/[^/]*/[^/]*/[^/]*/[^/]*xdp[^/]*$|^drivers/net/ethernet/[^/]*/[^/]*/[^/]*xdp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^include/net/xdp_sock[^/]*$|^include/net/xsk_buff_pool\\\\.h$|^include/uapi/linux/if_xdp\\\\.h$|^include/uapi/linux/xdp_diag\\\\.h$|^include/net/netns/xdp\\\\.h$|^net/xdp/\"},\n\t\t\t{IncludeRegexp: \"^include/net/xfrm\\\\.h$|^include/uapi/linux/xfrm\\\\.h$|^net/ipv4/ah4\\\\.c$|^net/ipv4/esp4[^/]*$|^net/ipv4/ip_vti\\\\.c$|^net/ipv4/ipcomp\\\\.c$|^net/ipv4/xfrm[^/]*$|^net/ipv6/ah6\\\\.c$|^net/ipv6/esp6[^/]*$|^net/ipv6/ip6_vti\\\\.c$|^net/ipv6/ipcomp6\\\\.c$|^net/ipv6/xfrm[^/]*$|^net/key/|^net/xfrm/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/net_dropmon\\\\.h$|^net/core/drop_monitor\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/openvswitch\\\\.h$|^net/openvswitch/\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/tipc[^/]*\\\\.h$|^net/tipc/\"},\n\t\t\t{IncludeRegexp: \"^kernel/bpf/bpf_struct[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^net/core/filter\\\\.c$|^net/sched/act_bpf\\\\.c$|^net/sched/cls_bpf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^net/hsr/\"},\n\t\t\t{IncludeRegexp: \"^net/rds/\"},\n\t\t\t{IncludeRegexp: \"^net/sched/sch_cbs\\\\.c$|^net/sched/sch_etf\\\\.c$|^net/sched/sch_taprio\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^net/sched/sch_netem\\\\.c$\"},\n\t\t},\n\t}\n\n\tnetfilter = Subsystem{\n\t\tName: \"netfilter\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/netfilter[^/]*$|^include/linux/netfilter/|^include/net/netfilter/|^include/uapi/linux/netfilter[^/]*$|^include/uapi/linux/netfilter/|^net/[^/]*/netfilter\\\\.c$|^net/[^/]*/netfilter/|^net/bridge/br_netfilter[^/]*\\\\.c$|^net/netfilter/\"},\n\t\t},\n\t}\n\n\tnfc = Subsystem{\n\t\tName: \"nfc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/nfc/nxp-nci$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/s3fwrn5$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/trf7970a\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/virtual_ncidev\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/|^include/linux/platform_data/nfcmrvl\\\\.h$|^include/net/nfc/|^include/uapi/linux/nfc\\\\.h$|^net/nfc/\"},\n\t\t},\n\t}\n\n\tnfs = Subsystem{\n\t\tName: \"nfs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/exportfs/|^fs/lockd/|^fs/nfs_common/|^fs/nfsd/|^include/linux/lockd/|^include/linux/sunrpc/|^include/trace/events/rpcgss\\\\.h$|^include/trace/events/rpcrdma\\\\.h$|^include/trace/events/sunrpc\\\\.h$|^include/trace/misc/fs\\\\.h$|^include/trace/misc/nfs\\\\.h$|^include/trace/misc/sunrpc\\\\.h$|^include/uapi/linux/nfsd/|^include/uapi/linux/sunrpc/|^net/sunrpc/\"},\n\t\t\t{IncludeRegexp: \"^fs/lockd/|^fs/nfs/|^fs/nfs_common/|^include/linux/lockd/|^include/linux/nfs[^/]*$|^include/linux/sunrpc/|^include/uapi/linux/nfs[^/]*$|^include/uapi/linux/sunrpc/|^net/sunrpc/\"},\n\t\t},\n\t}\n\n\tnilfs = Subsystem{\n\t\tName: \"nilfs\",\n\t\tSyscalls: []string{\"syz_mount_image$nilfs2\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/nilfs2/|^include/trace/events/nilfs2\\\\.h$|^include/uapi/linux/nilfs2_api\\\\.h$|^include/uapi/linux/nilfs2_ondisk\\\\.h$\"},\n\t\t},\n\t}\n\n\tnitro = Subsystem{\n\t\tName: \"nitro\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/virt/nitro_enclaves/|^include/linux/nitro_enclaves\\\\.h$|^include/uapi/linux/nitro_enclaves\\\\.h$\"},\n\t\t},\n\t}\n\n\tnouveau = Subsystem{\n\t\tName: \"nouveau\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&dri},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/mm/kmmio\\\\.c$|^arch/x86/mm/mmio-mod\\\\.c$|^arch/x86/mm/testmmiotrace\\\\.c$|^include/linux/mmiotrace\\\\.h$|^kernel/trace/trace_mmiotrace\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/nouveau/|^include/uapi/drm/nouveau_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tntb = Subsystem{\n\t\tName: \"ntb\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/ntb_netdev\\\\.c$|^drivers/ntb/|^drivers/pci/endpoint/functions/pci-epf-[^/]*ntb\\\\.c$|^include/linux/ntb\\\\.h$|^include/linux/ntb_transport\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ntb/hw/amd/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ntb/hw/idt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ntb/hw/intel/\"},\n\t\t},\n\t}\n\n\tntfs = Subsystem{\n\t\tName: \"ntfs\",\n\t\tSyscalls: []string{\"syz_mount_image$ntfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^block/partitions/ldm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^fs/ntfs/\"},\n\t\t},\n\t}\n\n\tntfs3 = Subsystem{\n\t\tName: \"ntfs3\",\n\t\tSyscalls: []string{\"syz_mount_image$ntfs3\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/ntfs3/\"},\n\t\t},\n\t}\n\n\tnvdimm = Subsystem{\n\t\tName: \"nvdimm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/acpi/nfit/|^drivers/nvdimm/|^include/linux/libnvdimm\\\\.h$|^include/linux/nd\\\\.h$|^include/uapi/linux/ndctl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/dax/\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvdimm/btt[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvdimm/of_pmem\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvdimm/pmem[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^fs/dax\\\\.c$|^include/linux/dax\\\\.h$|^include/trace/events/fs_dax\\\\.h$\"},\n\t\t},\n\t}\n\n\tnvme = Subsystem{\n\t\tName: \"nvme\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/nvme/common/|^drivers/nvme/host/|^include/linux/nvme-[^/]*\\\\.h$|^include/linux/nvme\\\\.h$|^include/uapi/linux/nvme_ioctl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvme/host/auth\\\\.c$|^drivers/nvme/target/auth\\\\.c$|^drivers/nvme/target/fabrics-cmd-auth\\\\.c$|^include/linux/nvme-auth\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvme/host/fc\\\\.c$|^drivers/nvme/target/fc\\\\.c$|^drivers/nvme/target/fcloop\\\\.c$|^include/linux/nvme-fc-driver\\\\.h$|^include/linux/nvme-fc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvme/host/hwmon\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvme/target/\"},\n\t\t},\n\t}\n\n\tocfs2 = Subsystem{\n\t\tName: \"ocfs2\",\n\t\tSyscalls: []string{\"syz_mount_image$ocfs2\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/ocfs2/\"},\n\t\t},\n\t}\n\n\tomap = Subsystem{\n\t\tName: \"omap\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/[^/]*omap[^/]*/[^/]*clock[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/[^/]*omap[^/]*/[^/]*pm[^/]*$|^drivers/cpufreq/omap-cpufreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/[^/]*omap[^/]*/usb[^/]*$|^drivers/usb/[^/]*/[^/]*omap[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/[^/]*am3[^/]*$|^arch/arm/boot/dts/[^/]*am4[^/]*$|^arch/arm/boot/dts/[^/]*am5[^/]*$|^arch/arm/boot/dts/[^/]*dra7[^/]*$|^arch/arm/boot/dts/[^/]*omap[^/]*$|^arch/arm/boot/dts/logicpd-som-lv[^/]*$|^arch/arm/boot/dts/logicpd-torpedo[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/am335x-nano\\\\.dts$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/omap3-igep[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/configs/omap1_defconfig$|^arch/arm/mach-omap1/|^drivers/i2c/busses/i2c-omap\\\\.c$|^include/linux/platform_data/ams-delta-fiq\\\\.h$|^include/linux/platform_data/i2c-omap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/configs/omap2plus_defconfig$|^arch/arm/mach-omap2/|^drivers/bus/ti-sysc\\\\.c$|^drivers/i2c/busses/i2c-omap\\\\.c$|^drivers/irqchip/irq-omap-intc\\\\.c$|^drivers/mfd/[^/]*omap[^/]*\\\\.c$|^drivers/mfd/menelaus\\\\.c$|^drivers/mfd/palmas\\\\.c$|^drivers/mfd/tps65217\\\\.c$|^drivers/mfd/tps65218\\\\.c$|^drivers/mfd/tps65219\\\\.c$|^drivers/mfd/tps65910\\\\.c$|^drivers/mfd/twl-core\\\\.\\\\[ch\\\\]$|^drivers/mfd/twl4030[^/]*\\\\.c$|^drivers/mfd/twl6030[^/]*\\\\.c$|^drivers/mfd/twl6040[^/]*\\\\.c$|^drivers/regulator/palmas-regulator[^/]*\\\\.c$|^drivers/regulator/pbias-regulator\\\\.c$|^drivers/regulator/tps65217-regulator\\\\.c$|^drivers/regulator/tps65218-regulator\\\\.c$|^drivers/regulator/tps65219-regulator\\\\.c$|^drivers/regulator/tps65910-regulator\\\\.c$|^drivers/regulator/twl-regulator\\\\.c$|^drivers/regulator/twl6030-regulator\\\\.c$|^include/linux/platform_data/i2c-omap\\\\.h$|^include/linux/platform_data/ti-sysc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-omap2/[^/]*gpmc[^/]*$|^drivers/memory/omap-gpmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-omap2/omap_hwmod[^/]*data[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-omap2/omap_hwmod\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-omap2/prm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/ti/|^include/linux/clk/ti\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/counter/ti-ecap-capture\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-omap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hwspinlock/omap_hwspinlock\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-omap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/omap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/omap_hsmmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/ti/cpsw[^/]*$|^drivers/net/ethernet/ti/davinci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/cadence/pci-j721e\\\\.c$|^drivers/pci/controller/dwc/pci-dra7xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-single\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/ti-soc-thermal/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/omap/\"},\n\t\t\t{IncludeRegexp: \"^drivers/video/fbdev/omap2/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/ti/n810\\\\.c$|^sound/soc/ti/omap[^/]*$|^sound/soc/ti/rx51\\\\.c$|^sound/soc/ti/sdma-pcm\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\toptee = Subsystem{\n\t\tName: \"op-tee\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/char/hw_random/optee-rng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tee/optee/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tee/|^include/linux/tee_drv\\\\.h$|^include/uapi/linux/tee\\\\.h$\"},\n\t\t},\n\t}\n\n\topeniscsi = Subsystem{\n\t\tName: \"open-iscsi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&scsi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/scsi/[^/]*iscsi[^/]*$|^include/scsi/[^/]*iscsi[^/]*$\"},\n\t\t},\n\t}\n\n\topenbmc = Subsystem{\n\t\tName: \"openbmc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/nuvoton-npcm[^/]*$|^arch/arm/mach-npcm/|^arch/arm64/boot/dts/nuvoton/|^drivers/[^/]*/[^/]*npcm[^/]*$|^drivers/[^/]*/[^/]*/[^/]*npcm[^/]*$|^drivers/rtc/rtc-nct3018y\\\\.c$|^include/dt-bindings/clock/nuvoton,npcm7xx-clock\\\\.h$|^include/dt-bindings/clock/nuvoton,npcm845-clk\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/nuvoton-wpcm450[^/]*$|^arch/arm/configs/wpcm450_defconfig$|^arch/arm/mach-npcm/wpcm450\\\\.c$|^drivers/[^/]*/[^/]*/[^/]*wpcm[^/]*$|^drivers/[^/]*/[^/]*wpcm[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-aspeed\\\\.c$|^drivers/irqchip/irq-aspeed-i2c-ic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-fsi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/sdhci-of-aspeed[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/peci/controller/peci-aspeed\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/peci/|^include/linux/peci-cpu\\\\.h$|^include/linux/peci\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/aspeed/\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-aspeed-smc\\\\.c$\"},\n\t\t},\n\t}\n\n\topenipmi = Subsystem{\n\t\tName: \"openipmi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/char/ipmi/|^include/linux/ipmi[^/]*$|^include/uapi/linux/ipmi[^/]*$\"},\n\t\t},\n\t}\n\n\topenrisc = Subsystem{\n\t\tName: \"openrisc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/openrisc/|^drivers/irqchip/irq-ompic\\\\.c$|^drivers/irqchip/irq-or1k-[^/]*$\"},\n\t\t},\n\t}\n\n\topenvswitch = Subsystem{\n\t\tName: \"openvswitch\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/openvswitch\\\\.h$|^net/openvswitch/\"},\n\t\t},\n\t}\n\n\topenwrt = Subsystem{\n\t\tName: \"openwrt\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/b53/|^drivers/net/dsa/bcm_sf2[^/]*$|^include/linux/dsa/brcm\\\\.h$|^include/linux/platform_data/b53\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vlynq/vlynq\\\\.c$|^include/linux/vlynq\\\\.h$\"},\n\t\t},\n\t}\n\n\torangefs = Subsystem{\n\t\tName: \"orangefs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/orangefs/\"},\n\t\t},\n\t}\n\n\tossdrivers = Subsystem{\n\t\tName: \"oss-drivers\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/netronome/\"},\n\t\t},\n\t}\n\n\toverlayfs = Subsystem{\n\t\tName: \"overlayfs\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/overlayfs/\"},\n\t\t},\n\t}\n\n\toxnas = Subsystem{\n\t\tName: \"oxnas\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/ox8[^/]*\\\\.dts[^/]*$|^arch/arm/mach-oxnas/|^drivers/power/reset/oxnas-restart\\\\.c$|oxnas\"},\n\t\t},\n\t}\n\n\tparisc = Subsystem{\n\t\tName: \"parisc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/parisc/|^drivers/char/agp/parisc-agp\\\\.c$|^drivers/input/misc/hp_sdc_rtc\\\\.c$|^drivers/input/serio/gscps2\\\\.c$|^drivers/input/serio/hp_sdc[^/]*$|^drivers/parisc/|^drivers/parport/parport_gsc\\\\.[^/]*$|^drivers/tty/serial/8250/8250_parisc\\\\.c$|^drivers/video/console/sti[^/]*$|^drivers/video/fbdev/sti[^/]*$|^drivers/video/logo/logo_parisc[^/]*$|^include/linux/hp_sdc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/dec/tulip/\"},\n\t\t\t{IncludeRegexp: \"^sound/parisc/harmony\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^sound/pci/ad1889\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\tparport = Subsystem{\n\t\tName: \"parport\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/char/ppdev\\\\.c$|^drivers/parport/|^include/linux/parport[^/]*\\\\.h$|^include/uapi/linux/ppdev\\\\.h$\"},\n\t\t},\n\t}\n\n\tpci = Subsystem{\n\t\tName: \"pci\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/early-quirks\\\\.c$|^arch/x86/kernel/quirks\\\\.c$|^arch/x86/pci/|^drivers/acpi/pci[^/]*$|^drivers/pci/|^include/asm-generic/pci[^/]*$|^include/linux/of_pci\\\\.h$|^include/linux/pci[^/]*$|^include/uapi/linux/pci[^/]*$|^lib/pci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/dw-xdata-pcie\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/misc/pci_endpoint_test\\\\.c$|^drivers/pci/endpoint/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ntb/hw/mscc/|^drivers/pci/switch/switchtec[^/]*$|^include/linux/switchtec\\\\.h$|^include/uapi/linux/switchtec_ioctl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*mediatek[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*microchip[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*mvebu[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*rcar[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/cadence/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/cadence/pci-j721e\\\\.c$|^drivers/pci/controller/dwc/pci-dra7xx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*artpec[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*designware[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*imx6[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*layerscape[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/[^/]*spear[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pci-exynos\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pci-meson\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-al\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-armada8k\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-fu740\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-hisi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-histb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-intel-gw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-keembay\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-kirin\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-qcom-ep\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-qcom\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pcie-uniphier[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/mobiveil/pcie-layerscape-gen4\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/mobiveil/pcie-mobiveil[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-aardvark\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-host-common\\\\.c$|^drivers/pci/controller/pci-host-generic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-tegra\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-thunder-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-v3-semi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-versatile\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-xgene-msi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-xgene\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-altera-msi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-altera\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-apple\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-brcmstb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-rockchip[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-xilinx-cpm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/vmd\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/|^drivers/pci/pci-bridge-emul\\\\.c$|^drivers/pci/pci-bridge-emul\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/cpci_hotplug[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/cpcihp_generic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/cpcihp_zt5550\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/rpadlpar[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/hotplug/rpaphp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/p2pdma\\\\.c$|^include/linux/pci-p2pdma\\\\.h$\"},\n\t\t},\n\t}\n\n\tperf = Subsystem{\n\t\tName: \"perf\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/events/|^arch/[^/]*/events/[^/]*/|^arch/[^/]*/include/asm/perf_event\\\\.h$|^arch/[^/]*/kernel/[^/]*/[^/]*/perf_event[^/]*\\\\.c$|^arch/[^/]*/kernel/[^/]*/perf_event[^/]*\\\\.c$|^arch/[^/]*/kernel/perf_callchain\\\\.c$|^arch/[^/]*/kernel/perf_event[^/]*\\\\.c$|^include/linux/perf_event\\\\.h$|^include/uapi/linux/perf_event\\\\.h$|^kernel/events/\"},\n\t\t},\n\t}\n\n\tphy = Subsystem{\n\t\tName: \"phy\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/phy/|^include/dt-bindings/phy/|^include/linux/phy/\"},\n\t\t},\n\t}\n\n\tpm = Subsystem{\n\t\tName: \"pm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/suspend[^/]*\\\\.h$|^arch/x86/power/|^drivers/base/power/|^include/linux/freezer\\\\.h$|^include/linux/pm\\\\.h$|^include/linux/suspend\\\\.h$|^kernel/power/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-exynos/pm\\\\.c$|^drivers/cpuidle/cpuidle-exynos\\\\.c$|^include/linux/platform_data/cpuidle-exynos\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/kernel/acpi/sleep[^/]*$|^arch/x86/kernel/acpi/wakeup[^/]*$|^drivers/base/power/|^include/linux/freezer\\\\.h$|^include/linux/pm\\\\.h$|^include/linux/suspend\\\\.h$|^kernel/power/\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/power/domain[^/]*\\\\.c$|^include/linux/pm_domain\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/base/power/|^drivers/powercap/|^include/linux/intel_rapl\\\\.h$|^include/linux/pm\\\\.h$|^include/linux/pm_[^/]*$|^include/linux/powercap\\\\.h$|^kernel/configs/nopm\\\\.config$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/amd-pstate[^/]*$|^include/linux/amd-pstate\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/bmips-cpufreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/brcmstb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/intel_pstate\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/qcom-cpufreq-nvmem\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/sun50i-cpufreq-nvmem\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/vexpress-spc-cpufreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpufreq/|^include/linux/cpufreq\\\\.h$|^include/linux/sched/cpufreq\\\\.h$|^kernel/sched/cpufreq[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-big_little\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-psci\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-psci\\\\.h$|^drivers/cpuidle/cpuidle-psci-domain\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-riscv-sbi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/dt_idle_genpd\\\\.c$|^drivers/cpuidle/dt_idle_genpd\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/|^include/linux/cpuidle\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/devfreq-event\\\\.c$|^drivers/devfreq/event/|^include/dt-bindings/pmu/exynos_ppmu\\\\.h$|^include/linux/devfreq-event\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/exynos-bus\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/tegra30-devfreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/|^include/linux/devfreq\\\\.h$|^include/trace/events/devfreq\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/idle/intel_idle\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/interconnect/samsung/\"},\n\t\t\t{IncludeRegexp: \"^drivers/interconnect/|^include/dt-bindings/interconnect/|^include/linux/interconnect-provider\\\\.h$|^include/linux/interconnect\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/samsung/exynos5422-dmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/opp/|^include/linux/pm_opp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/reset/\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/reset/mt6323-poweroff\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/adp5061\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/max14577_charger\\\\.c$|^drivers/power/supply/max77693_charger\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/max17040_battery\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/max17042_battery\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/surface_battery\\\\.c$|^drivers/power/supply/surface_charger\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/|^include/linux/power/|^include/linux/power_supply\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/powercap/dtpm[^/]*$|^include/linux/dtpm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/bcm/bcm63xx/bcm-pmb\\\\.c$|^include/dt-bindings/soc/bcm-pmb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/qcom/cpr\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/ti/smartreflex\\\\.c$|^include/linux/power/smartreflex\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/amlogic_thermal\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/broadcom/brcmstb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/cpufreq_cooling\\\\.c$|^drivers/thermal/cpuidle_cooling\\\\.c$|^include/linux/cpu_cooling\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/gov_power_allocator\\\\.c$|^include/trace/events/thermal_power_allocator\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/intel/intel_menlow\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/qcom/\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/samsung/\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/sun8i_thermal\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/ti-soc-thermal/\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/|^include/dt-bindings/thermal/|^include/linux/cpu_cooling\\\\.h$|^include/linux/thermal\\\\.h$|^include/uapi/linux/thermal\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/freezer\\\\.h$|^kernel/freezer\\\\.c$\"},\n\t\t},\n\t}\n\n\tppp = Subsystem{\n\t\tName: \"ppp\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/ppp/ppp_[^/]*$\"},\n\t\t},\n\t}\n\n\tpvrusb2 = Subsystem{\n\t\tName: \"pvrusb2\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&media},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/media/usb/pvrusb2/\"},\n\t\t},\n\t}\n\n\tpwm = Subsystem{\n\t\tName: \"pwm\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-mvebu\\\\.c$|^drivers/pwm/|^drivers/video/backlight/pwm_bl\\\\.c$|^include/dt-bindings/pwm/|^include/linux/pwm\\\\.h$|^include/linux/pwm_backlight\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pwm/pwm-atmel\\\\.c$\"},\n\t\t},\n\t}\n\n\tqat = Subsystem{\n\t\tName: \"qat\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&crypto},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/crypto/qat/\"},\n\t\t},\n\t}\n\n\traid = Subsystem{\n\t\tName: \"raid\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/md/Kconfig$|^drivers/md/md[^/]*$|^drivers/md/raid[^/]*$|^include/linux/raid/|^include/uapi/linux/raid/\"},\n\t\t},\n\t}\n\n\trcu = Subsystem{\n\t\tName: \"rcu\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{\"^include/linux/rcu[^/]*$|^kernel/rcu/\", \"^include/linux/srcu[^/]*\\\\.h$|^kernel/rcu/srcu[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^include/linux/srcu[^/]*\\\\.h$|^kernel/rcu/srcu[^/]*\\\\.c$\"},\n\t\t},\n\t}\n\n\trdma = Subsystem{\n\t\tName: \"rdma\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/bnxt_re/|^include/uapi/rdma/bnxt_re-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/cxgb4/|^include/uapi/rdma/cxgb4-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/efa/|^include/uapi/rdma/efa-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/erdma$|^include/uapi/rdma/erdma-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/hfi1$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/hns/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/irdma/|^include/uapi/rdma/irdma-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/mana/|^include/net/mana$|^include/uapi/rdma/mana-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/mlx4/|^include/linux/mlx4/|^include/uapi/rdma/mlx4-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/mlx5/|^include/linux/mlx5/|^include/uapi/rdma/mlx5-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/ocrdma/|^include/uapi/rdma/ocrdma-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/qedr/|^include/uapi/rdma/qedr-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/qib/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/hw/vmw_pvrdma/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/sw/rdmavt$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/sw/rxe/|^include/uapi/rdma/rdma_user_rxe\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/sw/siw/|^include/uapi/rdma/siw-abi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/iser/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/isert$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/opa_vnic$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/rtrs/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/srp/|^include/scsi/srp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/srpt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/|^include/rdma/|^include/trace/events/ib_mad\\\\.h$|^include/trace/events/ib_umad\\\\.h$|^include/trace/misc/rdma\\\\.h$|^include/uapi/linux/if_infiniband\\\\.h$|^include/uapi/rdma/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx4/|^include/linux/mlx4/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/mellanox/mlx5/core/|^include/linux/mlx5/\"},\n\t\t\t{IncludeRegexp: \"^net/rds/\"},\n\t\t},\n\t}\n\n\trds = Subsystem{\n\t\tName: \"rds\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net, &rdma},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^net/rds/\"},\n\t\t},\n\t}\n\n\treiserfs = Subsystem{\n\t\tName: \"reiserfs\",\n\t\tSyscalls: []string{\"syz_mount_image$reiserfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/reiserfs/\"},\n\t\t},\n\t}\n\n\tremoteproc = Subsystem{\n\t\tName: \"remoteproc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/hwspinlock/|^include/linux/hwspinlock\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wwan/rpmsg_wwan_ctrl\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/remoteproc/|^include/linux/remoteproc\\\\.h$|^include/linux/remoteproc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/rpmsg/|^include/linux/rpmsg\\\\.h$|^include/linux/rpmsg/|^include/uapi/linux/rpmsg\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/rpmsg_tty\\\\.c$\"},\n\t\t},\n\t}\n\n\trenesassoc = Subsystem{\n\t\tName: \"renesas-soc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/emev2[^/]*$|^arch/arm/boot/dts/gr-peach[^/]*$|^arch/arm/boot/dts/iwg20d-q7[^/]*$|^arch/arm/boot/dts/r7s[^/]*$|^arch/arm/boot/dts/r8a[^/]*$|^arch/arm/boot/dts/r9a[^/]*$|^arch/arm/boot/dts/sh[^/]*$|^arch/arm/configs/shmobile_defconfig$|^arch/arm/include/debug/renesas-scif\\\\.S$|^arch/arm/mach-shmobile/|^arch/arm64/boot/dts/renesas/|^arch/riscv/boot/dts/renesas/|^drivers/soc/renesas/|^include/linux/soc/renesas/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ata/sata_rcar\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/renesas/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-bd9571mwv\\\\.c$|^drivers/mfd/bd9571mwv\\\\.c$|^drivers/regulator/bd9571mwv-regulator\\\\.c$|^include/linux/mfd/bd9571mwv\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/rcar-du/|^drivers/gpu/drm/shmobile/|^include/linux/platform_data/shmob_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-emev2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-rcar\\\\.c$|^drivers/i2c/busses/i2c-sh_mobile\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-riic\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iio/adc/rzg2l_adc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar-fcp\\\\.c$|^include/media/rcar-fcp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar-isp\\\\.c$|^drivers/media/platform/renesas/rcar-vin/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_drif\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_fdp1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/rcar_jpu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/renesas-ceu\\\\.c$|^include/media/drv-intf/renesas-ceu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/renesas/vsp1/\"},\n\t\t\t{IncludeRegexp: \"^drivers/mmc/host/renesas_sdhi[^/]*$|^drivers/mmc/host/tmio_mmc[^/]*$|^include/linux/mfd/tmio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/mtd/nand/raw/renesas-nand-controller\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/dsa/rzn1_a5psw[^/]*$|^drivers/net/pcs/pcs-rzn1-miic\\\\.c$|^include/dt-bindings/net/pcs-rzn1-miic\\\\.h$|^include/linux/pcs-rzn1-miic\\\\.h$|^net/dsa/tag_rzn1_a5psw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ethernet/renesas/|^include/linux/sh_eth\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/[^/]*rcar[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/renesas/phy-rcar-gen3-usb[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/renesas/\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-rzn1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/rcar_gen3_thermal\\\\.c$|^drivers/thermal/rcar_thermal\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-renesas\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/renesas_usbf\\\\.c$\"},\n\t\t},\n\t}\n\n\triscv = Subsystem{\n\t\tName: \"riscv\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/riscv/boot/dts/\"},\n\t\t\t{IncludeRegexp: \"^arch/riscv/boot/dts/microchip/|^drivers/char/hw_random/mpfs-rng\\\\.c$|^drivers/clk/microchip/clk-mpfs[^/]*\\\\.c$|^drivers/i2c/busses/i2c-microchip-corei2c\\\\.c$|^drivers/mailbox/mailbox-mpfs\\\\.c$|^drivers/pci/controller/pcie-microchip-host\\\\.c$|^drivers/reset/reset-mpfs\\\\.c$|^drivers/rtc/rtc-mpfs\\\\.c$|^drivers/soc/microchip/mpfs-sys-controller\\\\.c$|^drivers/spi/spi-microchip-core-qspi\\\\.c$|^drivers/spi/spi-microchip-core\\\\.c$|^drivers/usb/musb/mpfs\\\\.c$|^include/soc/microchip/mpfs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/riscv/include/asm/kvm[^/]*$|^arch/riscv/include/uapi/asm/kvm[^/]*$|^arch/riscv/kvm/\"},\n\t\t\t{IncludeRegexp: \"^arch/riscv/|riscv\"},\n\t\t\t{IncludeRegexp: \"^drivers/cpuidle/cpuidle-riscv-sbi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/perf/riscv_pmu\\\\.c$|^drivers/perf/riscv_pmu_legacy\\\\.c$|^drivers/perf/riscv_pmu_sbi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/pinctrl-k210\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/reset/reset-k210\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/canaan/|^include/soc/canaan/\"},\n\t\t\t{IncludeRegexp: \"^drivers/soc/sifive/\"},\n\t\t\t{IncludeRegexp: \"fu540\"},\n\t\t\t{IncludeRegexp: \"sifive\"},\n\t\t},\n\t}\n\n\trockchip = Subsystem{\n\t\tName: \"rockchip\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/rk3[^/]*$|^arch/arm/boot/dts/rv11[^/]*$|^arch/arm/mach-rockchip/|^drivers/[^/]*/[^/]*/[^/]*rockchip[^/]*$|^drivers/[^/]*/[^/]*rockchip[^/]*$|^drivers/clk/rockchip/|^drivers/i2c/busses/i2c-rk3x\\\\.c$|^sound/soc/rockchip/|rockchip\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/rockchip/rga/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/rockchip/rkisp1$|^include/uapi/linux/rkisp1-config\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/verisilicon/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-rockchip[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/rkvdec/\"},\n\t\t\t{IncludeRegexp: \"^sound/soc/rockchip/rockchip_i2s_tdm\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\trpi = Subsystem{\n\t\tName: \"rpi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pcie-brcmstb\\\\.c$|^drivers/staging/vc04_services$|bcm2711|bcm283*|raspberrypi\"},\n\t\t},\n\t}\n\n\trttools = Subsystem{\n\t\tName: \"rt-tools\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&trace},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/rv\\\\.h$|^include/rv/|^kernel/trace/rv/\"},\n\t\t},\n\t}\n\n\trtc = Subsystem{\n\t\tName: \"rtc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-optee\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-rzn1\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-sd3078\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/rtc-sunplus\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/rtc/|^include/linux/platform_data/rtc-[^/]*$|^include/linux/rtc\\\\.h$|^include/linux/rtc/|^include/uapi/linux/rtc\\\\.h$\"},\n\t\t},\n\t}\n\n\trust = Subsystem{\n\t\tName: \"rust\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^rust/\"},\n\t\t},\n\t}\n\n\ts390 = Subsystem{\n\t\tName: \"s390\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/s390/include/asm/pgtable\\\\.h$|^arch/s390/mm$\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/include/uapi/asm/virtio-ccw\\\\.h$|^drivers/s390/virtio/\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/kvm/pci[^/]*$|^drivers/vfio/pci/vfio_pci_zdev\\\\.c$|^include/uapi/linux/vfio_zdev\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/pci/|^drivers/pci/hotplug/s390_pci_hpc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/|^drivers/s390/|^drivers/watchdog/diag288_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^block/partitions/ibm\\\\.c$|^drivers/s390/block/dasd[^/]*$|^include/linux/dasd_mod\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/s390-iommu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/block/scm[^/]*$|^drivers/s390/cio/scm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/cio/\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/cio/vfio_ccw[^/]*$|^include/uapi/linux/vfio_ccw\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/crypto/\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/crypto/vfio_ap[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/net/\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/net/[^/]*iucv[^/]*$|^include/net/iucv/|^net/iucv/\"},\n\t\t\t{IncludeRegexp: \"^drivers/s390/scsi/zfcp_[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^net/smc/\"},\n\t\t},\n\t}\n\n\tsamsungsoc = Subsystem{\n\t\tName: \"samsung-soc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/exynos[^/]*$|^arch/arm/boot/dts/s3c[^/]*$|^arch/arm/boot/dts/s5p[^/]*$|^arch/arm/mach-exynos[^/]*/|^arch/arm/mach-s3c/|^arch/arm/mach-s5p[^/]*/|^arch/arm64/boot/dts/exynos/|^drivers/[^/]*/[^/]*/[^/]*s3c24[^/]*$|^drivers/[^/]*/[^/]*s3c24[^/]*$|^drivers/[^/]*/[^/]*s3c64xx[^/]*$|^drivers/[^/]*/[^/]*s5pv210[^/]*$|^drivers/clocksource/samsung_pwm_timer\\\\.c$|^drivers/memory/samsung/|^drivers/pwm/pwm-samsung\\\\.c$|^drivers/soc/samsung/|^drivers/tty/serial/samsung[^/]*$|^include/clocksource/samsung_pwm\\\\.h$|^include/linux/platform_data/[^/]*s3c[^/]*$|^include/linux/serial_s3c\\\\.h$|^include/linux/soc/samsung/|exynos|s3c64xx|s5pv210\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-exynos/pm\\\\.c$|^drivers/cpuidle/cpuidle-exynos\\\\.c$|^include/linux/platform_data/cpuidle-exynos\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/boot/dts/tesla/\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/hw_random/exynos-trng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/clk-s2mps11\\\\.c$|^drivers/mfd/sec[^/]*\\\\.c$|^drivers/regulator/s2m[^/]*\\\\.c$|^drivers/regulator/s5m[^/]*\\\\.c$|^drivers/rtc/rtc-s5m\\\\.c$|^include/linux/mfd/samsung/\"},\n\t\t\t{IncludeRegexp: \"^drivers/clk/samsung/|^include/dt-bindings/clock/exynos[^/]*\\\\.h$|^include/dt-bindings/clock/s5p[^/]*\\\\.h$|^include/dt-bindings/clock/samsung,[^/]*\\\\.h$|^include/linux/clk/samsung\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/exynos-rng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/s5p-sss\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/exynos-bus\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/interconnect/samsung/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/s5p/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/samsung/s3c-camif/|^include/media/drv-intf/s3c_camif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/memory/samsung/exynos5422-dmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/dwc/pci-exynos\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/pinctrl/samsung/|^include/dt-bindings/pinctrl/samsung\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-s3c[^/]*$|^include/linux/platform_data/spi-s3c64xx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thermal/samsung/\"},\n\t\t},\n\t}\n\n\tscsi = Subsystem{\n\t\tName: \"scsi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^block/bsg\\\\.c$|^include/linux/bsg\\\\.h$|^include/uapi/linux/bsg\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/message/fusion/|^drivers/scsi/mpt3sas/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/3w-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/53c700[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/53c700[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/BusLogic\\\\.[^/]*$|^drivers/scsi/FlashPoint\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/NCR5380\\\\.[^/]*$|^drivers/scsi/arm/cumana_1\\\\.c$|^drivers/scsi/arm/oak\\\\.c$|^drivers/scsi/atari_scsi\\\\.[^/]*$|^drivers/scsi/dmx3191d\\\\.c$|^drivers/scsi/g_NCR5380\\\\.[^/]*$|^drivers/scsi/mac_scsi\\\\.[^/]*$|^drivers/scsi/sun3_scsi\\\\.[^/]*$|^drivers/scsi/sun3_scsi_vme\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/[^/]*iscsi[^/]*$|^include/scsi/[^/]*iscsi[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/aacraid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/advansys\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/aha152x[^/]*$|^drivers/scsi/pcmcia/aha152x[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/aic7xxx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/am53c974\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/be2iscsi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/bfa/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/bnx2fc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/bnx2i/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/cxgbi/cxgb3i$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/cxgbi/cxgb4i$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/cxlflash/|^include/uapi/scsi/cxlflash_ioctl\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/elx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/esas2r$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/fcoe/|^drivers/scsi/libfc/|^include/scsi/fc/|^include/scsi/libfc\\\\.h$|^include/scsi/libfcoe\\\\.h$|^include/uapi/scsi/fc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/fnic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/hpsa[^/]*\\\\.\\\\[ch\\\\]$|^include/linux/cciss[^/]*\\\\.h$|^include/uapi/linux/cciss[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/ibmvscsi/ibmvfc[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/ibmvscsi/ibmvscsi[^/]*$|^include/scsi/viosrp\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/ibmvscsi_tgt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/ips[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/isci/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/lpfc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/megaraid\\\\.[^/]*$|^drivers/scsi/megaraid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/mpi3mr/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/myrb\\\\.[^/]*$|^drivers/scsi/myrs\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/pm8001/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/pmcraid\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/qedf/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/qedi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/qla1280\\\\.\\\\[ch\\\\]$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/qla2xxx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/qla4xxx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/sg\\\\.c$|^include/scsi/sg\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/smartpqi/Kconfig$|^drivers/scsi/smartpqi/smartpqi[^/]*\\\\.\\\\[ch\\\\]$|^include/linux/cciss[^/]*\\\\.h$|^include/uapi/linux/cciss[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/snic/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/st\\\\.[^/]*$|^drivers/scsi/st_[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/sym53c8xx_2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/vmw_pvscsi\\\\.c$|^drivers/scsi/vmw_pvscsi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/xen-scsifront\\\\.c$|^drivers/xen/xen-scsiback\\\\.c$|^include/xen/interface/io/vscsiif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/|^drivers/ufs/|^include/scsi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/sbp/\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/target_core_user\\\\.c$|^include/uapi/linux/target_core_user\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/|^include/target/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/core/\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/[^/]*dwc[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-exynos[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-mediatek[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-qcom[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ufs/host/ufs-renesas\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/storage/uas\\\\.c$\"},\n\t\t},\n\t}\n\n\tsctp = Subsystem{\n\t\tName: \"sctp\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/linux/sctp\\\\.h$|^include/net/sctp/|^include/uapi/linux/sctp\\\\.h$|^net/sctp/\"},\n\t\t},\n\t}\n\n\tselinux = Subsystem{\n\t\tName: \"selinux\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/trace/events/avc\\\\.h$|^include/uapi/linux/selinux_netlink\\\\.h$|^security/selinux/\"},\n\t\t},\n\t}\n\n\tserial = Subsystem{\n\t\tName: \"serial\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/tty/serdev/|^include/linux/serdev\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/8250/8250_bcm7271\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/8250/8250_pci1xxxx\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/8250[^/]*$|^include/linux/serial_8250\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/altera_jtaguart\\\\.c$|^drivers/tty/serial/altera_uart\\\\.c$|^include/linux/altera_jtaguart\\\\.h$|^include/linux/altera_uart\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/jsm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/rp2\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/uartlite\\\\.c$\"},\n\t\t},\n\t}\n\n\tsgx = Subsystem{\n\t\tName: \"sgx\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/entry/vdso/vsgx\\\\.S$|^arch/x86/include/asm/sgx\\\\.h$|^arch/x86/include/uapi/asm/sgx\\\\.h$|^arch/x86/kernel/cpu/sgx/\"},\n\t\t},\n\t}\n\n\tsh = Subsystem{\n\t\tName: \"sh\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/sh/|^drivers/sh/\"},\n\t\t},\n\t}\n\n\tsnpsarc = Subsystem{\n\t\tName: \"snps-arc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arc/|^drivers/clocksource/arc_timer\\\\.c$|^drivers/tty/serial/arc_uart\\\\.c$\"},\n\t\t},\n\t}\n\n\tsof = Subsystem{\n\t\tName: \"sof\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&alsa},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^sound/soc/sof/\"},\n\t\t},\n\t}\n\n\tsparclinux = Subsystem{\n\t\tName: \"sparclinux\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/sparc/|^drivers/sbus/\"},\n\t\t\t{IncludeRegexp: \"^drivers/tty/serial/suncore\\\\.c$|^drivers/tty/serial/sunhv\\\\.c$|^drivers/tty/serial/sunsab\\\\.c$|^drivers/tty/serial/sunsab\\\\.h$|^drivers/tty/serial/sunsu\\\\.c$|^drivers/tty/serial/sunzilog\\\\.c$|^drivers/tty/serial/sunzilog\\\\.h$|^drivers/tty/vcc\\\\.c$|^include/linux/sunserialcore\\\\.h$\"},\n\t\t},\n\t}\n\n\tspeakup = Subsystem{\n\t\tName: \"speakup\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/accessibility/speakup/\"},\n\t\t},\n\t}\n\n\tspi = Subsystem{\n\t\tName: \"spi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-aspeed-smc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-at91-usart\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-bcm63xx-hsspi\\\\.c$|^drivers/spi/spi-bcmbca-hsspi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-dw[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-fsi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-fsl-dspi\\\\.c$|^include/linux/spi/spi-fsl-dspi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-fsl-qspi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-hisi-kunpeng\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-nxp-fspi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-s3c[^/]*$|^include/linux/platform_data/spi-s3c64xx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-stm32\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-sunplus-sp7021\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-synquacer\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/|^include/linux/spi/|^include/uapi/linux/spi/\"},\n\t\t},\n\t}\n\n\tspice = Subsystem{\n\t\tName: \"spice\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&dri, &virt},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/qxl/|^include/uapi/drm/qxl_drm\\\\.h$\"},\n\t\t},\n\t}\n\n\tsquashfs = Subsystem{\n\t\tName: \"squashfs\",\n\t\tSyscalls: []string{\"syz_mount_image$squashfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/squashfs/\"},\n\t\t},\n\t}\n\n\tstaging = Subsystem{\n\t\tName: \"staging\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&media},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/staging/\"},\n\t\t},\n\t}\n\n\tstm32 = Subsystem{\n\t\tName: \"stm32\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/stm32[^/]*$|^arch/arm/mach-stm32/|^drivers/clocksource/armv7m_systick\\\\.c$|stm32|stm\"},\n\t\t},\n\t}\n\n\tsunxi = Subsystem{\n\t\tName: \"sunxi\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/mach-sunxi/|^arch/arm64/boot/dts/allwinner/|^drivers/clk/sunxi-ng/|^drivers/pinctrl/sunxi/|^drivers/soc/sunxi/|allwinner|sun[x456789]i|sun[25]0i\"},\n\t\t},\n\t}\n\n\ttarget = Subsystem{\n\t\tName: \"target\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&scsi},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/isert$\"},\n\t\t\t{IncludeRegexp: \"^drivers/infiniband/ulp/srpt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/elx/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/ibmvscsi_tgt/\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/sbp/\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/target_core_user\\\\.c$|^include/uapi/linux/target_core_user\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/target/|^include/target/\"},\n\t\t},\n\t}\n\n\ttegra = Subsystem{\n\t\tName: \"tegra\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"[^a-z]tegra\"},\n\t\t\t{IncludeRegexp: \"^drivers/devfreq/tegra30-devfreq\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tegra/|^drivers/gpu/host1x/|^include/linux/host1x\\\\.h$|^include/uapi/drm/tegra_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/arm/arm-smmu/arm-smmu-nvidia\\\\.c$|^drivers/iommu/tegra[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/cec/platform/tegra/\"},\n\t\t\t{IncludeRegexp: \"^drivers/media/platform/nvidia/tegra-vde/\"},\n\t\t\t{IncludeRegexp: \"^drivers/pci/controller/pci-tegra\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-tegra210-quad\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/media/tegra-video/\"},\n\t\t\t{IncludeRegexp: \"^drivers/staging/nvec/\"},\n\t\t},\n\t}\n\n\ttipc = Subsystem{\n\t\tName: \"tipc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/tipc[^/]*\\\\.h$|^net/tipc/\"},\n\t\t},\n\t}\n\n\ttomoyo = Subsystem{\n\t\tName: \"tomoyo\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&lsm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^security/tomoyo/\"},\n\t\t},\n\t}\n\n\ttrace = Subsystem{\n\t\tName: \"trace\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/proc/bootconfig\\\\.c$|^include/linux/bootconfig\\\\.h$|^lib/bootconfig-data\\\\.S$|^lib/bootconfig\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^fs/tracefs/|^include/linux/trace[^/]*\\\\.h$|^include/trace/|^kernel/trace/\"},\n\t\t\t{IncludeRegexp: \"^include/asm-generic/kprobes\\\\.h$|^include/linux/kprobes\\\\.h$|^kernel/kprobes\\\\.c$|^lib/test_kprobes\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^kernel/trace/ftrace[^/]*$|^kernel/trace/fgraph\\\\.c$|^arch/[^/]*/[^/]*/[^/]*/[^/]*ftrace[^/]*$|^arch/[^/]*/[^/]*/[^/]*ftrace[^/]*$|^include/[^/]*/ftrace\\\\.h$\"},\n\t\t},\n\t}\n\n\tuclinux = Subsystem{\n\t\tName: \"uclinux\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&m68k},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/m68k/[^/]*/[^/]*_no\\\\.[^/]*$|^arch/m68k/68[^/]*/|^arch/m68k/coldfire/|^arch/m68k/include/asm/[^/]*_no\\\\.[^/]*$\"},\n\t\t},\n\t}\n\n\tudf = Subsystem{\n\t\tName: \"udf\",\n\t\tSyscalls: []string{\"syz_mount_image$udf\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/udf/\"},\n\t\t},\n\t}\n\n\tum = Subsystem{\n\t\tName: \"um\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/um/|^arch/x86/um/|^fs/hostfs/\"},\n\t\t},\n\t}\n\n\tunisoc = Subsystem{\n\t\tName: \"unisoc\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&arm},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/boot/dts/rda8810pl-[^/]*$|^drivers/clocksource/timer-rda\\\\.c$|^drivers/gpio/gpio-rda\\\\.c$|^drivers/irqchip/irq-rda-intc\\\\.c$|^drivers/tty/serial/rda-uart\\\\.c$\"},\n\t\t},\n\t}\n\n\tusb = Subsystem{\n\t\tName: \"usb\",\n\t\tSyscalls: []string{\"syz_usb_connect\", \"syz_usb_connect$hid\", \"syz_usb_connect$printer\", \"syz_usb_connect$cdc_ecm\", \"syz_usb_connect$cdc_ncm\", \"syz_usb_connect$uac1\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/arm/[^/]*omap[^/]*/usb[^/]*$|^drivers/usb/[^/]*/[^/]*omap[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/usbhid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/cdc_[^/]*\\\\.c$|^include/uapi/linux/usb/cdc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/hso\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/pegasus\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/usb/rtl8150\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/hisilicon/phy-hi3660-usb3\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/hisilicon/phy-hi3670-usb3\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/phy/sunplus/Kconfig$|^drivers/phy/sunplus/phy-sunplus-usb2\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thunderbolt/dma_test\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/thunderbolt/|^include/linux/thunderbolt\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/atm/speedtch\\\\.c$|^drivers/usb/atm/usbatm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/c67x00/\"},\n\t\t\t{\"^drivers/usb/cdns3/\", \"^drivers/usb/cdns3/cdns3[^/]*$\"},\n\t\t\t{\"^drivers/usb/cdns3/\", \"^drivers/usb/cdns3/cdnsp[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/chipidea/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/class/cdc-acm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/class/usblp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/common/ulpi\\\\.c$|^include/linux/ulpi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/common/usb-otg-fsm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/dwc2/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/dwc3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/fotg210/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/function/[^/]*uvc[^/]*$|^drivers/usb/gadget/legacy/webcam\\\\.c$|^include/uapi/linux/usb/g_uvc\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/legacy/raw_gadget\\\\.c$|^include/uapi/linux/usb/raw_gadget\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/bcm63xx_udc\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/bdc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/fsl[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/gadget/udc/renesas_usbf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/ehci-brcm\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/ehci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/isp116x[^/]*$|^include/linux/usb/isp116x\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/ohci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/pci-quirks[^/]*$|^drivers/usb/host/xhci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/uhci[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/xen[^/]*$|^include/xen/interface/io/usbif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/xhci-mtk[^/]*$|^drivers/usb/mtu3/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/isp1760/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/apple-mfi-fastcharge\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/brcmstb-usb-pinmap\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/chaoskey\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/onboard_usb_hub\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/misc/usb251xb\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/musb/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/phy/phy-fsl-usb[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/roles/intel-xhci-usb-role-switch\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/serial/|^include/linux/usb/serial\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/storage/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/storage/uas\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/typec/altmodes/|^include/linux/usb/typec_altmode\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/typec/mux/intel_pmc_mux\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/typec/mux/pi3usb30532\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/typec/tcpm/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/typec/|^include/linux/usb/typec\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/usbip/\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/|^include/dt-bindings/usb/|^include/linux/usb\\\\.h$|^include/linux/usb/\"},\n\t\t},\n\t}\n\n\tusbstorage = Subsystem{\n\t\tName: \"usb-storage\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&usb},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/usb/storage/\"},\n\t\t},\n\t}\n\n\tvideo = Subsystem{\n\t\tName: \"video\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/boot/video[^/]*$\"},\n\t\t},\n\t}\n\n\tvirt = Subsystem{\n\t\tName: \"virt\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/paravirt[^/]*\\\\.h$|^arch/[^/]*/kernel/paravirt[^/]*$|^include/linux/hypervisor\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/s390/include/uapi/asm/virtio-ccw\\\\.h$|^drivers/s390/virtio/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/vmware\\\\.h$|^arch/x86/kernel/cpu/vmware\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/virtio_blk\\\\.c$|^drivers/crypto/virtio/|^drivers/net/virtio_net\\\\.c$|^drivers/vdpa/|^drivers/virtio/|^include/linux/vdpa\\\\.h$|^include/linux/virtio[^/]*\\\\.h$|^include/uapi/linux/virtio_[^/]*\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/virtio_blk\\\\.c$|^drivers/scsi/virtio_scsi\\\\.c$|^drivers/vhost/scsi\\\\.c$|^include/uapi/linux/virtio_blk\\\\.h$|^include/uapi/linux/virtio_scsi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/virtio_console\\\\.c$|^include/linux/virtio_console\\\\.h$|^include/uapi/linux/virtio_console\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/crypto/virtio/|^include/uapi/linux/virtio_crypto\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpio/gpio-virtio\\\\.c$|^include/uapi/linux/virtio_gpio\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/qxl/|^include/uapi/drm/qxl_drm\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tiny/bochs\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/tiny/cirrus\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/virtio/|^include/uapi/linux/virtio_gpu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/i2c/busses/i2c-virtio\\\\.c$|^include/uapi/linux/virtio_i2c\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/iommu/virtio-iommu\\\\.c$|^include/uapi/linux/virtio_iommu\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/vsockmon\\\\.c$|^include/net/af_vsock\\\\.h$|^include/uapi/linux/vm_sockets\\\\.h$|^include/uapi/linux/vm_sockets_diag\\\\.h$|^include/uapi/linux/vsockmon\\\\.h$|^net/vmw_vsock/\"},\n\t\t\t{IncludeRegexp: \"^drivers/nvdimm/virtio_pmem\\\\.c$|^drivers/nvdimm/nd_virtio\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/vsock\\\\.c$|^include/linux/virtio_vsock\\\\.h$|^include/uapi/linux/virtio_vsock\\\\.h$|^net/vmw_vsock/virtio_transport\\\\.c$|^net/vmw_vsock/virtio_transport_common\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/vhost/|^include/linux/vhost_iotlb\\\\.h$|^include/uapi/linux/vhost\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/virtio/virtio_balloon\\\\.c$|^include/uapi/linux/virtio_balloon\\\\.h$|^include/linux/balloon_compaction\\\\.h$|^mm/balloon_compaction\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/virtio/virtio_mem\\\\.c$|^include/uapi/linux/virtio_mem\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/fuse/virtio_fs\\\\.c$|^include/uapi/linux/virtio_fs\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^include/uapi/linux/virtio_snd\\\\.h$|^sound/virtio/\"},\n\t\t},\n\t}\n\n\twatchdog = Subsystem{\n\t\tName: \"watchdog\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/ebc-c384_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/mena21_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/menz69_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/realtek_otto_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/sunplus_wdt\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/watchdog/|^include/linux/watchdog\\\\.h$|^include/uapi/linux/watchdog\\\\.h$|^include/trace/events/watchdog\\\\.h$\"},\n\t\t},\n\t}\n\n\twcn36xx = Subsystem{\n\t\tName: \"wcn36xx\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/wcn36xx/\"},\n\t\t},\n\t}\n\n\twireguard = Subsystem{\n\t\tName: \"wireguard\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireguard/\"},\n\t\t},\n\t}\n\n\twireless = Subsystem{\n\t\tName: \"wireless\",\n\t\tSyscalls: []string{\"syz_80211_join_ibss\", \"syz_80211_inject_frame\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/bcma/|^include/linux/bcma/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/admtek/adm8211\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ar5523/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath5k/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath6kl/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/ath9k/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/carl9170/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ath/wil6210/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/atmel/atmel[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/b43/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/b43legacy/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/broadcom/brcm80211/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intel/ipw2x00/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intel/iwlegacy/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intel/iwlwifi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intersil/hostap/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intersil/orinoco/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/intersil/p54/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/mac80211_hwsim\\\\.\\\\[ch\\\\]$|^include/net/mac80211\\\\.h$|^net/mac80211/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/marvell/mwifiex/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/marvell/mwl8k\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/mediatek/mt76/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/mediatek/mt7601u/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/microchip/wilc1000/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/purelifi/plfxlc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/quantenna$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ralink/rt2x00/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ray[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtl818x/rtl8180/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtl818x/rtl8187/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtl8xxxu/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtlwifi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtw88/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/realtek/rtw89/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/rndis_wlan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/rsi/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/ti/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/wl3501[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/zydas/zd1201\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/zydas/zd1211rw/\"},\n\t\t\t{IncludeRegexp: \"^drivers/nfc/trf7970a\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/ssb/|^include/linux/ssb/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/ieee80211\\\\.h$|^include/net/cfg80211\\\\.h$|^include/net/ieee80211_radiotap\\\\.h$|^include/net/iw_handler\\\\.h$|^include/net/wext\\\\.h$|^include/uapi/linux/nl80211\\\\.h$|^include/uapi/linux/wireless\\\\.h$|^net/wireless/\"},\n\t\t\t{IncludeRegexp: \"^include/linux/rfkill\\\\.h$|^include/uapi/linux/rfkill\\\\.h$|^net/rfkill/\"},\n\t\t},\n\t}\n\n\twpan = Subsystem{\n\t\tName: \"wpan\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/adf7242\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/at86rf230\\\\.h$|^drivers/net/ieee802154/atusb\\\\.c$|^drivers/net/ieee802154/atusb\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/ca8210\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/cc2520\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/mcr20a\\\\.c$|^drivers/net/ieee802154/mcr20a\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/mrf24j40\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/ieee802154/|^include/linux/ieee802154\\\\.h$|^include/linux/nl802154\\\\.h$|^include/net/af_ieee802154\\\\.h$|^include/net/cfg802154\\\\.h$|^include/net/ieee802154_netdev\\\\.h$|^include/net/mac802154\\\\.h$|^include/net/nl802154\\\\.h$|^net/ieee802154/|^net/mac802154/\"},\n\t\t\t{IncludeRegexp: \"^include/net/6lowpan\\\\.h$|^net/6lowpan/\"},\n\t\t},\n\t}\n\n\tx25 = Subsystem{\n\t\tName: \"x25\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&net},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wan/hdlc_x25\\\\.c$|^drivers/net/wan/lapbether\\\\.c$|^include/[^/]*/lapb\\\\.h$|^include/net/x25[^/]*$|^include/uapi/linux/x25\\\\.h$|^net/lapb/|^net/x25/\"},\n\t\t},\n\t}\n\n\tx86 = Subsystem{\n\t\tName: \"x86\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&virt},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/paravirt[^/]*\\\\.h$|^arch/[^/]*/kernel/paravirt[^/]*$|^include/linux/hypervisor\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/vmware\\\\.h$|^arch/x86/kernel/cpu/vmware\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/platform$\"},\n\t\t},\n\t}\n\n\tx86drivers = Subsystem{\n\t\tName: \"x86-drivers\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/amd_hsmp\\\\.h$|^arch/x86/include/uapi/asm/amd_hsmp\\\\.h$|^drivers/platform/x86/amd/hsmp\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/intel_punit_ipc\\\\.h$|^drivers/platform/x86/intel/punit_ipc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/include/asm/intel_telemetry\\\\.h$|^drivers/platform/x86/intel/telemetry/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/platform$\"},\n\t\t\t{IncludeRegexp: \"^drivers/char/sonypi\\\\.c$|^drivers/platform/x86/sony-laptop\\\\.c$|^include/linux/sony-laptop\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/hid/surface-hid/\"},\n\t\t\t{IncludeRegexp: \"^drivers/input/touchscreen/silead\\\\.c$|^drivers/platform/x86/touchscreen_dmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/mellanox/|^include/linux/platform_data/mlxreg\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/olpc/|^drivers/platform/x86/|^include/linux/platform_data/x86/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/aggregator/|^drivers/platform/surface/surface_acpi_notify\\\\.c$|^drivers/platform/surface/surface_aggregator_cdev\\\\.c$|^drivers/platform/surface/surface_aggregator_registry\\\\.c$|^include/linux/surface_acpi_notify\\\\.h$|^include/linux/surface_aggregator/|^include/uapi/linux/surface_aggregator/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_aggregator_hub\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_aggregator_tabletsw\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_dtx\\\\.c$|^include/uapi/linux/surface_aggregator/dtx\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_gpe\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_hotplug\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surface_platform_profile\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/surface/surfacepro3_button\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/acer-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/acerhdf\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/adv_swbutton\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/amd/pmc\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/amd/pmf/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/asus-tf103c-dock\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/asus-wireless\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/asus[^/]*\\\\.c$|^drivers/platform/x86/eeepc[^/]*\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/classmate-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/compal-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dcdbas\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios-smm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-smbios\\\\.[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-wmi-privacy\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell-wmi-sysman/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/dell/dell_rbu\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/fujitsu-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/fujitsu-tablet\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/gigabyte-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/gpd-pocket-fan\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/hdaps\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/hp/tc1100-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/ideapad-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/atomisp2/led\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/atomisp2/pm\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/hid\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/int1092/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/ishtp_eclite\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/pmc/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/speed_select_if/|^include/uapi/linux/isst_if\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/tpmi\\\\.c$|^include/linux/intel_tpmi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/uncore-frequency/\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/intel/vbtn\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/lg-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/mlx-platform\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/msi-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/msi-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/nvidia-wmi-ec-backlight\\\\.c$|^include/linux/platform_data/x86/nvidia-wmi-ec-backlight\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/panasonic-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/peaq-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/samsung-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/serial-multi-instantiate\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/system76_acpi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/think-lmi\\\\..$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/thinkpad_acpi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/topstar-laptop\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/toshiba-wmi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/toshiba_acpi\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/toshiba_bluetooth\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/toshiba_haps\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/uv_sysfs\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/wmi\\\\.c$|^include/uapi/linux/wmi\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/platform/x86/x86-android-tablets\\\\.c$\"},\n\t\t\t{IncludeRegexp: \"^drivers/power/supply/surface_battery\\\\.c$|^drivers/power/supply/surface_charger\\\\.c$\"},\n\t\t},\n\t}\n\n\txen = Subsystem{\n\t\tName: \"xen\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/[^/]*/include/asm/xen/swiotlb-xen\\\\.h$|^drivers/xen/swiotlb-xen\\\\.c$|^include/xen/arm/swiotlb-xen\\\\.h$|^include/xen/swiotlb-xen\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^arch/arm/include/asm/xen/|^arch/arm/xen/\"},\n\t\t\t{IncludeRegexp: \"^arch/arm64/include/asm/xen/|^arch/arm64/xen/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/configs/xen\\\\.config$|^arch/x86/include/asm/pvclock-abi\\\\.h$|^arch/x86/include/asm/xen/|^arch/x86/platform/pvh/|^arch/x86/xen/\"},\n\t\t\t{IncludeRegexp: \"^arch/x86/pci/[^/]*xen[^/]*$|^drivers/pci/[^/]*xen[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/[^/]*/xen-[^/]*front\\\\.c$|^drivers/xen/|^include/uapi/xen/|^include/xen/|^kernel/configs/xen\\\\.config$\"},\n\t\t\t{IncludeRegexp: \"^drivers/block/xen[^/]*$|^drivers/block/xen-blkback/\"},\n\t\t\t{IncludeRegexp: \"^drivers/gpu/drm/xen/\"},\n\t\t\t{IncludeRegexp: \"^drivers/net/xen-netback/\"},\n\t\t\t{IncludeRegexp: \"^drivers/scsi/xen-scsifront\\\\.c$|^drivers/xen/xen-scsiback\\\\.c$|^include/xen/interface/io/vscsiif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^drivers/usb/host/xen[^/]*$|^include/xen/interface/io/usbif\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^sound/xen/\"},\n\t\t},\n\t}\n\n\txfs = Subsystem{\n\t\tName: \"xfs\",\n\t\tSyscalls: []string{\"syz_mount_image$xfs\"},\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&fs},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^fs/iomap/|^include/linux/iomap\\\\.h$\"},\n\t\t\t{IncludeRegexp: \"^fs/xfs/|^include/uapi/linux/dqblk_xfs\\\\.h$|^include/uapi/linux/fsmap\\\\.h$\"},\n\t\t},\n\t}\n\n\txtensa = Subsystem{\n\t\tName: \"xtensa\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\", \"[email protected]\"},\n\t\tParents: []*Subsystem{&kernel},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^arch/xtensa/|^drivers/irqchip/irq-xtensa-[^/]*$\"},\n\t\t\t{IncludeRegexp: \"^drivers/spi/spi-xtensa-xtfpga\\\\.c$|^sound/soc/xtensa/xtfpga-i2s\\\\.c$\"},\n\t\t},\n\t}\n\n\tzd1211 = Subsystem{\n\t\tName: \"zd1211\",\n\t\tLists: []string{\"[email protected]\"},\n\t\tMaintainers: []string{\"[email protected]\"},\n\t\tParents: []*Subsystem{&wireless},\n\t\tPathRules: []PathRule{\n\t\t\t{IncludeRegexp: \"^drivers/net/wireless/zydas/zd1211rw/\"},\n\t\t},\n\t}\n\n\treturn []*Subsystem{\n\t\t&_9p, &ac100, &accelerators, &acpi, &acpi4asus, &acpica, &acrn, &actions, &afs, &alpha, &alsa, &amdgfx, &amlogic, &apparmor, &arch, &arm, &armmsm, &asahi, &aspeed, &ath10k, &ath11k, &ath12k, &atm, &audit, &autofs, &axis, &b43, &batman, &bcache, &bfs, &block, &bluetooth, &bpf, &brcm80211, &bridge, &btrfs, &cachefs, &can, &ceph, &cgroups, &chrome, &cifs, &cirrus, &clk, &coda, &coresight, &crypto, &csky, &cxl, &damon, &dccp, &dell, &devicetree, &dm, &dmaengine, &drbd, &dri, &ecryptfs, &edac, &efi, &erofs, &etnaviv, &ext4, &f2fs, &fat, &fbdev, &fpga, &freedreno, &fs, &fscrypt, &fsi, &fsverity, &fuse, &geode, &gfs2, &gpio, &greybus, &hams, &hardening, &hexagon, &hfs, &hippi, &hwmon, &hyperv, &i2c, &i3c, &ia64, &ide, &iio, &imx, &input, &integrity, &intelgfx, &intelgvt, &intelwiredlan, &iouring, &iommu, &ipack, &isdn4linux, &isofs, &jfs, &karma, &kasan, &kernel, &kernfs, &kexec, &keyrings, &kgdb, &kunit, &kvm, &kvmriscv, &kvmarm, &leds, &libertas, &lima, &linux1394, &linuxppc, &linuxpps, &livepatching, &llvm, &loongarch, &lsm, &lvs, &m68k, &malidp, &media, &mediatek, &megaraid, &mhi, &mips, &mjpeg, &mm, &mmc, &modules, &mpi3, &mptfusion, &mptcp, &mtd, &nbd, &net, &netfilter, &nfc, &nfs, &nilfs, &nitro, &nouveau, &ntb, &ntfs, &ntfs3, &nvdimm, &nvme, &ocfs2, &omap, &optee, &openiscsi, &openbmc, &openipmi, &openrisc, &openvswitch, &openwrt, &orangefs, &ossdrivers, &overlayfs, &oxnas, &parisc, &parport, &pci, &perf, &phy, &pm, &ppp, &pvrusb2, &pwm, &qat, &raid, &rcu, &rdma, &rds, &reiserfs, &remoteproc, &renesassoc, &riscv, &rockchip, &rpi, &rttools, &rtc, &rust, &s390, &samsungsoc, &scsi, &sctp, &selinux, &serial, &sgx, &sh, &snpsarc, &sof, &sparclinux, &speakup, &spi, &spice, &squashfs, &staging, &stm32, &sunxi, &target, &tegra, &tipc, &tomoyo, &trace, &uclinux, &udf, &um, &unisoc, &usb, &usbstorage, &video, &virt, &watchdog, &wcn36xx, &wireguard, &wireless, &wpan, &x25, &x86, &x86drivers, &xen, &xfs, &xtensa, &zd1211,\n\t}\n\n}", "func setupDevices(ctx context.Context, c *Container, s *specs.Spec) error {\n\tvar devs []specs.LinuxDevice\n\tdevPermissions := s.Linux.Resources.Devices\n\tif c.HostConfig.Privileged {\n\t\thostDevices, err := devices.HostDevices()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, d := range hostDevices {\n\t\t\tdevs = append(devs, linuxDevice(d))\n\t\t}\n\t\tdevPermissions = []specs.LinuxDeviceCgroup{\n\t\t\t{\n\t\t\t\tAllow: true,\n\t\t\t\tAccess: \"rwm\",\n\t\t\t},\n\t\t}\n\t} else {\n\t\tfor _, deviceMapping := range c.HostConfig.Devices {\n\t\t\tif !opts.ValidateDeviceMode(deviceMapping.CgroupPermissions) {\n\t\t\t\treturn fmt.Errorf(\"%s invalid device mode: %s\", deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)\n\t\t\t}\n\t\t\td, dPermissions, err := devicesFromPath(deviceMapping.PathOnHost, deviceMapping.PathInContainer, deviceMapping.CgroupPermissions)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdevs = append(devs, d...)\n\t\t\tdevPermissions = append(devPermissions, dPermissions...)\n\t\t}\n\t}\n\n\ts.Linux.Devices = append(s.Linux.Devices, devs...)\n\ts.Linux.Resources.Devices = append(s.Linux.Resources.Devices, devPermissions...)\n\treturn nil\n}", "func getNbdDeviceList() ([]string, error) {\n\tif nbdEnabled, _ := checkNbdModule(); !nbdEnabled {\n\t\terr := loadNbd()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcmd := exec.Command(\"bash\", \"-c\", \"ls /dev/nbd*\")\n\toba, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tostr := string(oba)\n\n\t//now split the results on space...\n\n\toarr := strings.Split(ostr, \"\\n\")\n\n\tresArr := []string{}\n\tfor _, item := range oarr {\n\t\tif len(item) > 0 {\n\t\t\tmatched, _ := regexp.Match(`^/dev/nbd\\d+$`, []byte(item))\n\t\t\tif matched {\n\t\t\t\tresArr = append(resArr, item)\n\t\t\t\t//quick chown...\n\t\t\t\tcmd := vutils.Exec.CreateAsyncCommand(\"chown\", false, fmt.Sprintf(\"%d\", UID), item).Sudo()\n\t\t\t\tif err := cmd.StartAndWait(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn resArr, nil\n}", "func (o *PluginConfigLinux) GetDevices() []PluginDevice {\n\tif o == nil {\n\t\tvar ret []PluginDevice\n\t\treturn ret\n\t}\n\n\treturn o.Devices\n}", "func CUDA(index int32) Device {\n return Device{kDLCUDA, index}\n}", "func getVfDevicesByContainer(networkName string) (string, string, error) {\n\tvar rdmadev string\n\n\tcontainerId := getContainerId(networkName)\n\tif containerId == \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"Invalid container id format\")\n\t}\n\n\t// Lock the OS Thread so we don't accidentally switch namespaces\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tnsHandle, err := netns.GetFromDocker(containerId)\n\tif err != nil {\n\t\tfmt.Println(\"Invalid container id: \", containerId)\n\t\treturn \"\", \"\", fmt.Errorf(\"Invalid container id\")\n\t}\n\toriginalHandle, err := netns.Get()\n\tif err != nil {\n\t\tfmt.Println(\"Fail to get handle of current net ns\", err)\n\t\treturn \"\", \"\", fmt.Errorf(\"Fail to get handle of current net ns\")\n\t}\n\tnetns.Set(nsHandle)\n\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\tnetns.Set(originalHandle)\n\t\treturn \"\", \"\", fmt.Errorf(\"Fail to get interfaces\")\n\t}\n\tfor _, iface := range ifaces {\n\t\tif iface.Name == \"lo\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t/* We currently support only first rdma device */\n\t\trdmadev, err = rdmamap.GetRdmaDeviceForNetdevice(iface.Name)\n\t\tif err == nil && rdmadev != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tnetns.Set(originalHandle)\n\treturn \"\", rdmadev, nil\n}", "func (p *Plugin) ListAndWatch(e *pluginapi.Empty, s pluginapi.DevicePlugin_ListAndWatchServer) error {\n\tdevs := make([]*pluginapi.Device, 0)\n\n\t// TODO implement a more sophisticated ways to find the number of GPU available\n\t// TODO register multiple GPUs per node if available\n\tdevs = append(devs, &pluginapi.Device{\n\t\tID: \"gpu\",\n\t\tHealth: pluginapi.Healthy,\n\t})\n\ts.Send(&pluginapi.ListAndWatchResponse{Devices: devs})\n\n\tfor {\n\t\tselect {\n\t\t//TODO implement health monitor and other control mechanisms\n\t\t}\n\t}\n\t// returning a value with this function will unregister the plugin from k8s\n\treturn nil\n}", "func QuotaNvidiaGpu(v int) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldQuotaNvidiaGpu), v))\n\t})\n}", "func PlatformDeviceType_Values() []string {\n\treturn []string{\n\t\tPlatformDeviceTypeGpu,\n\t}\n}", "func QuotaNvidiaGpuIn(vs ...int) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldQuotaNvidiaGpu), v...))\n\t})\n}", "func SupportedAPIs(glMajor, glMinor int, vulkan bool) []APIType {\n\tvar apis []APIType\n\tif glMajor >= 2 {\n\t\tapis = append(apis, GLES2)\n\t}\n\tif glMajor >= 3 {\n\t\tapis = append(apis, GLES3)\n\t\tif glMajor > 3 || glMinor >= 1 {\n\t\t\tapis = append(apis, GLES31)\n\t\t}\n\t}\n\tif vulkan {\n\t\tapis = append(apis, VK)\n\t}\n\treturn apis\n}", "func getSerialDevices() ([]string, error) {\n\t//log.Println(\"getting serial devices\")\n\tdevices, err := ioutil.ReadDir(\"/dev/serial/by-id\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\tdeviceList := make([]string, len(devices))\n\tfor index, deviceLink := range devices {\n\t\t//log.Println(\"Found device: \", deviceLink.Name())\n\t\tabs, err := filepath.EvalSymlinks(\"/dev/serial/by-id/\" + deviceLink.Name())\n\t\t//log.Print(\"Absolute Device: \")\n\t\t//log.Println(abs)\n\t\tdeviceList[index] = abs\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn deviceList, nil\n}", "func (sys *Sys) GetDeviceList() ([]string, error) {\n\tlog.Debugln(\"GetDeviceList ENTER\")\n\n\tlist := []string{}\n\n\toutputCmd := \"fdisk -l | grep \\\\/dev\\\\/\"\n\toutput, err := sys.run.CommandOutput(outputCmd)\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to get device list. Err:\", err)\n\t\tlog.Debugln(\"GetDeviceList LEAVE\")\n\t\treturn list, err\n\t}\n\n\tbuffer := bytes.NewBufferString(output)\n\tfor {\n\t\tstr, err := buffer.ReadString('\\n')\n\n\t\tneedles, errRegex := sys.str.RegexMatch(str, \"Disk (/dev/.*): \")\n\t\tif errRegex != nil {\n\t\t\tlog.Warnln(\"RegexMatch Failed. Err:\", err)\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif len(needles) != 2 {\n\t\t\tfmt.Println(\"Incorrect output size:\", len(needles))\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tdevice := needles[1]\n\t\tlog.Debugln(\"Device Found:\", device)\n\n\t\tlist = append(list, device)\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Debugln(\"GetDeviceList Succeeded. Device Count:\", len(list))\n\tlog.Debugln(\"GetDeviceList LEAVE\")\n\n\treturn list, nil\n}", "func (nc NvmeController) Free() (tb uint64) {\n\tfor _, d := range nc.SmdDevices {\n\t\ttb += d.AvailBytes\n\t}\n\treturn\n}", "func DisplaySupportedDrivers() string {\n\tvar sd []string\n\tfor _, d := range SupportedDrivers() {\n\t\tif registry.Driver(d).Priority == registry.Experimental {\n\t\t\tsd = append(sd, d+\" (experimental)\")\n\t\t\tcontinue\n\t\t}\n\t\tsd = append(sd, d)\n\t}\n\treturn strings.Join(sd, \", \")\n}", "func GetDevices(request *Request) (devices Almanac, err error) {\n\tqueryList := make([]Query, 0)\n\tattachments := make(map[string]string)\n\tattachments[\"properties\"] = \"1\"\n\tattachments[\"projects\"] = \"1\"\n\tqueryList = append(queryList, Query{\"map\", \"attachments\", attachments})\n\tqueryList = append(queryList, Query{\"string\", \"limit\", \"100\"})\n\trequest.SetMethod(\"almanac.device.search\")\n\trequest.AddValues(queryList)\n\tresp, err := SendRequest(request)\n\terr = json.Unmarshal(resp, &devices)\n\treturn devices, err\n}", "func AddGpuConfigs(vm *gce.Instance) *gce.Instance {\n\tvm.Gpu = true\n\tvm.MachineType = gce.MACHINE_TYPE_STANDARD_8 // Max 8 CPUs when using a GPU.\n\tvm.MaintenancePolicy = gce.MAINTENANCE_POLICY_TERMINATE // Required for GPUs.\n\treturn vm\n}", "func (d *DeviceProp) ConcurrentKernels() int32 {\n\treturn (int32)(d.concurrentKernels)\n}", "func (s *gPUQuotaLister) List(selector labels.Selector) (ret []*v1alpha1.GPUQuota, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.GPUQuota))\n\t})\n\treturn ret, err\n}", "func GetDevices(c *gin.Context) {\n\tdevices, err := database.GetAllDevices(c)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, devices)\n\t}\n}", "func (m *AppVulnerabilityTask) GetManagedDevices()([]AppVulnerabilityManagedDeviceable) {\n val, err := m.GetBackingStore().Get(\"managedDevices\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]AppVulnerabilityManagedDeviceable)\n }\n return nil\n}" ]
[ "0.73773146", "0.7123039", "0.7023056", "0.6901569", "0.6864932", "0.6853776", "0.68265855", "0.67780554", "0.6508854", "0.64963824", "0.6262117", "0.6234437", "0.6191978", "0.6002187", "0.5865044", "0.5861507", "0.58297217", "0.580825", "0.5808116", "0.5734605", "0.57278997", "0.56872386", "0.56190926", "0.5590629", "0.5571828", "0.55669117", "0.5547231", "0.55346096", "0.5460562", "0.5452702", "0.5408852", "0.53898805", "0.5364553", "0.5353988", "0.53522027", "0.5347619", "0.5295012", "0.52853996", "0.5284855", "0.526747", "0.52465004", "0.5241858", "0.5214347", "0.5213368", "0.5208345", "0.52019787", "0.5198379", "0.51983637", "0.51899", "0.5168738", "0.5165659", "0.5160146", "0.51016307", "0.5097046", "0.5080462", "0.5079838", "0.507938", "0.50713134", "0.50679", "0.50505465", "0.5040349", "0.50303984", "0.50303984", "0.5025262", "0.5020506", "0.50010705", "0.50007457", "0.49891633", "0.49700552", "0.49609923", "0.49569744", "0.49532694", "0.4952357", "0.49504218", "0.4942958", "0.4934584", "0.49308595", "0.49303612", "0.49255508", "0.4923856", "0.49230668", "0.49178597", "0.49144807", "0.49137437", "0.48965645", "0.48872286", "0.4886753", "0.4885692", "0.48795474", "0.4874584", "0.48708278", "0.48652002", "0.48646128", "0.48603842", "0.48586005", "0.48514044", "0.48457196", "0.48450673", "0.48373267", "0.48295256" ]
0.7898917
0
ObjMatchPointcut returns true if obj matches the pointcut. current implementation is very naive: just checks regexp for types.Func.FullName() TODO: support interface pointcut
func ObjMatchPointcut(prog *loader.Program, id *ast.Ident, obj types.Object, pointcut aspect.Pointcut) bool { fn, ok := obj.(*types.Func) if ok { return fnObjMatchPointcutByRegexp(fn, pointcut) } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pattern targetPattern) Match(object *metav1.ObjectMeta) bool {\n\treturn object.Name == pattern.name && pattern.namespace.MatchString(object.Namespace)\n}", "func (oe objectExpectation) matches(obj interface{}) bool {\n\tif oe.val == nil || obj == nil {\n\t\treturn oe.val == nil && obj == nil\n\t}\n\n\tparamBuf1 := new(bytes.Buffer)\n\toe.val.MarshalCBOR(paramBuf1) // nolint: errcheck\n\tmarshaller, ok := obj.(cbor.Marshaler)\n\tif !ok {\n\t\treturn false\n\t}\n\tparamBuf2 := new(bytes.Buffer)\n\tif marshaller != nil {\n\t\tmarshaller.MarshalCBOR(paramBuf2) // nolint: errcheck\n\t}\n\treturn bytes.Equal(paramBuf1.Bytes(), paramBuf2.Bytes())\n}", "func matchAspects(object *topoapi.Object, aspects []string) bool {\n\tfor i := range aspects {\n\t\tif _, ok := object.Aspects[aspects[i]]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (Any) IsMatch(ctx runtime.PatternContext) bool {\n\treturn true\n}", "func (Any) IsMatch(ctx runtime.PatternContext) bool {\n\treturn true\n}", "func isAspectMatch(aspectExpress, location string) bool {\n\t// regular\n\tpattern, err := regexp.Compile(aspectExpress)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn pattern.MatchString(location)\n}", "func (m *Matcher) Match(actual interface{}) (success bool, err error) {\n\t// Nil checks required first here for:\n\t// 1) Nil equality which returns true\n\t// 2) One object nil which returns an error\n\n\tif util.IsNil(actual) && util.IsNil(m.original) {\n\t\treturn true, nil\n\t}\n\tif util.IsNil(actual) || util.IsNil(m.original) {\n\t\treturn false, fmt.Errorf(\"can not compare an object with a nil. original %v , actual %v\", m.original, actual)\n\t}\n\n\t// Calculate diff returns a json diff between the two objects.\n\tm.diff, err = m.calculateDiff(actual)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn bytes.Equal(m.diff, []byte(\"{}\")), nil\n}", "func (o *MakeStdUpdateArgsObjMatcher) Matches(arg interface{}) bool {\n\tassert := assert.New(o.t)\n\tswitch x := arg.(type) {\n\tcase *int32: // version\n\t\treturn assert.Equal(o.ver, *x, \"MSUA version match\")\n\tcase string: // id\n\t\treturn assert.Equal(o.id, x, \"MSUA id match\")\n\tcase [centrald.NumActionTypes][]string:\n\t\treturn assert.Equal(o.fields, x, \"MSUA fields match\")\n\tdefault: // object - only match type\n\t\treturn assert.IsType(o.obj, x, \"MSUA object type match\")\n\t}\n}", "func fnMatch(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 2 {\n\t\tctx.Log().Error(\"error_type\", \"func_match\", \"op\", \"match\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to match function\"), \"match\", params})\n\t\treturn nil\n\t}\n\treg, err := regexp.Compile(extractStringParam(params[1]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_match\", \"op\", \"match\", \"cause\", \"invalid_regex\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"invalid regex in call to match function: %s\", err.Error()), \"match\", params})\n\t\treturn nil\n\t}\n\treturn reg.MatchString(extractStringParam(params[0]))\n}", "func (unit *Unit) FindFunc(name string, params []*TypeObject) (IObject, bool) {\n\tvar isStruct bool\n\tkey := npFunc + name\n\tkeyAny := key\n\tfor _, v := range params {\n\t\tif v == nil {\n\t\t\treturn nil, false\n\t\t}\n\t\tparName := v.GetName()\n\t\tkey += npFunc + parName\n\t\tif strings.HasPrefix(parName, `arr.`) {\n\t\t\tkeyAny += npFunc + `arr*`\n\t\t} else if strings.HasPrefix(parName, `map.`) {\n\t\t\tkeyAny += npFunc + `map*`\n\t\t} else {\n\t\t\tkeyAny += npFunc + parName\n\t\t}\n\t\tisStruct = isStruct || v.Custom != nil\n\t}\n\tif obj := unit.FindObj(key); obj != nil {\n\t\treturn obj, false\n\t}\n\tif key != keyAny {\n\t\tif obj := unit.FindObj(keyAny); obj != nil {\n\t\t\treturn obj, false\n\t\t}\n\t}\n\tif isStruct {\n\t\tkey = npFunc + name\n\t\tfor _, v := range params {\n\t\t\tvar parName string\n\t\t\tif v.Custom != nil {\n\t\t\t\tparName = `struct`\n\t\t\t} else {\n\t\t\t\tparName = v.GetName()\n\t\t\t}\n\t\t\tkey += npFunc + parName\n\t\t}\n\t\tif obj := unit.FindObj(key); obj != nil {\n\t\t\treturn obj, false\n\t\t}\n\t}\n\treturn unit.FindObj(npVariadic + name), true\n}", "func (p *Package) InvocationsOf(obj types.Object) []Invocation {\n\tfn, _ := obj.(*types.Func)\n\tif fn == nil {\n\t\tpanic(fmt.Sprintf(\"object %[1]s is not *types.Func (%[1]T)\", obj))\n\t}\n\n\tvar ret []Invocation\n\tfor _, use := range p.LifetimeOf(obj).Uses {\n\t\tancs := p.AncestorsOf(use)\n\n\t\tvar invocant types.Object\n\t\tif sel, _ := ancs.Peek().(*ast.SelectorExpr); sel != nil {\n\t\t\tswitch x := sel.X.(type) {\n\t\t\tcase *ast.SelectorExpr:\n\t\t\t\tinvocant = p.ObjectOf(x.Sel)\n\t\t\tcase *ast.Ident:\n\t\t\t\tinvocant = p.ObjectOf(x)\n\t\t\t}\n\n\t\t\tancs.Pop()\n\t\t}\n\n\t\tcall, _ := ancs.Peek().(*ast.CallExpr)\n\t\tif call == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, Invocation{\n\t\t\tInvocant: invocant,\n\t\t\tArgs: call.Args,\n\t\t\tCall: call,\n\t\t})\n\t}\n\n\treturn ret\n}", "func Contains(obj interface{}, target interface{}) (bool, error) {\n\ttargetValue := reflect.ValueOf(target)\n\tswitch reflect.TypeOf(target).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < targetValue.Len(); i++ {\n\t\t\tif targetValue.Index(i).Interface() == obj {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, errors.New(\"not in\")\n}", "func (r *MethodCallRetrier) objectIsAPointer(object interface{}) bool {\n\treturn reflect.ValueOf(object).Kind() == reflect.Ptr\n}", "func ObjectIf(vm *VM, target, locals Interface, msg *Message) Interface {\n\tc, ok := CheckStop(msg.EvalArgAt(vm, locals, 0), NoStop)\n\tif !ok {\n\t\treturn c\n\t}\n\tif vm.AsBool(c) {\n\t\tif len(msg.Args) < 2 {\n\t\t\t// Return true to support `if(condition) then(action)`.\n\t\t\treturn vm.True\n\t\t}\n\t\treturn msg.EvalArgAt(vm, locals, 1)\n\t}\n\tif len(msg.Args) < 3 {\n\t\t// Return false to support `if(c, message) elseif(c, message)`.\n\t\treturn vm.False\n\t}\n\t// Even if only two arguments are supplied, this will evaluate to vm.Nil.\n\treturn msg.EvalArgAt(vm, locals, 2)\n}", "func (c *completer) objChainMatches(cand *candidate, chain []types.Object) bool {\n\t// For example, when completing:\n\t//\n\t// foo.ba<>\n\t//\n\t// If we are considering the deep candidate \"bar.baz\", cand is baz,\n\t// objChain is [foo] and deepChain is [bar]. We would match the\n\t// chain [foo, bar, baz].\n\tif len(chain) != len(c.inference.objChain)+len(cand.path)+1 {\n\t\treturn false\n\t}\n\n\tif chain[len(chain)-1] != cand.obj {\n\t\treturn false\n\t}\n\n\tfor i, o := range c.inference.objChain {\n\t\tif chain[i] != o {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor i, o := range cand.path {\n\t\tif chain[i+len(c.inference.objChain)] != o {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func matchType(object *topoapi.Object, types []topoapi.Object_Type) bool {\n\tif len(types) != 0 {\n\t\tfor i := range types {\n\t\t\tif object.Type == types[i] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool {\n\tif n.Obj != nil {\n\t\treturn n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun\n\t}\n\n\t// Try to resolve unresolved identifiers using other files in same package\n\tfor _, file := range c.PkgFiles {\n\t\tif node, ok := file.Scope.Objects[n.String()]; ok {\n\t\t\treturn node.Kind != ast.Var && node.Kind != ast.Fun\n\t\t}\n\t}\n\treturn false\n}", "func (a AnyArgument) Match(v driver.Value) bool {\n\treturn true\n}", "func (a AnyArgument) Match(v driver.Value) bool {\n\treturn true\n}", "func (self *Rectangle) ContainsPointI(args ...interface{}) bool{\n return self.Object.Call(\"containsPoint\", args).Bool()\n}", "func AnyOf(fn ...PredicateFn) PredicateFn {\n\treturn func(obj runtime.Object) bool {\n\t\tfor _, f := range fn {\n\t\t\tif f(obj) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}", "func (acl AccessControlDomainRegexBasic) IsMatch(_ Subject, object Object) (match bool) {\n\treturn acl.Pattern.MatchString(object.Domain)\n}", "func (m HaveJSONPointerMatcher) Match(actual interface{}) (bool, error) {\n\n\tswitch t := actual.(type) {\n\tdefault:\n\t\treturn false, fmt.Errorf(\"not a Data object. Have you done unstructured.Parse[JSON|YAML](...)?\")\n\tcase unstructured.Data:\n\t\treturn t.HasPointer(m.p)\n\t}\n}", "func (util copyHandlerUtil) matchBlobNameAgainstPattern(pattern string, blobName string, recursive bool) bool {\n\tif recursive {\n\t\treturn util.blobNameMatchesThePattern(pattern, blobName)\n\t}\n\treturn util.blobNameMatchesThePatternComponentWise(pattern, blobName)\n}", "func (acl AccessControlDomainRegex) IsMatch(subject Subject, object Object) (match bool) {\n\tmatches := acl.Pattern.FindAllStringSubmatch(object.Domain, -1)\n\tif matches == nil {\n\t\treturn false\n\t}\n\n\tif acl.SubexpNameUser != -1 && !strings.EqualFold(subject.Username, matches[0][acl.SubexpNameUser]) {\n\t\treturn false\n\t}\n\n\tif acl.SubexpNameGroup != -1 && !utils.IsStringInSliceFold(matches[0][acl.SubexpNameGroup], subject.Groups) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (a *Arg) Match(arg string) bool {\n\tswitch {\n\tcase a.ShortName != \"\" && a.ShortName == arg:\n\t\treturn true\n\tcase a.LongName != \"\" && a.LongName == arg:\n\t\treturn true\n\t}\n\treturn false\n}", "func (acl AccessControlDomain) IsMatch(subject Subject, object Object) (match bool) {\n\tswitch {\n\tcase acl.Wildcard:\n\t\treturn strings.HasSuffix(object.Domain, acl.Name)\n\tcase acl.UserWildcard:\n\t\treturn object.Domain == fmt.Sprintf(\"%s.%s\", subject.Username, acl.Name)\n\tcase acl.GroupWildcard:\n\t\tprefix, suffix := domainToPrefixSuffix(object.Domain)\n\n\t\treturn suffix == acl.Name && utils.IsStringInSliceFold(prefix, subject.Groups)\n\tdefault:\n\t\treturn object.Domain == acl.Name\n\t}\n}", "func (s *ASAEngine) GetMatchingFuncByFormationObjectType(objType graphql.FormationObjectType) (MatchingFunc, error) {\n\tswitch objType {\n\tcase graphql.FormationObjectTypeRuntime:\n\t\treturn s.isASAMatchingRuntime, nil\n\tcase graphql.FormationObjectTypeRuntimeContext:\n\t\treturn s.isASAMatchingRuntimeContext, nil\n\t}\n\treturn nil, errors.Errorf(\"unexpected formation object type %q\", objType)\n}", "func (obj GoObject) ObjectMethod(name string) Function {\n\tval := reflect.ValueOf(obj.val)\n\tmethod := val.MethodByName(name)\n\tif method.IsValid() {\n\t\treturn GoFunc{val: method.Interface()}\n\t} else {\n\t\treturn Function(nil)\n\t}\n}", "func isFunc(obj reflect.Value) bool {\n\t// Zero value reflected: not a valid function\n\tif obj == (reflect.Value{}) {\n\t\treturn false\n\t}\n\n\tif obj.Type().Kind() != reflect.Func {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (r RuleFunc) Match(src net.Addr) bool {\n\treturn r(src)\n}", "func (f *Fuzzer) Fuzz(obj interface{}) {\n\tv := reflect.ValueOf(obj)\n\tif v.Kind() != reflect.Ptr {\n\t\tpanic(\"needed ptr!\")\n\t}\n\tv = v.Elem()\n\tf.fuzzWithContext(v, 0)\n}", "func (r *PodsIncomingReflector) isAllowed(ctx context.Context, obj interface{}) bool {\n\tif value, ok := vkContext.IncomingMethod(ctx); ok && value == vkContext.IncomingDeleted {\n\t\treturn true\n\t}\n\n\tpod, ok := obj.(*corev1.Pod)\n\tif !ok {\n\t\tklog.Error(\"cannot convert obj to pod\")\n\t\treturn false\n\t}\n\tkey := r.Keyer(pod.Namespace, pod.Name)\n\t_, ok = reflectors.Blacklist[apimgmt.Pods][key]\n\tif ok {\n\t\tklog.V(5).Infof(\"event for pod %v blacklisted\", key)\n\t}\n\treturn !ok\n}", "func exportedFrom(obj types.Object, pkg *types.Package) bool {\n\tswitch obj := obj.(type) {\n\tcase *types.Func:\n\t\treturn obj.Exported() && obj.Pkg() == pkg ||\n\t\t\tobj.Type().(*types.Signature).Recv() != nil\n\tcase *types.Var:\n\t\treturn obj.Exported() && obj.Pkg() == pkg ||\n\t\t\tobj.IsField()\n\tcase *types.TypeName, *types.Const:\n\t\treturn true\n\t}\n\treturn false // Nil, Builtin, Label, or PkgName\n}", "func (self *Rectangle) ContainsI(args ...interface{}) bool{\n return self.Object.Call(\"contains\", args).Bool()\n}", "func Match(op aof.Operation, filter Filter, inverse bool) bool {\n\trCode := false\n\tif inverse {\n\t\trCode = true\n\t}\n\tif filter.Command != nil && filter.Command.FindStringIndex(strings.ToUpper(op.Command)) == nil {\n\t\treturn rCode\n\t}\n\tif filter.SubOp != nil && filter.SubOp.FindStringIndex(strings.ToUpper(op.SubOp)) == nil {\n\t\treturn rCode\n\t}\n\tif filter.Key != nil && filter.Key.FindStringIndex(op.Key) == nil {\n\t\treturn rCode\n\t}\n\tif filter.Parameter == nil {\n\t\treturn !rCode\n\t}\n\tfor _, p := range op.Arguments {\n\t\tif filter.Parameter.FindStringIndex(p) != nil {\n\t\t\treturn !rCode\n\t\t}\n\t}\n\treturn rCode\n}", "func (m scanOpMatcher) Matches(x interface{}) bool {\n\top, ok := x.(*ScanOp)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, field := range op.fieldsToRead {\n\t\tif !m.fields[field] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn op.limit == m.limit && op.token == m.token && reflect.TypeOf(op.object).Elem() == m.typ\n}", "func (c KubernetesDefaultRouter) isOwnedByCanary(obj interface{}, name string) (bool, bool) {\n\tobject, ok := obj.(metav1.Object)\n\tif !ok {\n\t\treturn false, false\n\t}\n\n\townerRef := metav1.GetControllerOf(object)\n\tif ownerRef == nil {\n\t\treturn false, false\n\t}\n\n\tif ownerRef.Kind != flaggerv1.CanaryKind {\n\t\treturn false, false\n\t}\n\n\treturn true, ownerRef.Name == name\n}", "func (r *DefaultObjectAccessControl) matcher(c *Client) func([]byte) bool {\n\treturn func(b []byte) bool {\n\t\tcr, err := unmarshalDefaultObjectAccessControl(b, c)\n\t\tif err != nil {\n\t\t\tc.Config.Logger.Warning(\"failed to unmarshal provided resource in matcher.\")\n\t\t\treturn false\n\t\t}\n\t\tnr := r.urlNormalized()\n\t\tncr := cr.urlNormalized()\n\t\tc.Config.Logger.Infof(\"looking for %v\\nin %v\", nr, ncr)\n\n\t\tif nr.Project == nil && ncr.Project == nil {\n\t\t\tc.Config.Logger.Info(\"Both Project fields null - considering equal.\")\n\t\t} else if nr.Project == nil || ncr.Project == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Project field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Project != *ncr.Project {\n\t\t\treturn false\n\t\t}\n\t\tif nr.Bucket == nil && ncr.Bucket == nil {\n\t\t\tc.Config.Logger.Info(\"Both Bucket fields null - considering equal.\")\n\t\t} else if nr.Bucket == nil || ncr.Bucket == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Bucket field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Bucket != *ncr.Bucket {\n\t\t\treturn false\n\t\t}\n\t\tif nr.Entity == nil && ncr.Entity == nil {\n\t\t\tc.Config.Logger.Info(\"Both Entity fields null - considering equal.\")\n\t\t} else if nr.Entity == nil || ncr.Entity == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Entity field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Entity != *ncr.Entity {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n}", "func (IsAccountActor) IsMatch(ctx runtime.PatternContext) bool {\n\treturn builtin.IsAccountActor(ctx.CallerCode())\n}", "func (c OneCase) PropertyMatch(property string) bool { return c.Property == property }", "func Contain(target interface{}, obj interface{}) bool {\n\ttargetValue := reflect.ValueOf(target)\n\tswitch reflect.TypeOf(target).Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tfor i := 0; i < targetValue.Len(); i++ {\n\t\t\tif targetValue.Index(i).Interface() == obj {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\tcase reflect.Map:\n\t\tif targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func VerifyReflection(body, payload string) bool {\n\tif strings.Contains(body, payload) {\n\t\treturn true\n\t} \n\treturn false\n}", "func (p AddressIn) IsMatch(ctx runtime.PatternContext) bool {\n\tfor _, a := range p.Addresses {\n\t\tif a == ctx.CallerAddr() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Contain(obj interface{}, element interface{}) bool {\n\ttypeOfObj := reflect.TypeOf(obj)\n\tvalueOfObj := reflect.ValueOf(obj)\n\ttypeOfElement := reflect.TypeOf(element)\n\tswitch typeOfObj.Kind() {\n\tcase reflect.Array, reflect.Slice:\n\t\tif valueOfObj.Len() == 0 {\n\t\t\treturn false\n\t\t}\n\t\tif typeOfElement.Kind() == reflect.Array || typeOfElement.Kind() == reflect.Slice {\n\t\t\treturn CheckArrContainNested(obj, element)\n\t\t}\n\t\treturn CheckArrContainSimple(obj, element)\n\tcase reflect.String:\n\t\tif typeOfElement.Kind() != reflect.String {\n\t\t\tpanic(\"make sure element is same type with Obj | String\")\n\t\t}\n\t\tvalueOfObj := reflect.ValueOf(obj).String()\n\t\tvalueOfElement := reflect.ValueOf(element).String()\n\t\treturn strings.Index(valueOfObj, valueOfElement) != -1\n\tcase reflect.Struct:\n\t\tfor i := 0; i < valueOfObj.NumField(); i++ {\n\t\t\tfield := valueOfObj.Field(i)\n\t\t\tvalueOfField := field.Interface()\n\t\t\tif typeOfElement.Kind() != field.Type().Kind() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch typeOfElement.Kind() {\n\t\t\tcase reflect.Int:\n\t\t\t\tif reflect.ValueOf(valueOfField).Int() == reflect.ValueOf(element).Int() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\tif reflect.ValueOf(valueOfField).Uint() == reflect.ValueOf(element).Uint() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tif reflect.ValueOf(valueOfField).Float() == reflect.ValueOf(element).Float() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tif reflect.ValueOf(valueOfField).String() == reflect.ValueOf(element).String() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tpanic(\"make sure obj is array or string or struct\")\n\t}\n\n\treturn false\n}", "func (m *matcher) matchExpr(x, y ast.Expr) bool {\n\tx = unparen(x)\n\ty = unparen(y)\n\n\t// Is x a wildcard? (a reference to a 'before' parameter)\n\tif xobj, ok := m.wildcardObj(x); ok {\n\t\treturn m.matchWildcard(xobj, y)\n\t}\n\n\t// Object identifiers (including pkg-qualified ones)\n\t// are handled semantically, not syntactically.\n\txobj := isRef(x, m.infoX)\n\tyobj := isRef(y, m.infoY)\n\tif xobj != nil {\n\t\treturn xobj == yobj\n\t}\n\tif yobj != nil {\n\t\treturn false\n\t}\n\n\t// TODO(adonovan): audit: we cannot assume these ast.Exprs\n\t// contain non-nil pointers. e.g. ImportSpec.Name may be a\n\t// nil *ast.Ident.\n\n\tif reflect.TypeOf(x) != reflect.TypeOf(y) {\n\t\treturn false\n\t}\n\tswitch x := x.(type) {\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unhandled AST node type: %T\", x))\n\n\tcase *ast.Ident:\n\t\tlog.Fatalf(\"unexpected Ident: %s\", astString(m.fset, x))\n\t\tpanic(\"unreachable\")\n\n\tcase *ast.BasicLit:\n\t\ty := y.(*ast.BasicLit)\n\t\txval := constant.MakeFromLiteral(x.Value, x.Kind, 0)\n\t\tyval := constant.MakeFromLiteral(y.Value, y.Kind, 0)\n\t\treturn constant.Compare(xval, token.EQL, yval)\n\n\tcase *ast.FuncLit:\n\t\t// func literals (and thus statement syntax) never match.\n\t\treturn false\n\n\tcase *ast.CompositeLit:\n\t\ty := y.(*ast.CompositeLit)\n\t\treturn (x.Type == nil) == (y.Type == nil) &&\n\t\t\t(x.Type == nil || m.matchType(x.Type, y.Type)) &&\n\t\t\tm.matchExprs(x.Elts, y.Elts)\n\n\tcase *ast.SelectorExpr:\n\t\ty := y.(*ast.SelectorExpr)\n\t\treturn m.matchSelectorExpr(x, y) &&\n\t\t\tm.infoX.Selections[x].Obj() == m.infoY.Selections[y].Obj()\n\n\tcase *ast.IndexExpr:\n\t\ty := y.(*ast.IndexExpr)\n\t\treturn m.matchExpr(x.X, y.X) &&\n\t\t\tm.matchExpr(x.Index, y.Index)\n\n\tcase *ast.SliceExpr:\n\t\ty := y.(*ast.SliceExpr)\n\t\treturn m.matchExpr(x.X, y.X) &&\n\t\t\tm.matchExpr(x.Low, y.Low) &&\n\t\t\tm.matchExpr(x.High, y.High) &&\n\t\t\tm.matchExpr(x.Max, y.Max) &&\n\t\t\tx.Slice3 == y.Slice3\n\n\tcase *ast.TypeAssertExpr:\n\t\ty := y.(*ast.TypeAssertExpr)\n\t\treturn m.matchExpr(x.X, y.X) &&\n\t\t\tm.matchType(x.Type, y.Type)\n\n\tcase *ast.CallExpr:\n\t\ty := y.(*ast.CallExpr)\n\t\tmatch := m.matchExpr // function call\n\t\tif m.infoX.Types[x.Fun].IsType() {\n\t\t\tmatch = m.matchType // type conversion\n\t\t}\n\t\treturn x.Ellipsis.IsValid() == y.Ellipsis.IsValid() &&\n\t\t\tmatch(x.Fun, y.Fun) &&\n\t\t\tm.matchExprs(x.Args, y.Args)\n\n\tcase *ast.StarExpr:\n\t\ty := y.(*ast.StarExpr)\n\t\treturn m.matchExpr(x.X, y.X)\n\n\tcase *ast.UnaryExpr:\n\t\ty := y.(*ast.UnaryExpr)\n\t\treturn x.Op == y.Op &&\n\t\t\tm.matchExpr(x.X, y.X)\n\n\tcase *ast.BinaryExpr:\n\t\ty := y.(*ast.BinaryExpr)\n\t\treturn x.Op == y.Op &&\n\t\t\tm.matchExpr(x.X, y.X) &&\n\t\t\tm.matchExpr(x.Y, y.Y)\n\n\tcase *ast.KeyValueExpr:\n\t\ty := y.(*ast.KeyValueExpr)\n\t\treturn m.matchExpr(x.Key, y.Key) &&\n\t\t\tm.matchExpr(x.Value, y.Value)\n\t}\n}", "func (s *sqlStrFormat) constObject(e ast.Expr, c *gosec.Context) bool {\n\tn, ok := e.(*ast.Ident)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif n.Obj != nil {\n\t\treturn n.Obj.Kind == ast.Con\n\t}\n\n\t// Try to resolve unresolved identifiers using other files in same package\n\tfor _, file := range c.PkgFiles {\n\t\tif node, ok := file.Scope.Objects[n.String()]; ok {\n\t\t\treturn node.Kind == ast.Con\n\t\t}\n\t}\n\treturn false\n}", "func (obj *match) HasPattern() bool {\n\treturn obj.pattern != \"\"\n}", "func isHandlerFuncInResource(m string, r Resource) (func(c context.Context, w http.ResponseWriter, r *http.Request), bool) {\n\tname := strings.Title(strings.ToLower(m))\n\tmethod := reflect.ValueOf(r).MethodByName(name)\n\tif !method.IsValid() {\n\t\treturn nil, false\n\t}\n\n\tfn, ok := method.Interface().(func(c context.Context, w http.ResponseWriter, r *http.Request))\n\treturn fn, ok\n}", "func (unit *Unit) FindObj(fullName string) IObject {\n\tif ind, ok := unit.NameSpace[fullName]; ok {\n\t\treturn unit.VM.Objects[ind&NSIndex]\n\t}\n\treturn nil\n}", "func (r *MethodCallRetrier) callMethodOnObject(object interface{}, methodName string, args []interface{}) []reflect.Value {\n\tvar method reflect.Value\n\n\tif r.objectIsAPointer(object) {\n\t\tmethod = reflect.ValueOf(object).MethodByName(methodName)\n\t} else {\n\t\tmethod = reflect.New(reflect.TypeOf(object)).MethodByName(methodName)\n\t}\n\n\targuments := make([]reflect.Value, method.Type().NumIn())\n\n\tfor i := 0; i < method.Type().NumIn(); i++ {\n\t\targuments[i] = reflect.ValueOf(args[i])\n\t}\n\n\treturn method.Call(arguments)\n}", "func (f TransformObjFunc) Func() TransformFunc {\n\treturn TransformFunc(func(n nodes.Node) (nodes.Node, bool, error) {\n\t\tobj, ok := n.(nodes.Object)\n\t\tif !ok {\n\t\t\treturn n, false, nil\n\t\t}\n\t\tnn, ok, err := f(obj)\n\t\tif err != nil {\n\t\t\treturn n, false, err\n\t\t} else if !ok {\n\t\t\treturn n, false, nil\n\t\t}\n\t\treturn nn, ok, nil\n\t})\n}", "func Match(regx string, arg string) bool {\n\tmatched, err := regexp.MatchString(\"^(\"+regx+\")$\", arg)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn matched\n}", "func matchFuncType(src, test reflect.Type) error {\n\tvar errorStr string\n\n\tsourceKind := src.Kind()\n\ttestKind := test.Kind()\n\tif sourceKind != reflect.Slice {\n\t\terrorStr = fmt.Sprintf(\"Expected type (slice) but received src of type (%v)\\n\", sourceKind)\n\t} else if testKind != reflect.Func {\n\t\terrorStr = fmt.Sprintf(\"Expected type (func) but received testFunc of type (%v)\\n\", testKind)\n\t}\n\n\ttestOutput := test.Out(0).Kind()\n\ttestInput := test.In(0)\n\telemType := src.Elem()\n\tif test.NumIn() != 1 {\n\t\terrorStr = \"Expected testFunc to have 1 input\\n\"\n\t} else if testInput != elemType {\n\t\terrorStr = fmt.Sprintf(\"Received slice of type (%v), but testFunc expects type (%v)\", elemType, testInput)\n\t} else if test.NumOut() != 1 || testOutput != reflect.Bool {\n\t\terrorStr = \"Expected func to have 1 return of type (bool)\\n\"\n\t}\n\n\tif errorStr != \"\" {\n\t\treturn errors.New(errorStr)\n\t}\n\n\treturn nil\n}", "func matchFuncType(src, test reflect.Type) error {\n\tvar errorStr string\n\n\tsourceKind := src.Kind()\n\ttestKind := test.Kind()\n\tif sourceKind != reflect.Slice {\n\t\terrorStr = fmt.Sprintf(\"Expected type (slice) but received src of type (%v)\\n\", sourceKind)\n\t} else if testKind != reflect.Func {\n\t\terrorStr = fmt.Sprintf(\"Expected type (func) but received testFunc of type (%v)\\n\", testKind)\n\t}\n\n\ttestOutput := test.Out(0).Kind()\n\ttestInput := test.In(0)\n\telemType := src.Elem()\n\tif test.NumIn() != 1 {\n\t\terrorStr = \"Expected testFunc to have 1 input\\n\"\n\t} else if testInput != elemType {\n\t\terrorStr = fmt.Sprintf(\"Received slice of type (%v), but testFunc expects type (%v)\", elemType, testInput)\n\t} else if test.NumOut() != 1 || testOutput != reflect.Bool {\n\t\terrorStr = \"Expected func to have 1 return of type (bool)\\n\"\n\t}\n\n\tif errorStr != \"\" {\n\t\treturn errors.New(errorStr)\n\t}\n\n\treturn nil\n}", "func RegexMatchFunc(args ...interface{}) (interface{}, error) {\n\tname1 := args[0].(string)\n\tname2 := args[1].(string)\n\n\treturn (bool)(RegexMatch(name1, name2)), nil\n}", "func (action Action) Match(a Action) bool {\n\treturn wildcard.Match(string(action), string(a))\n}", "func lookupPath(obj interface{}, path string, kind reflect.Kind) (reflect.Value, bool) {\n\tnodes := strings.Split(path, \".\")\n\n\tvar name string\n\tvalue := reflect.ValueOf(obj)\n\nLOOP:\n\tfor _, node := range nodes {\n\t\tname = node\n\t\tif value.Kind() == reflect.Struct {\n\t\t\tt := value.Type()\n\n\t\t\tfor i := 0; i != t.NumField(); i++ {\n\t\t\t\tif t.Field(i).Name == node {\n\t\t\t\t\tvalue = value.Field(i)\n\t\t\t\t\tif value.Kind() == reflect.Interface || value.Kind() == reflect.Ptr {\n\t\t\t\t\t\tvalue = value.Elem()\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue LOOP\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbreak LOOP\n\t\t}\n\t}\n\n\tif name != nodes[len(nodes)-1] {\n\t\treturn value, false\n\t}\n\n\tif kind == reflect.Interface {\n\t\treturn value, true\n\t}\n\n\t// convert result kind to int for all size of interger as then\n\t// only a int64 version will be retrieve by value.Int()\n\trk := value.Kind()\n\tswitch rk {\n\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\trk = reflect.Int\n\t}\n\n\treturn value, rk == kind\n}", "func (l *logPipe) MatchFunc(mf func(string) bool) {\n\tl.matchFunc = mf\n}", "func (Functions) NameOf(obj interface{}) string {\n\treturn nameOf(obj)\n}", "func CheckObjStatusFunc(u TestUtil) bool {\n\treturn CheckFieldsValue(u) && CheckFieldsGetter(u)\n}", "func isMatch(exp *regexp.Regexp, val interface{}) bool {\n\tswitch v := val.(type) {\n\tcase []rune:\n\t\treturn exp.MatchString(string(v))\n\tcase []byte:\n\t\treturn exp.Match(v)\n\tcase string:\n\t\treturn exp.MatchString(v)\n\tdefault:\n\t\treturn false\n\t}\n}", "func (s *Plugin) Match(ctx context.Context, request *interact.Request, condition *v1alpha1.MockAPI_Condition) (match bool, err error) {\n\tsimple := condition.GetSimple()\n\tif simple == nil {\n\t\treturn false, nil\n\t}\n\tc := core.NewContext(request)\n\tfor _, item := range simple.Items {\n\t\toperandX := core.Render(c, item.OperandX)\n\t\toperandY := core.Render(c, item.OperandY)\n\t\tmatched, err := core.Match(operandX, item.Operator, operandY)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif item.Opposite {\n\t\t\tmatched = !matched\n\t\t}\n\t\tif matched {\n\t\t\tif simple.UseOrAmongItems {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif simple.UseOrAmongItems {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}", "func (fpp *FoPoPattern) Match(serviceName string) bool {\n\tvar pattern string\n\tvar matched bool\n\tfor _, pattern = range fpp.ServicePatterns {\n\t\tmatched, _ = filepath.Match(pattern, serviceName)\n\t\tif matched {\n\t\t\treturn matched\n\t\t}\n\t}\n\treturn false\n}", "func (r *gatewayReconciler) hasMatchingController(obj client.Object) bool {\n\tlog := r.log.WithFields(logrus.Fields{\n\t\t\"namespace\": obj.GetNamespace(),\n\t\t\"name\": obj.GetName(),\n\t})\n\n\tgw, ok := obj.(*gatewayapi_v1alpha1.Gateway)\n\tif !ok {\n\t\tlog.Info(\"invalid object, bypassing reconciliation.\")\n\t\treturn false\n\t}\n\n\tmatches, err := r.hasContourOwnedClass(gw)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn false\n\t}\n\tif matches {\n\t\tlog.Info(\"enqueueing gateway\")\n\t\treturn true\n\t}\n\n\tlog.Info(\"configured controllerName doesn't match an existing GatewayClass\")\n\treturn false\n}", "func NameLike(patterns ...string) MatcherFunc { return NameLikes(patterns) }", "func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool {\n\treturn Regexp(a.t, rx, str, msgAndArgs...)\n}", "func (p CodeIn) IsMatch(ctx runtime.PatternContext) bool {\n\tfor _, c := range p.Codes {\n\t\tif c == ctx.CallerCode() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (*InstZExt) isInst() {}", "func isOwner(owner *unstructured.Unstructured, obj interface{}) bool {\n\tif obj == nil {\n\t\treturn false\n\t}\n\tvar owners []metav1.OwnerReference\n\tobjMeta, ok := obj.(*metav1.ObjectMeta)\n\tif ok {\n\t\towners = objMeta.GetOwnerReferences()\n\t} else {\n\t\tif objUnstructured, ok := obj.(*unstructured.Unstructured); ok {\n\t\t\towners = objUnstructured.GetOwnerReferences()\n\t\t} else {\n\t\t\tklog.Error(\"Failed to get owners\")\n\t\t\treturn false\n\t\t}\n\t}\n\n\tfor _, ownerRef := range owners {\n\t\tif _, ok := owner.Object[\"metadata\"]; !ok {\n\t\t\tklog.Error(\"no meta\")\n\t\t\tcontinue\n\t\t}\n\t\tmeta, ok := owner.Object[\"metadata\"].(map[string]interface{})\n\t\tif !ok || meta == nil {\n\t\t\tklog.Error(\"no meta map\")\n\t\t\tcontinue\n\t\t}\n\t\tname, ok := meta[\"name\"].(string)\n\t\tif !ok || name == \"\" {\n\t\t\tklog.Error(\"failed to get name\")\n\t\t\tcontinue\n\t\t}\n\t\tif ownerRef.Kind == owner.Object[\"kind\"] && ownerRef.Name == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (_m *Factory) MapBasedSelectorForObject(object runtime.Object) (string, error) {\n\tret := _m.Called(object)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(runtime.Object) string); ok {\n\t\tr0 = rf(object)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(runtime.Object) error); ok {\n\t\tr1 = rf(object)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (self *Rectangle) EqualsI(args ...interface{}) bool{\n return self.Object.Call(\"equals\", args).Bool()\n}", "func (self *Rectangle) ContainsRectI(args ...interface{}) bool{\n return self.Object.Call(\"containsRect\", args).Bool()\n}", "func (m MatcherFunc) Matches(endpoint Endpoint) (bool, error) {\n\treturn m(endpoint)\n}", "func (r *gatewayReconciler) hasMatchingController(obj client.Object) bool {\n\tlog := r.log.WithFields(logrus.Fields{\n\t\t\"namespace\": obj.GetNamespace(),\n\t\t\"name\": obj.GetName(),\n\t})\n\n\tgw, ok := obj.(*gatewayapi_v1beta1.Gateway)\n\tif !ok {\n\t\tlog.Debugf(\"unexpected object type %T, bypassing reconciliation.\", obj)\n\t\treturn false\n\t}\n\n\tgc := &gatewayapi_v1beta1.GatewayClass{}\n\tif err := r.client.Get(context.Background(), types.NamespacedName{Name: string(gw.Spec.GatewayClassName)}, gc); err != nil {\n\t\tlog.WithError(err).Errorf(\"failed to get gatewayclass %s\", gw.Spec.GatewayClassName)\n\t\treturn false\n\t}\n\tif gc.Spec.ControllerName != r.gatewayClassControllerName {\n\t\tlog.Debugf(\"gateway's class controller is not %s; bypassing reconciliation\", r.gatewayClassControllerName)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (o *OperationLimiter) Match(r *request.Request) (bool, error) {\n\tif o.regexp == nil {\n\t\tvar err error\n\t\to.regexp, err = regexp.Compile(\"^\" + o.Operation)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\treturn o.regexp.Match([]byte(r.Operation.Name)), nil\n}", "func (obj *Object) ObjDo(action string) {\n\t// Action behavior\n\tfmt.Println(\"I can, \", action)\n}", "func execObjectString(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.ObjectString(args[0].(types.Object), args[1].(types.Qualifier))\n\tp.Ret(2, ret)\n}", "func (s *BasePlSqlParserListener) EnterObject_member_spec(ctx *Object_member_specContext) {}", "func (command *Command) Match(incmd sfinterfaces.ICommandInput) bool {\n\n\tshell := command.GetShell()\n\tlog := *shell.GetLog()\n\n\tif strings.HasPrefix(incmd.GetLowerCommandName(), strings.ToLower(command.GetName())) {\n\t\tlog.LogDebugf(\"Match()\", \"Command '%s' matched '%s'\", command.GetName(), incmd.GetLowerCommandName())\n\t\treturn true\n\t}\n\n\t// this will space the trace with false positives\n\t//log.LogDebug(\"Match()\", \"Command '%s' did not match '%s'\", command.GetName(), incmd.GetLowerCommandName())\n\treturn false\n}", "func makeObjectPredicate(f func(objectOld client.Object, objectNew client.Object) bool) objectPredicate {\n\treturn objectPredicate{\n\t\tf: f,\n\t}\n}", "func matchObject(objs []*nlpMatch, sentence string) []*nlpMatch {\n\n\tinput_words := strings.Split(sentence, \" \")\n\n\tobject_weights := make(map[string]int)\n\n\ttotal_words := 0\n\tfor i := 0; i < len(objs); i++ {\n\t\twords := strings.Split(objs[i].object, \" \")\n\t\tfor _, word := range words {\n\t\t\tobject_weights[word]++\n\t\t\ttotal_words++\n\t\t}\n\t}\n\t// Refactor final object_weights - higher the weight, rarer the word\n\tfor key, _ := range object_weights {\n\t\tobject_weights[key] = total_words - object_weights[key]\n\t}\n\n\t//Calculate the relative hit rate of objects\n\tfor i := 0; i < len(objs); i++ {\n\t\twords := strings.Split(objs[i].object, \" \")\n\t\tweight := 0\n\t\tfor _, word := range words {\n\t\t\tif contains(input_words, word) {\n\t\t\t\tweight += object_weights[word]\n\t\t\t}\n\t\t}\n\t\tobjs[i].weight = weight\n\t}\n\n\t// Sort by weights in reverse.\n\tsort.Sort(sort.Reverse(byWeight(objs)))\n\n\t// Return only the highest matching entries.\n\tmatcher := objs[0].weight\n\tfor i := 1; i < len(objs); i++ {\n\t\tif objs[i].weight != matcher {\n\t\t\treturn objs[:i]\n\t\t}\n\t}\n\treturn nil\n}", "func (j JO) IsObject(path ...string) (bool, error) {\n\treturn IsObject(j, path...)\n}", "func FamiliarMatch(pattern string, ref Reference) (bool, error) {\n\tmatched, err := path.Match(pattern, FamiliarString(ref))\n\tif namedRef, isNamed := ref.(Named); isNamed && !matched {\n\t\tmatched, _ = path.Match(pattern, FamiliarName(namedRef))\n\t}\n\treturn matched, err\n}", "func intuitiveImplements(obj types.Object, iface types.Object) bool {\n\tif NewChar(obj) == NewChar(iface) {\n\t\treturn false\n\t}\n\treturn types.Implements(obj.Type(), iface.Type().Underlying().(*types.Interface))\n}", "func (self *Graphics) ContainsI(args ...interface{}) bool{\n return self.Object.Call(\"contains\", args).Bool()\n}", "func GetApplyFunc(obj runtime.Object) ApplyFunc {\n\tobjKind := obj.GetObjectKind().GroupVersionKind()\n\tfor kind, delegate := range supportedObjectKinds {\n\t\tif isKindEquals(kind, objKind) {\n\t\t\treturn getApplyFuncForDelegate(delegate)\n\t\t}\n\t}\n\treturn nil\n}", "func (t Term) Match(args ...interface{}) Term {\n\treturn constructMethodTerm(t, \"Match\", p.Term_MATCH, args, map[string]interface{}{})\n}", "func matchHook(data *domain.Data, hook config.Hook) (bool, error) {\n\tif hook.If.Empty() {\n\t\treturn true, nil\n\t}\n\treturn hook.If.Run(data.Convert()) //nolint:wrapcheck\n}", "func execmInfoObjectOf(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Info).ObjectOf(args[1].(*ast.Ident))\n\tp.Ret(2, ret)\n}", "func (ps *Segment) Match(s string) (name string, capture bool, wildcard bool, matches bool) {\n\tif ps.IsWildcard {\n\t\twildcard = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif ps.IsVariable {\n\t\tname = ps.Name\n\t\tcapture = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif strings.EqualFold(s, ps.Name) {\n\t\tmatches = true\n\t\treturn\n\t}\n\treturn\n}", "func (g *Group) Match(o Owner) bool {\n\tif g.Equal(o) {\n\t\treturn true\n\t}\n\tif g.GetOwner().Match(o) {\n\t\treturn true\n\t}\n\tfor _, m := range g.GetPerm(\"%member%\") {\n\t\tif m.Match(o) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func ofctlFlowMatch(flowList []string, tableId int, matchStr, actStr string) bool {\n\tmtStr := fmt.Sprintf(\"table=%d, %s\", tableId, matchStr)\n\taStr := fmt.Sprintf(\"actions=%s\", actStr)\n\tfor _, flowEntry := range flowList {\n\t\tlog.Debugf(\"Looking for %s %s in %s\", mtStr, aStr, flowEntry)\n\t\tif strings.Contains(flowEntry, mtStr) && strings.Contains(flowEntry, aStr) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (f *Filter) Match(buf []byte) bool {\n cbuf := (*C.char)(unsafe.Pointer(&buf[0]))\n blen := C.uint(len(buf))\n\n if C.bpf_filter(f.program.bf_insns, cbuf, blen, blen) > 0 {\n return true\n }\n\n return false\n}", "func (util copyHandlerUtil) blobNameMatchesThePatternComponentWise(pattern string, blobName string) bool {\n\t// find the number of path separator in pattern and blobName\n\t// If the number of path separator doesn't match, then blob name doesn't match the pattern\n\tpSepInPattern := strings.Count(pattern, common.AZCOPY_PATH_SEPARATOR_STRING)\n\tpSepInBlobName := strings.Count(blobName, common.AZCOPY_PATH_SEPARATOR_STRING)\n\tif pSepInPattern != pSepInBlobName {\n\t\treturn false\n\t}\n\t// If the number of path separator matches in both blobName and pattern\n\t// each component of the blobName should match each component in pattern\n\t// Length of patternComponents and blobNameComponents is same since we already\n\t// match the number of path separators above.\n\tpatternComponents := strings.Split(pattern, common.AZCOPY_PATH_SEPARATOR_STRING)\n\tblobNameComponents := strings.Split(blobName, common.AZCOPY_PATH_SEPARATOR_STRING)\n\tfor index := 0; index < len(patternComponents); index++ {\n\t\t// match the pattern component and blobName component\n\t\tif !util.blobNameMatchesThePattern(patternComponents[index], blobNameComponents[index]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestIsValidObjectName(t *testing.T) {\n\ttestCases := []struct {\n\t\tobjectName string\n\t\tshouldPass bool\n\t}{\n\t\t// cases which should pass the test.\n\t\t// passing in valid object name.\n\t\t{\"object\", true},\n\t\t{\"The Shining Script <v1>.pdf\", true},\n\t\t{\"Cost Benefit Analysis (2009-2010).pptx\", true},\n\t\t{\"117Gn8rfHL2ACARPAhaFd0AGzic9pUbIA/5OCn5A\", true},\n\t\t{\"SHØRT\", true},\n\t\t{\"There are far too many object names, and far too few bucket names!\", true},\n\t\t// cases for which test should fail.\n\t\t// passing invalid object names.\n\t\t{\"\", false},\n\t\t{string([]byte{0xff, 0xfe, 0xfd}), false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tisValidObjectName := IsValidObjectName(testCase.objectName)\n\t\tif testCase.shouldPass && !isValidObjectName {\n\t\t\tt.Errorf(\"Test case %d: Expected \\\"%s\\\" to be a valid object name\", i+1, testCase.objectName)\n\t\t}\n\t\tif !testCase.shouldPass && isValidObjectName {\n\t\t\tt.Errorf(\"Test case %d: Expected object name \\\"%s\\\" to be invalid\", i+1, testCase.objectName)\n\t\t}\n\t}\n}", "func (p *pathPattern) Match(name string) bool {\n\tif strings.HasPrefix(name, p.prefix) || strings.HasSuffix(name, p.suffix) || strings.Contains(name, p.inner) {\n\t\treturn true\n\t}\n\tmatched, _ := filepath.Match(p.rawPattern, name)\n\treturn matched\n}", "func (m *middleware) isTargeted(interceptedMethod string) bool {\n\tcaptureConfig := m.Config()\n\tfor _, spec := range captureConfig.CaptureConfig.MatchSpecs {\n\t\tif spec.GetService() == \"*\" && spec.GetMethod() == \"*\" {\n\t\t\treturn true\n\t\t}\n\t\tif spec.GetService() == \"*\" {\n\t\t\ttargetSuffix := fmt.Sprintf(\"/%s\", spec.GetMethod())\n\t\t\tif strings.HasSuffix(interceptedMethod, targetSuffix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\tif spec.GetMethod() == \"*\" {\n\t\t\ttargetPrefix := fmt.Sprintf(\"/%s\", spec.GetService())\n\t\t\tif strings.HasPrefix(interceptedMethod, targetPrefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\ttarget := fmt.Sprintf(\"/%s/%s\", spec.GetService(), spec.GetMethod())\n\t\tif interceptedMethod == target {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c *Concurrent) isExecutable(e interface{}) bool {\n\treturn reflect.TypeOf(e).Kind() == reflect.Func\n}", "func (pattern targetPattern) MatchString(target string) bool {\n\tparts := strings.SplitN(target, \"/\", 2)\n\treturn len(parts) == 2 && parts[1] == pattern.name && pattern.namespace.MatchString(parts[0])\n}" ]
[ "0.5910947", "0.58454806", "0.5392626", "0.5204354", "0.5204354", "0.516737", "0.5110892", "0.5110841", "0.49837717", "0.4959721", "0.49305275", "0.49202144", "0.48990116", "0.48679546", "0.48671716", "0.4849514", "0.48440117", "0.48232383", "0.48232383", "0.48164865", "0.48056594", "0.4785228", "0.475676", "0.47484496", "0.47479287", "0.4746245", "0.47172475", "0.46910572", "0.46717575", "0.4659947", "0.46433812", "0.4637848", "0.46338978", "0.4633079", "0.45941377", "0.45922193", "0.4592044", "0.45848876", "0.45835128", "0.45762923", "0.4571631", "0.45666692", "0.4566258", "0.45648366", "0.4550888", "0.45339325", "0.45156652", "0.45080146", "0.44939753", "0.44785503", "0.44529432", "0.44520283", "0.44493294", "0.44492692", "0.44492692", "0.44371682", "0.44370958", "0.44324696", "0.44273466", "0.44064084", "0.44046098", "0.43995258", "0.43946713", "0.4393338", "0.43929538", "0.4391385", "0.438945", "0.43864337", "0.43855625", "0.43833417", "0.43822265", "0.43798104", "0.437222", "0.4372189", "0.437118", "0.43652946", "0.43652886", "0.43643212", "0.43633357", "0.43601817", "0.43565527", "0.4354494", "0.43402424", "0.43364525", "0.43301168", "0.43296608", "0.43229803", "0.432254", "0.4320727", "0.43187165", "0.4316375", "0.43098077", "0.43031907", "0.4302678", "0.4299312", "0.42993087", "0.42989397", "0.4297614", "0.429053", "0.4286956" ]
0.86283475
0
Get the value of the environment variable key or the fallback
func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Get(key, defaultValue string) string {\n\tif v, ok := os.LookupEnv(key); ok {\n\t\treturn v\n\t}\n\treturn defaultValue\n}", "func Get(key, defaultValue string) string {\n\tvalue, ok := os.LookupEnv(key)\n\tif ok {\n\t\treturn value\n\t}\n\n\treturn defaultValue\n}", "func getOrElse(key, standard string) string {\n\tif val := os.Getenv(key); val != \"\" {\n\t\treturn val\n\t} else if standard == \"\" {\n\t\tlog.Fatalf(\"ERROR: The environment variable, %s, must be set\", key)\n\t}\n\treturn standard\n}", "func Get(key string, defaultVal string) string {\n\tval, ok := os.LookupEnv(key)\n\tif !ok {\n\t\tval = defaultVal\n\t}\n\treturn val\n}", "func getenv(key, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func getEnvString(key string, defaultVal string) string {\n if value, exists := os.LookupEnv(key); exists {\n\t return value\n }\n\n return defaultVal\n}", "func env(key string, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func Get(envKey, defaultVal string) string {\n\t// Check for an environment variable\n\tenvVal, envPresent := os.LookupEnv(envKey)\n\tif envPresent && envVal != \"\" {\n\t\treturn envVal\n\t}\n\t// Check the loaded vars\n\tif val, ok := envVars[envKey]; ok && val != \"\" {\n\t\treturn val\n\t}\n\treturn defaultVal\n}", "func getEnv(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnv(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnv(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnv(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnv(key string, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\tif value != \"\" {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tvalue = fallback\n\t}\n\treturn value\n}", "func Getenv(key string) string", "func getEnvWithDefault(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\treturn fallback\n\t}\n\treturn value\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func getEnvOrDefault(name string, fallback string) string {\n\tval := os.Getenv(name)\n\tif val == \"\" {\n\t\treturn fallback\n\t}\n\n\treturn val\n}", "func getenv(key, def string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn def\n}", "func getenv(key string, def ...string) string {\n\tif v, ok := os.LookupEnv(key); ok {\n\t\treturn v\n\t}\n\tif len(def) == 0 {\n\t\tlog.Fatalf(\"%s not defined in environment\", key)\n\t}\n\treturn def[0]\n}", "func env(key string, defaultValue string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\treturn defaultValue\n}", "func Get(envKey, defaultVal string) string {\n\tval := os.Getenv(envKey)\n\tif val == \"\" {\n\t\tval = defaultVal\n\t}\n\treturn val\n}", "func Get(key string) (string, error) {\n\tval := os.Getenv(key)\n\n\tif val == \"\" {\n\t\treturn \"\", ErrNotFound\n\t}\n\n\treturn val, nil\n}", "func Env(key, fallback string) string {\n\tif v := os.Getenv(key); v != \"\" {\n\t\treturn v\n\t}\n\n\treturn fallback\n}", "func Get(key, alt string) string {\n\tv := os.Getenv(key)\n\tif v == \"\" {\n\t\treturn alt\n\t}\n\n\treturn v\n}", "func (s envValueStore) get(key StoreKey) (string, error) {\n\tenvValueStoreKey := strings.ToUpper(s.prefix + string(key))\n\tval, found := os.LookupEnv(strings.ToUpper(envValueStoreKey))\n\tif !found {\n\t\treturn \"\", ParameterNotFoundError{key: key}\n\t}\n\n\treturn val, nil\n}", "func envOrDefault(key string, defaultVal string) (string, error) {\n\tif envVal, ok := os.LookupEnv(key); ok {\n\t\tlog.Debugf(\"ENV variable %s. Value %s\", key, envVal)\n\t\treturn envVal, nil\n\t}\n\tlog.Debugf(\"ENV variable %s undefined, set default value: %s\", key, defaultVal)\n\treturn defaultVal, nil\n}", "func getEnv(key string, defaultVal string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\n\treturn defaultVal\n}", "func getEnv(key string, defaultVal string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\n\treturn defaultVal\n}", "func getEnv(key string, defaultVal string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\n\treturn defaultVal\n}", "func env(key string, defaultValue string) string {\n\tvalue := os.Getenv(key)\n\n\tif len(value) > 0 {\n\t\treturn value\n\t}\n\treturn defaultValue\n\n}", "func Getenv(key, fallback string) string {\n\tv := os.Getenv(key)\n\tif len(v) == 0 {\n\t\tos.Setenv(key, fallback)\n\t\treturn os.Getenv(key)\n\t}\n\treturn v\n}", "func GetenvString(key, fallback string) string {\n\tif v, ok := syscall.Getenv(key); ok {\n\t\treturn v\n\t}\n\treturn fallback\n}", "func getOrDefaultEnv(arg, envKey string) string {\n\tif arg != \"\" {\n\t\treturn arg\n\t}\n\treturn os.Getenv(envKey)\n}", "func GetEnvVariableOrDefault(key string, defaultVal string) string {\n\tval := os.Getenv(key)\n\tif val == \"\" {\n\t\tval = defaultVal\n\t}\n\treturn val\n}", "func LookupEnv(key string) (string, bool)", "func Get(key string) string {\n\treturn os.Getenv(key)\n}", "func Get(key string) string {\n\treturn os.Getenv(key)\n}", "func Lookup(key string) (string, bool) { return os.LookupEnv(key) }", "func GetEnvString(key, fallback string) string {\n\tvalue, found := os.LookupEnv(key)\n\tif !found {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getRequiredEnv(key string) string {\n\tvalue, exists := os.LookupEnv(key)\n\tif !exists {\n\t\tlogrus.Fatalf(\"Environment variable not set: %s\", key)\n\t}\n\treturn value\n}", "func getEnvOrDefault(envVar string, defaultValue string) string {\n\tvalue := os.Getenv(envVar)\n\tif value == \"\" {\n\t\treturn defaultValue\n\t}\n\treturn value\n}", "func GetENV(key, fallback string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\treturn value\n}", "func GetFromEnvOrDefault(name, defaultValue string) string {\n\tfromEnv := os.Getenv(name)\n\tif fromEnv == \"\" {\n\t\treturn defaultValue\n\t}\n\treturn fromEnv\n}", "func GetStr(name string, defaultValue ...string) string {\n\tvalue, ok := os.LookupEnv(name)\n\tif !ok && len(defaultValue) == 0 {\n\t\tfmt.Printf(\"ERROR: missing %s environment variable!\\n\", name)\n\t\tos.Exit(1)\n\t}\n\n\tif !ok {\n\t\tvalue = defaultValue[0]\n\t}\n\n\treturn value\n}", "func Env(key, defaultValue string) string {\n\tvalue, defined := os.LookupEnv(key)\n\tif !defined {\n\t\treturn defaultValue\n\t}\n\n\treturn value\n}", "func getStringOpt(name, dfault string) string {\n if value := os.Getenv(name); value != \"\" {\n return value\n }\n return dfault\n}", "func GetEnv(key string, fallback string) string {\n\tvalue := os.Getenv(key)\n\n\tif len(value) == 0 {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnvOr(name, defaultValue string) (out string) {\n\tout = os.Getenv(name)\n\tif out == \"\" {\n\t\tout = defaultValue\n\t}\n\treturn\n}", "func GetEnv(key string, fallback string) string {\n\tvar result = os.Getenv(key)\n\n\tif result == \"\" {\n\t\tresult = fallback\n\t}\n\n\treturn result\n}", "func Getenv(key string, fallbacks ...string) (value string) {\n\tvalue, _ = LookupEnv(key, fallbacks...)\n\treturn\n}", "func getEnv(key string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\n\treturn \"\"\n}", "func getEnv(key string) string {\n\tif value, exists := os.LookupEnv(key); exists {\n\t\treturn value\n\t}\n\tpanic(fmt.Errorf(\"Env Variable is not defined %v\", key))\n}", "func (c *AppConfig) getString(key string, defaultValue string) (val string) {\n\tif val = os.Getenv(key); val != \"\" {\n\t\treturn val\n\t} else {\n\t\tos.Setenv(key, defaultValue)\n\t}\n\n\treturn defaultValue\n}", "func GetEnv(key string, fallback string) string {\n\tvalue, ok := os.LookupEnv(key)\n\tif !ok {\n\t\treturn fallback\n\t}\n\n\treturn value\n}", "func getEnv(key, defaultVal string) string {\n\tval := os.Getenv(key)\n\tif val != \"\" {\n\t\treturn val\n\t}\n\treturn defaultVal\n}", "func getEnvironmentVariable(key string) string {\n\treturn os.Getenv(key)\n}", "func (h funcHandler) returnPlatformVar(key string) string {\n\t// lowercase the key\n\tkey = strings.ToLower(key)\n\n\t// iterate through the list of possible prefixes to look for\n\tfor _, prefix := range []string{\"deployment_parameter_\", \"vela_\"} {\n\t\t// trim the prefix from the input key\n\t\ttrimmed := strings.TrimPrefix(key, prefix)\n\t\t// check if the key exists within map\n\t\tif _, ok := h.envs[trimmed]; ok {\n\t\t\t// return the non-prefixed value if exists\n\t\t\treturn h.envs[trimmed]\n\t\t}\n\t}\n\n\t// return empty string if not exists\n\treturn \"\"\n}", "func GetEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnvironmentValue(key string)string{\n\treturn os.Getenv(key)\n}", "func Get(key string) string {\n\t_ = godotenv.Load()\n\n\treturn os.Getenv(key)\n}", "func Get(name, defvalue string) string {\n\tif s := os.Getenv(strings.ToUpper(name)); s == \"\" {\n\t\treturn defvalue\n\t} else {\n\t\treturn s\n\t}\n}", "func (env Environment) Get(key string) string {\n\tif v, ok := env[key]; ok {\n\t\treturn v\n\t}\n\treturn \"\"\n}", "func GetEnv(key string, fallback ...string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\n\treturn fallback[0]\n}", "func getEnvKeyValue(match string, partial bool) (string, string, error) {\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\t\tif len(pair) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := pair[0]\n\t\tvalue := pair[1]\n\n\t\tif partial && strings.Contains(key, match) {\n\t\t\treturn key, value, nil\n\t\t}\n\n\t\tif strings.Compare(key, match) == 0 {\n\t\t\treturn key, value, nil\n\t\t}\n\t}\n\n\tmatchType := \"match\"\n\tif partial {\n\t\tmatchType = \"partial match\"\n\t}\n\n\treturn \"\", \"\", fmt.Errorf(\"Failed to find %s with %s\", matchType, match)\n}", "func GetEnvStr(key, def string) string {\n\tif value := os.Getenv(key); value != \"\" {\n\t\treturn value\n\t}\n\treturn def\n}", "func getEnv(env, fallback string) string {\n\tif value, ok := os.LookupEnv(env); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnv(key string, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func GetEnv(key string, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn fallback\n}", "func (o *OS) Get(key string) interface{} {\n\treturn os.Getenv(key)\n}", "func getEnv(key string) string {\r\n\tvalue, exists := os.LookupEnv(key)\r\n\tif !exists {\r\n\t\tvalue = readInput(key)\r\n\t}\r\n\treturn value\r\n}", "func GetEnv(key string, fallback string) string {\n\tenv := os.Getenv(key)\n\n\tif len(env) == 0 {\n\t\tenv = fallback\n\t}\n\n\treturn env\n}", "func (p *EnvProvider) Lookup(key string) (string, error) {\n\tvalue, ok := os.LookupEnv(key)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"Value not found in the environment\")\n\t}\n\n\treturn value, nil\n}", "func (e *Environment) Get(key string) string {\n\tif e.Map != nil {\n\t\tif val, ok := e.Map[key]; ok {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn \"\"\n}", "func LoadEnvFileAndReturnEnvVarValueByKey(key string) string {\n\terr := godotenv.Load(\".env\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading .env file\")\n\t}\n\treturn os.Getenv(key)\n}", "func GetEnvOrPanic(key string) string {\n\tvalue, ok := os.LookupEnv(key);\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"Missing required environment variable '%v'\\n\", key))\n\t}\n\treturn value\n}", "func getenvRequired(key string) string {\n\tvalue := os.Getenv(key)\n\tif value == \"\" {\n\t\tPtEnvError(fmt.Sprintf(\"no %s environment variable\", key))\n\t}\n\treturn value\n}", "func GetEnvironmentVariable(key string, defaultValue string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t}\n\treturn defaultValue\n}", "func Getenv(key string) (string, error) {\n\tfor _, b := range []byte(key) {\n\t\tif b == '(' || b == ')' || b == '_' ||\n\t\t\t'0' <= b && b <= '9' ||\n\t\t\t'a' <= b && b <= 'z' ||\n\t\t\t'A' <= b && b <= 'Z' {\n\t\t\tcontinue\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"wine: invalid character %q in variable name\", b)\n\t}\n\n\tserver.wg.Wait()\n\tout, err := exec.Command(\"wine\", \"cmd\", \"/c\", \"if defined\", key, \"echo\", \"%\"+key+\"%\").Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes.TrimSuffix(out, []byte(\"\\r\\n\"))), nil\n}", "func Get(goos string, env []string, key string) string {\n\tfor n := len(env); n > 0; n-- {\n\t\tkv := env[n-1]\n\t\tif v, ok := Match(goos, kv, key); ok {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn \"\"\n}", "func Load(key string) string {\n\t// Gets the value of the map, if it exists returns the value\n\tenvironmentMutex.RLock()\n\tval := environment[key]\n\tenvironmentMutex.RUnlock()\n\n\tif environment[key] != \"\" {\n\t\treturn val\n\t}\n\n\t// If the value does not exist, it gets from the .env file\n\tval = os.Getenv(key)\n\tif val == \"\" || len(val) <= 0 {\n\t\treturn val\n\t}\n\n\t// If the value exists in .env file it is assigned to the map\n\tenvironmentMutex.Lock()\n\tenvironment[key] = val\n\tenvironmentMutex.Unlock()\n\n\treturn val\n}", "func Getenv(key, defaultValue string) string {\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn defaultValue\n\t}\n\treturn value\n}", "func Env(def, key string, fallbacks ...string) string {\n\tif val, found := LookupEnv(key, fallbacks...); found {\n\t\treturn val\n\t}\n\treturn def\n}", "func getEnv(name, def string) (value string) {\n\tif value = os.Getenv(name); value == \"\" {\n\t\tvalue = def\n\t}\n\treturn\n}", "func GetOriginalValue(key string, fallbackValue string) string {\n\tenv := os.Getenv(\"WRAPPED_\" + strings.ToUpper(key))\n\tif env == \"\" {\n\t\treturn fallbackValue\n\t} else {\n\t\treturn env\n\t}\n}", "func GetStringEnvWithDefault(name, def string) string {\n\tvar val string\n\t\n\tif val = os.Getenv(name); val == \"\" {\n\t\tlog.Printf(\"Env variant %s not found, using default value: %s\", name, def)\n\t\treturn def\n\t}\n\t\n\tlog.Printf(\"Env variant %s found, using env value: %s\", name, val)\n\treturn val\n}", "func getEnvOrFail(envVar string) string {\n\tvalue := os.Getenv(envVar)\n\tif value == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"Error: environment variable %s doesn't exist or it's empty, set it and try it again\", envVar)\n\t\tos.Exit(1)\n\t}\n\treturn value\n}", "func getEnvInt(key string, defaultVal int) int {\n valueStr := getEnvString(key, \"\")\n if value, err := strconv.Atoi(valueStr); err == nil {\n\t return value\n }\n return defaultVal\n}", "func GetEnv(key, fallback string) string {\n\tif value, ok := os.LookupEnv(key); ok {\n\t\treturn value\n\t} else if value, ok := os.LookupEnv(key + \"_FILE\"); ok {\n\t\tdat, err := ioutil.ReadFile(filepath.Clean(value))\n\t\tif err == nil {\n\t\t\treturn string(dat)\n\t\t}\n\t}\n\treturn fallback\n}" ]
[ "0.8102057", "0.80944294", "0.80778646", "0.80517364", "0.8010078", "0.79884714", "0.7981627", "0.78754824", "0.7824577", "0.7824577", "0.7824577", "0.7824577", "0.7796386", "0.7790338", "0.7754597", "0.772839", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.7724433", "0.76945597", "0.7664006", "0.7608936", "0.76019114", "0.7574481", "0.75429666", "0.74883944", "0.7474374", "0.7471938", "0.7463237", "0.741002", "0.741002", "0.741002", "0.73915535", "0.7367795", "0.7341105", "0.7340389", "0.73384213", "0.73180974", "0.73038906", "0.73038906", "0.72923297", "0.7272091", "0.7271401", "0.72499186", "0.7247694", "0.72336596", "0.72316706", "0.722777", "0.7221333", "0.72129184", "0.7212516", "0.72124356", "0.71821684", "0.71750504", "0.7168986", "0.71666217", "0.7164822", "0.71600133", "0.71510243", "0.71487", "0.7142361", "0.7142361", "0.7142361", "0.7142361", "0.7138043", "0.71352005", "0.71273077", "0.7123552", "0.71139294", "0.7107901", "0.7105916", "0.7087548", "0.70765954", "0.70765954", "0.7070949", "0.7060225", "0.7038448", "0.702104", "0.70192873", "0.70144284", "0.70143163", "0.70112306", "0.69889635", "0.696362", "0.694225", "0.6936068", "0.69309014", "0.69138265", "0.6912787", "0.6893797", "0.68893605", "0.688916", "0.68882793", "0.6888105" ]
0.75996566
29
Record records a data point.
func (c *Counter) Record(v float64) { c.RecordN(v, 1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *notifier) RecordAdd(x, y int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tNew: &Point{x, y, value},\n\t\t}})\n}", "func (s *StoragePointsWriterRecorder) Record(ctx context.Context, run *taskmodel.Run) error {\n\ttags := models.NewTags(map[string]string{\n\t\tstatusTag: run.Status,\n\t\ttaskIDTag: run.TaskID.String(),\n\t})\n\n\t// log an error if we have incomplete data on finish\n\tif !run.ID.Valid() ||\n\t\trun.ScheduledFor.IsZero() ||\n\t\trun.StartedAt.IsZero() ||\n\t\trun.FinishedAt.IsZero() ||\n\t\trun.Status == \"\" {\n\t\ts.log.Error(\"Run missing critical fields\", zap.String(\"run\", fmt.Sprintf(\"%+v\", run)), zap.String(\"runID\", run.ID.String()))\n\t}\n\n\tfields := map[string]interface{}{}\n\tfields[runIDField] = run.ID.String()\n\tfields[startedAtField] = run.StartedAt.Format(time.RFC3339Nano)\n\tfields[finishedAtField] = run.FinishedAt.Format(time.RFC3339Nano)\n\tfields[scheduledForField] = run.ScheduledFor.Format(time.RFC3339)\n\tfields[requestedAtField] = run.RequestedAt.Format(time.RFC3339)\n\n\tstartedAt := run.StartedAt\n\tif startedAt.IsZero() {\n\t\tstartedAt = time.Now().UTC()\n\t}\n\n\tlogBytes, err := json.Marshal(run.Log)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields[logField] = string(logBytes)\n\n\tpoint, err := models.NewPoint(s.destination.Measurement, tags, fields, startedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.cli.WriteV2(influxdb.FluxWrite{\n\t\tBucket: s.destination.Bucket,\n\t\tOrg: s.destination.Org,\n\t\tOrgID: s.destination.OrgID,\n\t\tPoints: models.Points{point},\n\t})\n}", "func (ts *TimeSeries) AddPoint(value float64) Record {\n\trecord := newRecord(value)\n\tts.AddRecord(record)\n\treturn *record\n}", "func (a *Activity) Record(samples []*Sample, altitudeReference string) error {\n\tdata := struct {\n\t\tSamples []*Sample `json:\"samples\"`\n\t\tActivityId int `json:\"activityId\"`\n\t\tAltitudeReference string `json:\"altitudeReference\"`\n\t}{\n\t\tSamples: samples,\n\t\tActivityId: a.Id,\n\t\tAltitudeReference: altitudeReference,\n\t}\n\treq, err := a.c.newRequestJSON(\"POST\", a.c.apiURL+\"/activity/record\", &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := a.c.doRequest(req, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (tracer *TraceLogger) Record(context string, data []byte) {\n\tgo func() {\n\t\ttracer.traceMutex.Lock()\n\t\tdefer tracer.traceMutex.Unlock()\n\t\tif tracer.fileHandle == nil || tracer.isReplaying {\n\t\t\treturn\n\t\t}\n\t\tts := stratuxClock.Time.Format(time.RFC3339Nano)\n\t\ttracer.csvWriter.Write([]string {ts, context, string(data)})\n\t}()\n}", "func (s *Collector) Record(name string, stats []*Stat) error {\n\treturn NOT_IMPLEMENTED\n}", "func (r *rawHist) record(t int64, v float64) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tr.buf = append(r.buf, &pb.Sample{\n\t\tDatetime: t,\n\t\tValue: v,\n\t})\n\tif int32(len(r.buf)) >= GetRawHistBufLimit() {\n\t\tbuf := r.buf\n\t\tr.buf = make([]*pb.Sample, 0, GetRawHistBufLimit()/2)\n\t\tgo r.assembleAndSend(buf)\n\t}\n}", "func (info HistogramFloat64) Record(e *Config, key *keys.Float64) {\n\tdata := &HistogramFloat64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (g *StableGauge) Record(value int64) {\n\tg.gauge.Record(value)\n}", "func (t *TimeSeries) Add(timestamp time.Time, datum float64) {\n\tt.records = append(t.records, &Record{\n\t\ttimestamp: timestamp,\n\t\tDatum: datum,\n\t})\n}", "func (h *Histogram) Record(v float64) {\n\th.RecordN(v, 1)\n}", "func (h *PCPHistogram) Record(val int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValue(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func (b *ServerBackend) AddDPointRecord(server string, user string, record *DPointRecord) bool {\n\t// Validate user and server\n\tuserdata := b.GetUserData(server, user)\n\tif userdata == nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not get userdata\")\n\t\treturn false\n\t}\n\n\tpoints, err := strconv.ParseInt(record.Points, 10, 32)\n\tif err != nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not parse int\")\n\t\treturn false\n\t}\n\n\tdata := fromilyclient.DPointRecord{\n\t\tPoints: int32(points),\n\t\tReason: record.Reason,\n\t}\n\n\tif b.Client.CreateDPointRecord(server, user, &data) != nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not create record\")\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (mb *MetricsBuilder) RecordBigipNodeDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipNodeDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (summary *Summary) Record(name string, data interface{}) {\n\titem, ok := summary.Data[name]\n\tif !ok {\n\t\titem = new(Metrics)\n\t\titem.Keys = make(map[string]Metric)\n\t\tsummary.Data[name] = item\n\t}\n\n\titem.Hits++\n\trecordMembers(reflect.ValueOf(data).Elem(), item.Keys, \"\")\n}", "func (c *StepLookbackAccumulator) AddPoint(dp ts.Datapoint) {\n\tif dp.TimestampNanos.Before(c.earliestLookback) {\n\t\t// this datapoint is too far in the past, it can be dropped.\n\t\treturn\n\t}\n\n\tc.datapoints = append(c.datapoints, xts.Datapoint{\n\t\tTimestamp: dp.TimestampNanos,\n\t\tValue: dp.Value,\n\t})\n}", "func (g *Gauge) Record(value int64) {\n\tatomic.StoreInt64(&g.value, value)\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (x *Writer) emitDataRecord(p []byte) error {\n\t// collect all the stuff that goes into this type of record\n\tvar data = []interface{}{\n\t\tbyte(len(p)), // byte count\n\t\tx.addr, // standard 16-bit base address\n\t\tbyte(Data), // record type\n\t\tp, // slice of data\n\t}\n\n\terr := x.emitRecord(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"emitDataRecord: %v\", err)\n\t}\n\n\tx.addr += uint16(len(p))\n\n\treturn nil\n}", "func (self *Client) data(dataPoints models.DataPoints) {\n\tlog.WithFields(log.Fields{\n\t\t\"points\": dataPoints,\n\t}).Debug(\"New datapoints\")\n\t// TODO: Send dataPoints to remote\n}", "func (mb *MetricsBuilder) RecordBigipPoolDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (d *Distribution) AddPoint(timestamp time.Time, value float64) {\n\td.Values = append(d.Values, MetricValue{Timestamp: timestamp, Value: value})\n}", "func (mb *MetricsBuilder) RecordMysqlLogOperationsDataPoint(ts pcommon.Timestamp, inputVal string, logOperationsAttributeValue AttributeLogOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlLogOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlLogOperations.recordDataPoint(mb.startTime, ts, val, logOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordBigipVirtualServerDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipVirtualServerDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (n *notifier) RecordMove(x1, y1, x2, y2 int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tOld: &Point{x1, y1, value},\n\t\t\tNew: &Point{x2, y2, value},\n\t\t}})\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapSearchRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsLdapSearchRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsOperationRateDataPoint(ts pcommon.Timestamp, val float64, operationTypeAttributeValue AttributeOperationType) {\n\tmb.metricActiveDirectoryDsOperationRate.recordDataPoint(mb.startTime, ts, val, operationTypeAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationObjectRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection) {\n\tmb.metricActiveDirectoryDsReplicationObjectRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (info HistogramInt64) Record(e *Config, key *keys.Int64) {\n\tdata := &HistogramInt64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (mb *MetricsBuilder) RecordMysqlOperationsDataPoint(ts pcommon.Timestamp, inputVal string, operationsAttributeValue AttributeOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlOperations.recordDataPoint(mb.startTime, ts, val, operationsAttributeValue.String())\n\treturn nil\n}", "func (metric *Float64Metric) Record(tags map[string]string, measurement float64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (nv *NetView) Record(counters string, rastCtr int) {\n\tnv.DataMu.Lock()\n\tdefer nv.DataMu.Unlock()\n\tif counters != \"\" {\n\t\tnv.LastCtrs = counters\n\t}\n\tnv.Data.PrjnType = nv.Params.PrjnType\n\tnv.Data.Record(nv.LastCtrs, rastCtr, nv.Params.Raster.Max)\n\tnv.RecTrackLatest() // if we make a new record, then user expectation is to track latest..\n}", "func (mb *MetricsBuilder) RecordBigipPoolMemberDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolMemberDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (e *LogLoss) Record(probability float64, weight float64) {\n\te.mu.Lock()\n\te.weight += weight\n\te.sum += weight * math.Log(probability+e.Epsilon)\n\te.mu.Unlock()\n}", "func (mb *MetricsBuilder) RecordMysqlDoubleWritesDataPoint(ts pcommon.Timestamp, inputVal string, doubleWritesAttributeValue AttributeDoubleWrites) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlDoubleWrites, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlDoubleWrites.recordDataPoint(mb.startTime, ts, val, doubleWritesAttributeValue.String())\n\treturn nil\n}", "func (mc *metricsConfig) record(ctx context.Context, mss []stats.Measurement, ros ...stats.Options) error {\n\tif mc == nil || mc.backendDestination == none {\n\t\t// Don't record data points if the metric config is not initialized yet or if\n\t\t// the defined backend is \"none\" explicitly.\n\t\treturn nil\n\t}\n\n\topt, err := optionForResource(metricskey.GetResource(ctx))\n\tif err != nil {\n\t\treturn err\n\t}\n\tros = append(ros, opt)\n\n\treturn stats.RecordWithOptions(ctx, append(ros, stats.WithMeasurements(mss...))...)\n}", "func (t *PersonalRecordChaincode) addRecord(APIstub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 4 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 4\")\n\t}\n\n\tvar record = Record{Date: args[1], Position: args[2], Name: args[3]}\n\n\trecordAsBytes, _ := json.Marshal(record)\n\tAPIstub.PutState(args[0], recordAsBytes)\n\n\treturn shim.Success(nil)\n\n}", "func Record(ctx context.Context, ms ...Measurement) {\n\treq := &recordReq{\n\t\tnow: time.Now(),\n\t\ttm: tag.FromContext(ctx),\n\t\tms: ms,\n\t}\n\tdefaultWorker.c <- req\n}", "func (ts *Timeseries) AddNewPoint(v float64, x interface{}) error {\n\tts.Lock()\n\tdefer ts.Unlock() // unlocks at the end\n\n\tswitch T := x.(type) {\n\tcase int64:\n\t\tts.XY[T] = v\n\tcase time.Time:\n\t\tts.XY[T.UnixNano()] = v\n\tcase int:\n\t\tts.XY[int64(T)] = v\n\tdefault:\n\t\treturn fmt.Errorf(\"Adding point not possible\")\n\t}\n\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlHandlersDataPoint(ts pcommon.Timestamp, inputVal string, handlerAttributeValue AttributeHandler) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlHandlers, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlHandlers.recordDataPoint(mb.startTime, ts, val, handlerAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapBindLastSuccessfulTimeDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsLdapBindLastSuccessfulTime.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordAerospikeNamespaceGeojsonRegionQueryPointsDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for AerospikeNamespaceGeojsonRegionQueryPoints, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricAerospikeNamespaceGeojsonRegionQueryPoints.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (tw *TimingsWrapper) Record(name string, startTime time.Time) {\n\tif tw.name == \"\" {\n\t\ttw.timings.Record([]string{name}, startTime)\n\t\treturn\n\t}\n\ttw.timings.Record([]string{tw.name, name}, startTime)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapBindRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsLdapBindRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordFlinkJobLastCheckpointTimeDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJobLastCheckpointTime, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJobLastCheckpointTime.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func Record(cl *Client, span *ssf.SSFSpan, done chan<- error) error {\n\tif cl == nil {\n\t\treturn ErrNoClient\n\t}\n\n\top := func(ctx context.Context, s backend) {\n\t\terr := s.sendSync(ctx, span)\n\t\tif done != nil {\n\t\t\tdone <- err\n\t\t}\n\t}\n\tselect {\n\tcase cl.ops <- op:\n\t\treturn nil\n\tdefault:\n\t}\n\treturn ErrWouldBlock\n}", "func (repository *RecordCommandRepositoryCircuitBreaker) InsertRecord(data repositoryTypes.CreateRecord) (entity.Record, error) {\n\toutput := make(chan entity.Record, 1)\n\thystrix.ConfigureCommand(\"insert_record\", config.Settings())\n\terrors := hystrix.Go(\"insert_record\", func() error {\n\t\trecord, err := repository.RecordCommandRepositoryInterface.InsertRecord(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutput <- record\n\t\treturn nil\n\t}, nil)\n\n\tselect {\n\tcase out := <-output:\n\t\treturn out, nil\n\tcase err := <-errors:\n\t\treturn entity.Record{}, err\n\t}\n}", "func (s *session) AddRecord(key string, member interface{}, unixstamp int64) error {\n\taction, err := s.addRecord(key, member, unixstamp)\n\tif err != nil {\n\t\treturn s.catch(\"AddRecord: \"+action, err)\n\t}\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlRowOperationsDataPoint(ts pcommon.Timestamp, inputVal string, rowOperationsAttributeValue AttributeRowOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlRowOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlRowOperations.recordDataPoint(mb.startTime, ts, val, rowOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlPageOperationsDataPoint(ts pcommon.Timestamp, inputVal string, pageOperationsAttributeValue AttributePageOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlPageOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlPageOperations.recordDataPoint(mb.startTime, ts, val, pageOperationsAttributeValue.String())\n\treturn nil\n}", "func (s *ReprTimeSeries) AddPoint(t int64, min float64, max float64, last float64, sum float64, count int64) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.Stats = append(s.Stats, &repr.StatRepr{\n\t\tTime: t,\n\t\tMin: repr.CheckFloat(min),\n\t\tMax: repr.CheckFloat(max),\n\t\tLast: repr.CheckFloat(last),\n\t\tSum: repr.CheckFloat(sum),\n\t\tCount: count,\n\t})\n\tif t > s.curTime {\n\t\ts.curTime = t\n\t}\n\tif t < s.T0 {\n\t\ts.T0 = t\n\t}\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolDataPagesDataPoint(ts pcommon.Timestamp, val int64, bufferPoolDataAttributeValue AttributeBufferPoolData) {\n\tmb.metricMysqlBufferPoolDataPages.recordDataPoint(mb.startTime, ts, val, bufferPoolDataAttributeValue.String())\n}", "func (r *Recorder) Write(record *Record) {\n\tif r == nil || record == nil {\n\t\treturn\n\t}\n\trecord.Write(r.data)\n}", "func (c Client) WritePoint(db, measurement string, data interface{}) error {\n\tt, tags, fields, err := encode(data)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.WritePointTagsFields(db, measurement, tags, fields, t)\n}", "func (mb *MetricsBuilder) RecordAerospikeNodeQueryTrackedDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for AerospikeNodeQueryTracked, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricAerospikeNodeQueryTracked.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (p *Profiler) Record(name string) func() {\n\tif p == nil {\n\t\t// If the profiler instance doesn't exist, then don't attempt to operate on it.\n\t\treturn func() {}\n\t}\n\tstart := p.now()\n\treturn func() {\n\t\tp.AddProfile(Profile{\n\t\t\tName: name,\n\t\t\tStart: start,\n\t\t\tFinish: p.now(),\n\t\t})\n\t}\n}", "func (p *Provider) record(tx *lease.Tx) {\n\tvar ops uint64 // Total number of consumptive ops (really op effects)\n\n\tfor _, op := range tx.Ops() {\n\t\tif op.Type == lease.Update && op.UpdateType() == lease.Renew {\n\t\t\t// Don't record renewals\n\t\t\tcontinue\n\t\t}\n\t\tfor _, effect := range op.Effects() {\n\t\t\tif !effect.Consumptive() {\n\t\t\t\t// Only record effects that affect consumption\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.log.Printf(\"TX %s\", effect.String())\n\t\t\tops++\n\t\t}\n\t}\n\n\tp.add(ops)\n}", "func (f *flusher) Record(mtype int, name string, value interface{}, flush bool) {\n\tf.mu.Lock()\n\tf.sink.Record(mtype, name, value)\n\tif flush {\n\t\tf.sink.Flush()\n\t}\n\tf.mu.Unlock()\n}", "func (log *Logger) record(format string, args ...interface{}) []byte {\n\treturn []byte(\n\t\ttime.Now().Format(\"2006/01/02 15:04:05\") +\n\t\t\t\": \" +\n\t\t\tfmt.Sprintf(format, args...) +\n\t\t\t\"\\n\",\n\t)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationPropertyRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection) {\n\tmb.metricActiveDirectoryDsReplicationPropertyRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsNotificationQueuedDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsNotificationQueued.recordDataPoint(mb.startTime, ts, val)\n}", "func (r *Recorder) Record(ctx context.Context, outDir string) error {\n\tvs, err := r.timeline.StopRecording(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to stop timeline\")\n\t}\n\n\tpv := perf.NewValues()\n\ttimeElapsed := time.Since(r.startTime)\n\tpv.Set(perf.Metric{\n\t\tName: \"Recorder.ElapsedTime\",\n\t\tUnit: \"s\",\n\t\tDirection: perf.SmallerIsBetter,\n\t}, float64(timeElapsed.Seconds()))\n\tpv.Merge(vs)\n\n\treturn pv.Save(outDir)\n}", "func (gWal *GenericWAL) writeCheckpointRecord(data []byte) (int64, error) {\n doneCh := make(chan *Response)\n\n if gWal.lostOwnership {\n return -1, ErrLostOwnership\n }\n\n lsn, errAdd := gWal.wal.AddCheckpointEntry(data, false, /* skipChecksum */\n doneCh)\n\n if errAdd != nil {\n glog.Errorf(\"could not add wal entry :: %v\", errAdd)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n response := <-doneCh\n if response == nil {\n glog.Errorf(\"could not persist checkpoint record to wal\")\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n if response.Result != nil {\n glog.Errorf(\"could not persist checkpoint record to wal :: %v\",\n response.Result)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n return int64(lsn), nil\n}", "func (l *Logger) Record(remoteAddr net.IP, hijacked bool, qtype uint16, question string, answers ...string) {\n\tif l.mode == LogDiscard {\n\t\treturn\n\t}\n\tif l.mode == LogHijacked && !hijacked {\n\t\treturn\n\t}\n\tl.wg.Add(1)\n\tl.queue <- LogEntry{\n\t\tTime: l.now(),\n\t\tRemoteAddr: remoteAddr,\n\t\tHijacked: hijacked,\n\t\tQtype: qtype,\n\t\tQuestion: question,\n\t\tAnswers: answers,\n\t}\n}", "func (sr *StoredRecording) Data(key *ari.Key) (*ari.StoredRecordingData, error) {\n\tif key == nil || key.ID == \"\" {\n\t\treturn nil, errors.New(\"storedRecording key not supplied\")\n\t}\n\n\tdata := new(ari.StoredRecordingData)\n\tif err := sr.client.get(\"/recordings/stored/\"+key.ID, data); err != nil {\n\t\treturn nil, dataGetError(err, \"storedRecording\", \"%v\", key.ID)\n\t}\n\n\tdata.Key = sr.client.stamp(key)\n\n\treturn data, nil\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolPagesDataPoint(ts pcommon.Timestamp, inputVal string, bufferPoolPagesAttributeValue AttributeBufferPoolPages) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlBufferPoolPages, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlBufferPoolPages.recordDataPoint(mb.startTime, ts, val, bufferPoolPagesAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlCommandsDataPoint(ts pcommon.Timestamp, inputVal string, commandAttributeValue AttributeCommand) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlCommands, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlCommands.recordDataPoint(mb.startTime, ts, val, commandAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsBindRateDataPoint(ts pcommon.Timestamp, val float64, bindTypeAttributeValue AttributeBindType) {\n\tmb.metricActiveDirectoryDsBindRate.recordDataPoint(mb.startTime, ts, val, bindTypeAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordFlinkOperatorRecordCountDataPoint(ts pcommon.Timestamp, inputVal string, operatorNameAttributeValue string, recordAttributeValue AttributeRecord) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkOperatorRecordCount, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkOperatorRecordCount.recordDataPoint(mb.startTime, ts, val, operatorNameAttributeValue, recordAttributeValue.String())\n\treturn nil\n}", "func (n *notifier) RecordReplace(x, y int, orig, repl interface{}) {\n\tn.add([]Update{Update{\n\t\tOld: &Point{x, y, orig},\n\t\tNew: &Point{x, y, repl},\n\t}})\n}", "func (mb *MetricsBuilder) RecordRedisReplicationOffsetDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisReplicationOffset.recordDataPoint(mb.startTime, ts, val)\n}", "func (p *printer) recordLine(linePtr *int) {\n\tp.linePtr = linePtr\n}", "func (w *NamedHistogram) Record(elapsed time.Duration) {\n\tmaxLatency := time.Duration(w.mu.current.HighestTrackableValue())\n\tif elapsed < minLatency {\n\t\telapsed = minLatency\n\t} else if elapsed > maxLatency {\n\t\telapsed = maxLatency\n\t}\n\n\tw.mu.Lock()\n\terr := w.mu.current.RecordValue(elapsed.Nanoseconds())\n\tw.mu.Unlock()\n\n\tif err != nil {\n\t\t// Note that a histogram only drops recorded values that are out of range,\n\t\t// but we clamp the latency value to the configured range to prevent such\n\t\t// drops. This code path should never happen.\n\t\tpanic(fmt.Sprintf(`%s: recording value: %s`, w.name, err))\n\t}\n}", "func (mb *MetricsBuilder) RecordRedisNetInputDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisNetInput.recordDataPoint(mb.startTime, ts, val)\n}", "func (n *notifier) RecordRemove(x, y int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tOld: &Point{x, y, value},\n\t\t}})\n}", "func (metric *Int64Metric) Record(tags map[string]string, measurement int64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (self *averageCache) Insert(dataPoints []*whisper.TimeSeriesPoint) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Insert\")\n\tself.inputChan <- dataPoints\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolOperationsDataPoint(ts pcommon.Timestamp, inputVal string, bufferPoolOperationsAttributeValue AttributeBufferPoolOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlBufferPoolOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlBufferPoolOperations.recordDataPoint(mb.startTime, ts, val, bufferPoolOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsNameCacheHitRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsNameCacheHitRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (r *Recorder) Record(mediaSSRC uint32, sequenceNumber uint16, arrivalTime int64) {\n\tr.mediaSSRC = mediaSSRC\n\tif sequenceNumber < 0x0fff && (r.lastSequenceNumber&0xffff) > 0xf000 {\n\t\tr.cycles += 1 << 16\n\t}\n\tr.receivedPackets = insertSorted(r.receivedPackets, pktInfo{\n\t\tsequenceNumber: r.cycles | uint32(sequenceNumber),\n\t\tarrivalTime: arrivalTime,\n\t})\n\tr.lastSequenceNumber = sequenceNumber\n}", "func (log *Logger) Records(msg string, fd interface{}) {\n\tlog.pipeline[msg] = fd\n}", "func (b *Bucket) AddData(dataPoint data.Point) error {\n\terr := b.shards[b.index].AddData(dataPoint)\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif !errors.Is(err, ErrShardMaxReached) {\n\t\treturn err\n\t}\n\n\tvar m metrics.Metric\n\n\t// we have reached max timestamp for the current shard, make a new one\n\tif m, err = metrics.FromDescriptor(b.descriptor); err != nil {\n\t\treturn err\n\t}\n\tif err := m.AddData(dataPoint); err != nil {\n\t\treturn err\n\t}\n\n\tshard := NewShard(m, b.shardDuration)\n\n\tb.shards = append(b.shards, shard)\n\tb.index++\n\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordBigipPoolAvailabilityDataPoint(ts pcommon.Timestamp, val int64, availabilityStatusAttributeValue AttributeAvailabilityStatus) {\n\tmb.metricBigipPoolAvailability.recordDataPoint(mb.startTime, ts, val, availabilityStatusAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordBigipNodeAvailabilityDataPoint(ts pcommon.Timestamp, val int64, availabilityStatusAttributeValue AttributeAvailabilityStatus) {\n\tmb.metricBigipNodeAvailability.recordDataPoint(mb.startTime, ts, val, availabilityStatusAttributeValue.String())\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func (mb *MetricsBuilder) RecordFlinkJobCheckpointInProgressDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJobCheckpointInProgress, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJobCheckpointInProgress.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (s *KinesisService) PutRecord(req *PutRecordRequest) (result *PutRecordResult, err error) {\n\n\tresult = new(PutRecordResult)\n\terr = s.wrapperSignAndDo(\"Kinesis_20131202.PutRecord\", req, result)\n\treturn\n}", "func (srv *InfluxSrv) Write(measurement string, fields map[string]interface{}, tags map[string]string) {\n\tsrv.writer.WritePoint(influxdb.NewPoint(measurement, tags, fields, time.Now()))\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationOperationPendingDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsReplicationOperationPending.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordMysqlLocksDataPoint(ts pcommon.Timestamp, inputVal string, locksAttributeValue AttributeLocks) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlLocks, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlLocks.recordDataPoint(mb.startTime, ts, val, locksAttributeValue.String())\n\treturn nil\n}", "func (gWal *GenericWAL) writeDataRecord(data []byte) (int64, error) {\n doneCh := make(chan *Response)\n\n if gWal.lostOwnership {\n return -1, ErrLostOwnership\n }\n\n lsn, errAdd := gWal.wal.AddDataEntry(data, false /* skipChecksum */, doneCh)\n if errAdd != nil {\n glog.Errorf(\"could not add wal entry :: %v\", errAdd)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n response := <-doneCh\n if response == nil {\n glog.Errorf(\"could not persist delta record to wal\")\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n if response.Result != nil {\n glog.Errorf(\"could not persist delta record to wal :: %v\", response.Result)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n return int64(lsn), nil\n}", "func (c *Client) AddRecord(ctx context.Context, zone, recordName, recordValue string) error {\n\tdomain, err := c.getDomain(ctx, zone)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecord := Record{DomainID: domain.ID, Name: recordName, Value: recordValue, Type: \"TXT\"}\n\n\terr = c.addTxtRecord(ctx, record)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.publishRecords(ctx, domain.ID)\n}", "func (o *EntryTracker) Record() *EntryRecord {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\n\tvar r EntryRecord\n\tif len(o.streams) > 0 {\n\t\tr.Streams = make(map[types.StreamPath]*StreamEntryRecord, len(o.streams))\n\t\tfor k, v := range o.streams {\n\t\t\tr.Streams[k] = v.record()\n\t\t}\n\t}\n\treturn &r\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationValueRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection, valueTypeAttributeValue AttributeValueType) {\n\tmb.metricActiveDirectoryDsReplicationValueRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String(), valueTypeAttributeValue.String())\n}", "func (t *ZramInfoTracker) Record(pv *perf.Values) {\n\tif !t.hasZram {\n\t\treturn\n\t}\n\n\tfor i, stat := range t.stats {\n\t\tpv.Set(perf.Metric{\n\t\t\tName: t.prefix + \"RAM.Zram.\" + zramFieldNames[i],\n\t\t\tUnit: \"bytes\",\n\t\t\tDirection: perf.SmallerIsBetter,\n\t\t}, stat)\n\t}\n}", "func (vt *perfSchemaTable) AddRecord(ctx sessionctx.Context, r []types.Datum, skipHandleCheck bool) (recordID int64, err error) {\n\treturn 0, table.ErrUnsupportedOp\n}", "func (src *Source) StoreSavepoint() {\n\tsrc.savepointStack = append(src.savepointStack, &savepoint{\n\t\tcurrent: src.current,\n\t})\n}", "func NewRecord() *Record {\n\trecord := new(Record)\n\trecord.Formatted = new(bytes.Buffer)\n\treturn record\n}" ]
[ "0.7321669", "0.6991361", "0.6834238", "0.6516929", "0.64530843", "0.6376556", "0.625649", "0.6252531", "0.6237906", "0.6132665", "0.612506", "0.61025167", "0.60354906", "0.60345125", "0.6005778", "0.5993227", "0.59865916", "0.595146", "0.5946505", "0.59002554", "0.5885247", "0.58831114", "0.585158", "0.58467525", "0.581802", "0.5789543", "0.5783429", "0.57560873", "0.5752794", "0.5737017", "0.57337654", "0.5717129", "0.5708306", "0.56973016", "0.5680644", "0.56615627", "0.5644605", "0.56051266", "0.56027853", "0.5601796", "0.5601041", "0.5587749", "0.5566232", "0.55433905", "0.5539408", "0.55269486", "0.55267376", "0.55249363", "0.55137956", "0.5504769", "0.550279", "0.5499125", "0.5498905", "0.5468015", "0.54636484", "0.5461485", "0.54598176", "0.54538006", "0.5437438", "0.5433776", "0.54240125", "0.5421191", "0.539755", "0.53953046", "0.5388757", "0.53875554", "0.53611743", "0.53575253", "0.53533185", "0.5343173", "0.5329281", "0.53225374", "0.53185606", "0.53123873", "0.53057146", "0.5297677", "0.52857447", "0.5262405", "0.5262092", "0.5254877", "0.5247429", "0.5245295", "0.52447134", "0.52299714", "0.52294827", "0.5201413", "0.51982105", "0.5198131", "0.519694", "0.5187185", "0.5178688", "0.5175154", "0.51684326", "0.5154603", "0.515326", "0.51525706", "0.51474214", "0.51465595", "0.5144451", "0.5143458" ]
0.6280639
6
RecordN efficiently records the same value N times
func (c *Counter) RecordN(v float64, n int) { isFirst := (c.Count == 0) c.Count += int64(n) if isFirst { c.Min = v c.Max = v } else if v < c.Min { c.Min = v } else if v > c.Max { c.Max = v } s := v * float64(n) c.Sum += s c.sumOfSquares += (s * s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *PCPHistogram) RecordN(val, n int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValues(val, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func (h *Histogram) RecordN(v float64, n int) {\n\th.Counter.RecordN(v, n)\n\th.record(v, n)\n}", "func MemoryRecordN(b *MemoryBackend, n int) *Record {\n\tnode := b.Head()\n\tfor i := 0; i < n; i++ {\n\t\tif node == nil {\n\t\t\tbreak\n\t\t}\n\t\tnode = node.Next()\n\t}\n\tif node == nil {\n\t\treturn nil\n\t}\n\treturn node.Record\n}", "func RecordFilteredInN(n int) {\n\tstats.Record(context.Background(), mRecordsFilteredIn.M(int64(n)))\n}", "func (r *Dbfgo) GetRecordN(n int64) Record {\n\tvar record Record\n\tr.reader.Seek(0, 0)\n\trecordlen := r.Header.Recordlen\n\tstart := r.Header.Headerlen + n*r.Header.Recordlen\n\tbuf := make([]byte, recordlen)\n\t_, err := r.reader.ReadAt(buf, start)\n\tif err != nil {\n\t\treturn record\n\t}\n\ttempdata := map[string]string{}\n\t//record is deleted if there is a '*'\n\trecord.NotDeleted = (string(buf[0:1]) != \"*\")\n\ta := int64(1)\n\tfor _, val := range r.Fields {\n\t\tfieldlen := val.FieldLen\n\t\ttempdata[val.Name] = strings.Trim(fmt.Sprintf(\"%s\", buf[a:a+fieldlen]), \" \")\n\t\ta = a + fieldlen\n\t}\n\trecord.Data = tempdata\n\treturn record\n}", "func RecordFilteredOutN(n int) {\n\tstats.Record(context.Background(), mRecordsFilteredOut.M(int64(n)))\n}", "func NewRecords(n int) *Records {\n\treturn &Records{\n\t\tarr: make([]*Record, 0, n),\n\t\tm: make(map[string]*Record, 100),\n\t\tdups: make(map[string]struct{}, 10),\n\t}\n}", "func (c *Counter) Record(v float64) {\n\tc.RecordN(v, 1)\n}", "func (h *MultiHistCompat) RecordValues(value int64, n int64) error {\n\th.addWeightedValue(value, n)\n\n\treturn nil\n}", "func (h *HistCompat) RecordValues(value int64, n int64) error {\n\th.addWeightedValue(value, n)\n\n\treturn nil\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func (b *recBatch) appendRecord(pr promisedRec, nums recordNumbers) {\n\tb.wireLength += nums.wireLength\n\tb.v1wireLength += messageSet1Length(pr.Record)\n\tb.records = append(b.records, promisedNumberedRecord{\n\t\tnums,\n\t\tpr,\n\t})\n}", "func (b *recBatch) calculateRecordNumbers(r *Record) recordNumbers {\n\ttsMillis := r.Timestamp.UnixNano() / 1e6\n\ttsDelta := int32(tsMillis - b.firstTimestamp)\n\toffsetDelta := int32(len(b.records)) // since called before adding record, delta is the current end\n\n\tl := 1 + // attributes, int8 unused\n\t\tkbin.VarintLen(tsDelta) +\n\t\tkbin.VarintLen(offsetDelta) +\n\t\tkbin.VarintLen(int32(len(r.Key))) +\n\t\tlen(r.Key) +\n\t\tkbin.VarintLen(int32(len(r.Value))) +\n\t\tlen(r.Value) +\n\t\tkbin.VarintLen(int32(len(r.Headers))) // varint array len headers\n\n\tfor _, h := range r.Headers {\n\t\tl += kbin.VarintLen(int32(len(h.Key))) +\n\t\t\tlen(h.Key) +\n\t\t\tkbin.VarintLen(int32(len(h.Value))) +\n\t\t\tlen(h.Value)\n\t}\n\n\treturn recordNumbers{\n\t\twireLength: int32(kbin.VarintLen(int32(l)) + l),\n\t\tlengthField: int32(l),\n\t\ttimestampDelta: tsDelta,\n\t}\n}", "func (nv *NetView) Record(counters string, rastCtr int) {\n\tnv.DataMu.Lock()\n\tdefer nv.DataMu.Unlock()\n\tif counters != \"\" {\n\t\tnv.LastCtrs = counters\n\t}\n\tnv.Data.PrjnType = nv.Params.PrjnType\n\tnv.Data.Record(nv.LastCtrs, rastCtr, nv.Params.Raster.Max)\n\tnv.RecTrackLatest() // if we make a new record, then user expectation is to track latest..\n}", "func (r *rawHist) record(t int64, v float64) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tr.buf = append(r.buf, &pb.Sample{\n\t\tDatetime: t,\n\t\tValue: v,\n\t})\n\tif int32(len(r.buf)) >= GetRawHistBufLimit() {\n\t\tbuf := r.buf\n\t\tr.buf = make([]*pb.Sample, 0, GetRawHistBufLimit()/2)\n\t\tgo r.assembleAndSend(buf)\n\t}\n}", "func testSetN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Set(Key(i), i)\n\t}\n}", "func (h *Histogram) Record(v float64) {\n\th.RecordN(v, 1)\n}", "func (record) RecordCount(b []byte) int {\n\treturn len(b) / recordLength\n}", "func BenchmarkLastNWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastN\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func (h *PCPHistogram) MustRecordN(val, n int64) {\n\tif err := h.RecordN(val, n); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (info HistogramInt64) Record(e *Config, key *keys.Int64) {\n\tdata := &HistogramInt64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func genN(value byte, n int) []byte {\n\tvalues := make([]byte, n, n)\n\n\tfor i := 0; i < n; i++ {\n\t\tvalues = append(values, value)\n\t}\n\n\treturn values\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (d *Dataset) RecordCount() int {\n\tcount := 0\n\tif d.BlockCount() > 0 {\n\t\tfor _, block := range d.blocks {\n\t\t\tcount += block.RecordCount()\n\t\t}\n\t}\n\n\treturn count\n}", "func NewRecord(row []string, filename string, n int) (Record, error) {\n\tvar record Record = Record{}\n\tif len(row) < 3 {\n\t\treturn record, fmt.Errorf(\"Not enough columns in file %s after %d records\",\n\t\t\tfilename, n)\n\t}\n\tif row[1] == \"1\" || strings.ToLower(row[1]) == \"true\" {\n\t\trecord.Sensor = true\n\t} else if row[1] != \"0\" && strings.ToLower(row[1]) != \"false\" {\n\t\treturn record, fmt.Errorf(\"Expected 'true' or 'false' in file %s after %d records\",\n\t\t\tfilename, n)\n\t}\n\tfor _, col := range row[2:] {\n\t\trecord.Address += col\n\t}\n\trecord.Source = filename\n\trecord.ID = row[0]\n\treturn record, nil\n}", "func readRawRecords(n int, in []byte) []kmsg.Record {\n\trs := make([]kmsg.Record, n)\n\tfor i := 0; i < n; i++ {\n\t\tlength, used := kbin.Varint(in)\n\t\ttotal := used + int(length)\n\t\tif used == 0 || length < 0 || len(in) < total {\n\t\t\treturn rs[:i]\n\t\t}\n\t\tif err := (&rs[i]).ReadFrom(in[:total]); err != nil {\n\t\t\treturn rs[:i]\n\t\t}\n\t\tin = in[total:]\n\t}\n\treturn rs\n}", "func updateN(n int, b *testing.B) {\n\tb.StopTimer()\n\tw := benchWorld()\n\tp := benchPlayer()\n\n\tvar bds boids\n\tboidVal := bds.Generate(rand.New(rand.NewSource(rand.Int63())), n)\n\tbds = boidVal.Interface().(boids)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tUpdateBoids(uint(i), bds, p, w)\n\t}\n}", "func (metric *Int64Metric) Record(tags map[string]string, measurement int64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (h *PCPHistogram) Record(val int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValue(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func TestFileRecorder(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"/tmp\", \"file-recorder\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tfr, err := pool.NewFileRecorder(path.Join(dir, \"file-recorder\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer fr.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tif err := fr.Put([]byte(fmt.Sprintf(\"nice to meet you %d\", i))); err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 100; i < 50000; i++ {\n\t\t\tif err := fr.Put([]byte(fmt.Sprintf(\"nice to meet you %d\", i))); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor i := 0; i < 100; i++ {\n\t\tif bs, err := fr.GetN(20); err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t} else {\n\t\t\t// for _, b := range bs {\n\t\t\t// \tb\n\t\t\t// \t// fmt.Println(string(b))\n\t\t\t// }\n\t\t\tif len(bs) != 20 {\n\t\t\t\tif err := fr.Rewind(); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\twg.Wait()\n}", "func testCountN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Count()\n\t}\n}", "func (r *Recorder) Record(mediaSSRC uint32, sequenceNumber uint16, arrivalTime int64) {\n\tr.mediaSSRC = mediaSSRC\n\tif sequenceNumber < 0x0fff && (r.lastSequenceNumber&0xffff) > 0xf000 {\n\t\tr.cycles += 1 << 16\n\t}\n\tr.receivedPackets = insertSorted(r.receivedPackets, pktInfo{\n\t\tsequenceNumber: r.cycles | uint32(sequenceNumber),\n\t\tarrivalTime: arrivalTime,\n\t})\n\tr.lastSequenceNumber = sequenceNumber\n}", "func (summary *Summary) Record(name string, data interface{}) {\n\titem, ok := summary.Data[name]\n\tif !ok {\n\t\titem = new(Metrics)\n\t\titem.Keys = make(map[string]Metric)\n\t\tsummary.Data[name] = item\n\t}\n\n\titem.Hits++\n\trecordMembers(reflect.ValueOf(data).Elem(), item.Keys, \"\")\n}", "func (recBuf *recBuf) bufferRecord(pr promisedRec, abortOnNewBatch bool) bool {\n\trecBuf.mu.Lock()\n\tdefer recBuf.mu.Unlock()\n\n\t// Timestamp after locking to ensure sequential, and truncate to\n\t// milliseconds to avoid some accumulated rounding error problems\n\t// (see Shopify/sarama#1455)\n\tpr.Timestamp = time.Now().Truncate(time.Millisecond)\n\n\tnewBatch := true\n\tdrainBatch := recBuf.batchDrainIdx == len(recBuf.batches)\n\n\tproduceVersionKnown := atomic.LoadUint32(&recBuf.sink.produceVersionKnown) == 1\n\tif !drainBatch {\n\t\tbatch := recBuf.batches[len(recBuf.batches)-1]\n\t\trecordNumbers := batch.calculateRecordNumbers(pr.Record)\n\n\t\tnewBatchLength := batch.wireLength + recordNumbers.wireLength\n\n\t\t// If we do not know the broker version, we may be talking\n\t\t// to <0.11.0 and be using message sets. Until we know the\n\t\t// broker version, we pessimisitically cut our batch off using\n\t\t// the largest record length numbers.\n\t\tif !produceVersionKnown {\n\t\t\tv1newBatchLength := batch.v1wireLength + messageSet1Length(pr.Record)\n\t\t\tif v1newBatchLength > newBatchLength { // we only check v1 since it is larger than v0\n\t\t\t\tnewBatchLength = v1newBatchLength\n\t\t\t}\n\t\t} else {\n\t\t\t// If we do know our broker version and it is indeed\n\t\t\t// an old one, we use the appropriate length.\n\t\t\tswitch recBuf.sink.produceVersion {\n\t\t\tcase 0, 1:\n\t\t\t\tnewBatchLength = batch.v0wireLength() + messageSet0Length(pr.Record)\n\t\t\tcase 2:\n\t\t\t\tnewBatchLength = batch.v1wireLength + messageSet1Length(pr.Record)\n\t\t\t}\n\t\t}\n\n\t\tif batch.tries == 0 && newBatchLength <= recBuf.maxRecordBatchBytes {\n\t\t\tnewBatch = false\n\t\t\tbatch.appendRecord(pr, recordNumbers)\n\t\t}\n\t}\n\n\tif newBatch {\n\t\tnewBatch := recBuf.newRecordBatch(pr)\n\n\t\t// Before we decide to keep this new batch, if this single record is too\n\t\t// large for a batch, then we immediately fail it.\n\t\tnewBatchLength := newBatch.wireLength\n\t\tif !produceVersionKnown && newBatch.v1wireLength > newBatchLength {\n\t\t\tnewBatchLength = newBatch.v1wireLength\n\t\t} else {\n\t\t\tswitch recBuf.sink.produceVersion {\n\t\t\tcase 0, 1:\n\t\t\t\tnewBatchLength = newBatch.v0wireLength()\n\t\t\tcase 2:\n\t\t\t\tnewBatchLength = newBatch.v1wireLength\n\t\t\t}\n\t\t}\n\t\tif newBatchLength > recBuf.maxRecordBatchBytes {\n\t\t\trecBuf.cl.finishRecordPromise(pr, kerr.MessageTooLarge)\n\t\t\treturn true\n\t\t}\n\n\t\tif abortOnNewBatch {\n\t\t\treturn false\n\t\t}\n\t\trecBuf.batches = append(recBuf.batches, newBatch)\n\t}\n\n\tif recBuf.cl.cfg.linger == 0 {\n\t\tif drainBatch {\n\t\t\trecBuf.sink.maybeDrain()\n\t\t}\n\t} else {\n\t\t// With linger, if this is a new batch but not the first, we\n\t\t// stop lingering and begin draining. The drain loop will\n\t\t// restart our linger once this buffer has one batch left.\n\t\tif newBatch && !drainBatch ||\n\t\t\t// If this is the first batch, try lingering; if\n\t\t\t// we cannot, we are being flushed and must drain.\n\t\t\tdrainBatch && !recBuf.lockedMaybeStartLinger() {\n\t\t\trecBuf.lockedStopLinger()\n\t\t\trecBuf.sink.maybeDrain()\n\t\t}\n\t}\n\treturn true\n}", "func WriteCount(buffer []byte, offset int, value byte, valueCount int) {\n for i := 0; i < valueCount; i++ {\n buffer[offset + i] = value\n }\n}", "func (d *DB) recordMetrics() {\n\tticker := time.NewTicker(time.Second * time.Duration(30))\n\n\tfor range ticker.C {\n\t\tvar streamCount float64\n\t\terr := d.DB.Get(&streamCount, `SELECT COUNT(*) FROM streams`)\n\t\tif err != nil {\n\t\t\td.logger.Log(\n\t\t\t\t\"msg\", \"error counting streams\",\n\t\t\t\t\"err\", err,\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\tStreamGauge.Set(streamCount)\n\t}\n}", "func (kvcodec *tableKVEncoder) AddRecord(\n\trow []types.Datum,\n\trowID int64,\n\tcolumnPermutation []int,\n) (Row, int, error) {\n\tcols := kvcodec.tbl.Cols()\n\n\tvar value types.Datum\n\tvar err error\n\n\trecord := kvcodec.recordCache\n\tif record == nil {\n\t\trecord = make([]types.Datum, 0, len(cols)+1)\n\t}\n\n\tisAutoRandom := false\n\tif kvcodec.tbl.Meta().PKIsHandle && kvcodec.tbl.Meta().ContainsAutoRandomBits() {\n\t\tisAutoRandom = true\n\t}\n\n\tfor i, col := range cols {\n\t\tj := columnPermutation[i]\n\t\tisAutoIncCol := mysql.HasAutoIncrementFlag(col.Flag)\n\t\tisPk := mysql.HasPriKeyFlag(col.Flag)\n\t\tswitch {\n\t\tcase j >= 0 && j < len(row):\n\t\t\tvalue, err = table.CastValue(kvcodec.se, row[j], col.ToInfo(), false, false)\n\t\t\tif err == nil {\n\t\t\t\terr = col.HandleBadNull(&value, kvcodec.se.vars.StmtCtx)\n\t\t\t}\n\t\tcase isAutoIncCol:\n\t\t\t// we still need a conversion, e.g. to catch overflow with a TINYINT column.\n\t\t\tvalue, err = table.CastValue(kvcodec.se, types.NewIntDatum(rowID), col.ToInfo(), false, false)\n\t\tdefault:\n\t\t\tvalue, err = table.GetColDefaultValue(kvcodec.se, col.ToInfo())\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, 0, errors.Trace(err)\n\t\t}\n\n\t\trecord = append(record, value)\n\n\t\tif isAutoRandom && isPk {\n\t\t\ttypeBitsLength := uint64(mysql.DefaultLengthOfMysqlTypes[col.Tp] * 8)\n\t\t\tincrementalBits := typeBitsLength - kvcodec.tbl.Meta().AutoRandomBits\n\t\t\thasSignBit := !mysql.HasUnsignedFlag(col.Flag)\n\t\t\tif hasSignBit {\n\t\t\t\tincrementalBits--\n\t\t\t}\n\t\t\t_ = kvcodec.tbl.RebaseAutoID(kvcodec.se, value.GetInt64()&((1<<incrementalBits)-1), false, autoid.AutoRandomType)\n\t\t}\n\t\tif isAutoIncCol {\n\t\t\t// TODO use auto incremental type\n\t\t\t_ = kvcodec.tbl.RebaseAutoID(kvcodec.se, getAutoRecordID(value, &col.FieldType), false, autoid.RowIDAllocType)\n\t\t}\n\t}\n\n\tif TableHasAutoRowID(kvcodec.tbl.Meta()) {\n\t\tj := columnPermutation[len(cols)]\n\t\tif j >= 0 && j < len(row) {\n\t\t\tvalue, err = table.CastValue(kvcodec.se, row[j], extraHandleColumnInfo, false, false)\n\t\t} else {\n\t\t\tvalue, err = types.NewIntDatum(rowID), nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, 0, errors.Trace(err)\n\t\t}\n\t\trecord = append(record, value)\n\t\t_ = kvcodec.tbl.RebaseAutoID(kvcodec.se, value.GetInt64(), false, autoid.RowIDAllocType)\n\t}\n\t_, err = kvcodec.tbl.AddRecord(kvcodec.se, record)\n\tif err != nil {\n\t\tlog.Error(\"kv add Record failed\",\n\t\t\tzapRow(\"originalRow\", row),\n\t\t\tzapRow(\"convertedRow\", record),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn nil, 0, errors.Trace(err)\n\t}\n\n\tpairs, size := kvcodec.se.takeKvPairs()\n\tkvcodec.recordCache = record[:0]\n\treturn Pairs(pairs), size, nil\n}", "func (q *Query) Batch(n int) *Query {\n\tq.q = q.q.Batch(n)\n\treturn q\n}", "func (table *Table) CountRecord(db DB, field Field, record Map, excludeSelf bool, selector sqlbuilder.Selector, args ...interface{}) (int64, error) {\n\tif excludeSelf {\n\t\tqueryPK, argsPK, err := table.WherePrimaryKey(false, true, record)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tselector = selector.WhereAnd(queryPK)\n\t\targs = append(args, argsPK...)\n\t}\n\tif err := table.Open(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn table.CountValue(db, field, record[table.keysMap[field.Name]], selector, args...)\n}", "func (recBuf *recBuf) newRecordBatch(pr promisedRec) *recBatch {\n\tconst recordBatchOverhead = 4 + // array len\n\t\t8 + // firstOffset\n\t\t4 + // batchLength\n\t\t4 + // partitionLeaderEpoch\n\t\t1 + // magic\n\t\t4 + // crc\n\t\t2 + // attributes\n\t\t4 + // lastOffsetDelta\n\t\t8 + // firstTimestamp\n\t\t8 + // maxTimestamp\n\t\t8 + // producerID\n\t\t2 + // producerEpoch\n\t\t4 + // seq\n\t\t4 // record array length\n\tb := &recBatch{\n\t\towner: recBuf,\n\t\tfirstTimestamp: pr.Timestamp.UnixNano() / 1e6,\n\t\trecords: (*(emptyRecordsPool.Get().(*[]promisedNumberedRecord)))[:0],\n\t}\n\tpnr := promisedNumberedRecord{\n\t\tb.calculateRecordNumbers(pr.Record),\n\t\tpr,\n\t}\n\tb.records = append(b.records, pnr)\n\tb.wireLength = recordBatchOverhead + pnr.wireLength\n\tb.v1wireLength = messageSet1Length(pr.Record)\n\treturn b\n}", "func (p *Provider) record(tx *lease.Tx) {\n\tvar ops uint64 // Total number of consumptive ops (really op effects)\n\n\tfor _, op := range tx.Ops() {\n\t\tif op.Type == lease.Update && op.UpdateType() == lease.Renew {\n\t\t\t// Don't record renewals\n\t\t\tcontinue\n\t\t}\n\t\tfor _, effect := range op.Effects() {\n\t\t\tif !effect.Consumptive() {\n\t\t\t\t// Only record effects that affect consumption\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.log.Printf(\"TX %s\", effect.String())\n\t\t\tops++\n\t\t}\n\t}\n\n\tp.add(ops)\n}", "func (c *Cache) recordUpdate(p *partition, bytesAdded, bytesGuessed, entriesAdded int32) {\n\t// This method is always called while p.mu is held.\n\t// The below code takes care to ensure that all bytes in c due to p are\n\t// updated appropriately.\n\n\t// NB: The loop and atomics are used because p.size can be modified\n\t// concurrently to calls to recordUpdate. In all cases where p.size is updated\n\t// outside of this function occur while c.mu is held inside of c.Add. These\n\t// occur when either:\n\t//\n\t// 1) a new write adds its guessed write size to p\n\t// 2) p is evicted to make room for a write\n\t//\n\t// Thus p.size is either increasing or becomes evicted while we attempt to\n\t// record the update to p. Once p is evicted it stays evicted forever.\n\t// These facts combine to ensure that p.size never becomes negative from the\n\t// below call to add.\n\n\tdelta := bytesAdded - bytesGuessed\n\tfor {\n\t\tcurSize := p.loadSize()\n\t\tif curSize == evicted {\n\t\t\treturn\n\t\t}\n\t\tnewSize := curSize.add(delta, entriesAdded)\n\t\tif updated := p.setSize(curSize, newSize); updated {\n\t\t\tc.updateGauges(c.addBytes(delta), c.addEntries(entriesAdded))\n\t\t\treturn\n\t\t}\n\t}\n}", "func (info HistogramFloat64) Record(e *Config, key *keys.Float64) {\n\tdata := &HistogramFloat64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func testGetN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Get(Key(i))\n\t}\n}", "func RecordIoStreamBenchmark(b *testing.B, newIoStream func() rangedb.RecordIoStream) {\n\tb.Helper()\n\n\trecordTotals := []int{1, 10, 100, 1000}\n\tfor _, totalRecords := range recordTotals {\n\t\tbenchNReads(b, totalRecords, newIoStream)\n\t}\n\tfor _, totalRecords := range recordTotals {\n\t\tbenchNWrites(b, totalRecords, newIoStream)\n\t}\n}", "func (t *ZramInfoTracker) Record(pv *perf.Values) {\n\tif !t.hasZram {\n\t\treturn\n\t}\n\n\tfor i, stat := range t.stats {\n\t\tpv.Set(perf.Metric{\n\t\t\tName: t.prefix + \"RAM.Zram.\" + zramFieldNames[i],\n\t\t\tUnit: \"bytes\",\n\t\t\tDirection: perf.SmallerIsBetter,\n\t\t}, stat)\n\t}\n}", "func getRecordWrapper(numFound int, keys [][]byte, pointers []interface{}) (records Records, err error) {\n\tif numFound == 0 {\n\t\treturn nil, ErrScansNoResult\n\t}\n\n\trecords = Records{}\n\tfor i := 0; i < numFound; i++ {\n\t\trecords = append(records, pointers[i].(*Record))\n\t}\n\n\treturn records, nil\n}", "func (metric *Float64Metric) Record(tags map[string]string, measurement float64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (conn *Connection) GetLimitedRecords(q interface{}, n int, doc interface{}, fields ...string) error {\n\tif len(fields) == 0 {\n\t\treturn conn.collection.Find(q).Limit(n).All(doc)\n\t}\n\n\treturn conn.collection.Find(q).Sort(fields...).Limit(n).All(doc)\n}", "func testMapSetN(n int, m map[Key]interface{}) {\n\tfor i := 0; i < n; i++ {\n\t\tm[Key(i)] = i\n\t}\n}", "func (x *Writer) emitDataRecord(p []byte) error {\n\t// collect all the stuff that goes into this type of record\n\tvar data = []interface{}{\n\t\tbyte(len(p)), // byte count\n\t\tx.addr, // standard 16-bit base address\n\t\tbyte(Data), // record type\n\t\tp, // slice of data\n\t}\n\n\terr := x.emitRecord(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"emitDataRecord: %v\", err)\n\t}\n\n\tx.addr += uint16(len(p))\n\n\treturn nil\n}", "func (ix *IndexedBucket) List(offset, size int) ([]Record, int, error) {\n\ttotal := 0\n\tvar ret []Record = nil\n\tviewFn := func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(ix.mainBucket)\n\t\tnEntries := bucket.Stats().KeyN\n\n\t\t// If size <= 0 then we want all entries.\n\t\tif size <= 0 {\n\t\t\tsize = nEntries\n\t\t}\n\t\tresultSize := util.MaxInt(0, util.MinInt(nEntries-offset, size))\n\t\tif resultSize == 0 {\n\t\t\tret = []Record{}\n\t\t\treturn nil\n\t\t}\n\n\t\tcursor := bucket.Cursor()\n\t\t_, val := cursor.First()\n\n\t\t// TODO(stephana): This is definitely inefficient, but there is no\n\t\t// option in boltdb to address a specific element by index. If this is\n\t\t// too slow we can add an additional pseudo index for issue ids.\n\n\t\t// Skip the first entries if offset > 0.\n\t\tfor i := 0; i < offset; i++ {\n\t\t\t_, val = cursor.Next()\n\t\t}\n\n\t\tallEntries := make([]Record, resultSize, resultSize)\n\t\tvar err error\n\t\tvar iRec interface{}\n\t\t// Note: We are guaranteed to have resultSize records in the database.\n\t\tfor i := 0; i < resultSize; i++ {\n\t\t\tif iRec, err = ix.codec.Decode(val); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tallEntries[i] = iRec.(Record)\n\t\t\t_, val = cursor.Next()\n\t\t}\n\n\t\t// Success assign the results now.\n\t\tret = allEntries\n\t\ttotal = nEntries\n\t\treturn nil\n\t}\n\n\terr := ix.DB.View(viewFn)\n\treturn ret, total, err\n}", "func (c *Prometheus) TrackMetricN(section string, operation *bucket.MetricOperation, n int) Client {\n\tb := bucket.NewPrometheus(section, operation, true, c.unicode)\n\tmetric := b.Metric()\n\tmetricTotal := b.MetricTotal()\n\n\tmetricInc := c.getIncrementer(metric)\n\tmetricTotalInc := c.getIncrementer(metricTotal)\n\n\tmetric = c.prepareMetric(metric)\n\tmetricTotal = c.prepareMetric(metricTotal)\n\tmetricInc.IncrementN(metric, n, operation.Labels)\n\tmetricTotalInc.IncrementN(metricTotal, n, operation.Labels)\n\n\treturn c\n}", "func BenchmarkCloneByMakeCap_0_AndAppendN(b *testing.B) {\n\tbenchmarkCloneByMakeCapAndAppendN(b.N, 0)\n}", "func (i *InMemoryPlayerStore) RecordWin(name string) {\n\ti.store[name]++\n}", "func (s *Service) Records(c context.Context, types []int64, mid, stime, etime int64, order, sort string, pn, ps int32) (res []*model.Record, total int32, err error) {\n\tvar midAts []int64\n\tif res, total, err = s.search.RecordPaginate(c, types, mid, stime, etime, order, sort, pn, ps); err != nil {\n\t\tlog.Error(\"s.search.RecordPaginate(%d,%d,%d,%d,%s,%s) error(%v)\", mid, sort, pn, ps, stime, etime, err)\n\t\treturn\n\t}\n\tif res == nil {\n\t\tres = _emptyRecords\n\t\treturn\n\t}\n\tfor _, r := range res {\n\t\tr.Message = template.HTMLEscapeString(r.Message)\n\t\tif len(r.Ats) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tvar ats []int64\n\t\tif ats, err = xstr.SplitInts(r.Ats); err != nil {\n\t\t\tlog.Error(\"xstr.SplitInts(%s) error(%v)\", r.Ats, err)\n\t\t\terr = nil\n\t\t}\n\t\tmidAts = append(midAts, ats...)\n\t}\n\tif len(midAts) == 0 {\n\t\treturn\n\t}\n\taccMap, _ := s.getAccInfo(c, midAts)\n\tfor _, r := range res {\n\t\tr.FillAts(accMap)\n\t}\n\treturn\n}", "func (d *DBClient) RecordsCount(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tcount, err := d.Cache.RecordsCount()\n\n\tif err == nil {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tvar response recordsCount\n\t\tresponse.Count = count\n\t\tb, err := json.Marshal(response)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Error\": err.Error(),\n\t\t}).Error(\"Failed to get data from cache!\")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(500) // can't process this entity\n\t\treturn\n\t}\n}", "func (m *metricFlinkOperatorRecordCount) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (w *RecordWriter) Write(record []byte) (int, error) {\n\t_, err := w.Writer.Write([]byte{rs})\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tn, err := w.Writer.Write(record)\n\treturn n + 1, err\n}", "func (s *Collector) Record(name string, stats []*Stat) error {\n\treturn NOT_IMPLEMENTED\n}", "func (c *cachestub) NewRecord(r cache.Record) error {\n\treturn nil\n}", "func (wl *WriteLog) WriteRecord(rec *EncodedRecord) (offset uint32, err error) {\n\tif len(rec.key) > maxKeyLen {\n\t\treturn 0, ErrKeyTooLong\n\t}\n\n\tsize := wl.logw.Size()\n\tif size >= wl.maxSize {\n\t\treturn 0, ErrWriteLogFull\n\t}\n\toffset = uint32(size)\n\n\t// Write to the log\n\tbinary.BigEndian.PutUint64(wl.scratch, uint64(rec.t))\n\tnk := binary.PutUvarint(wl.scratch[8:], uint64(len(rec.key)))\n\tcopy(wl.scratch[8+nk:], rec.key)\n\n\tnv := binary.PutUvarint(wl.scratch[8+nk+len(rec.key):], uint64(len(rec.snappyVal)))\n\tif _, err := wl.logw.Write(wl.scratch[:8+nk+len(rec.key)+nv]); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err := wl.logw.Write(rec.snappyVal); err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Write to the index\n\twl.scratch[0] = 1\n\tcopy(wl.scratch[1:], rec.hash[:])\n\n\tif offset <= wl.lastOffset {\n\t\tpanic(\"offset is smaller than lastOffset\")\n\t}\n\toff := offset - wl.lastOffset\n\twl.lastOffset = offset\n\tno := binary.PutUvarint(wl.scratch[nk+len(rec.hash):], uint64(off))\n\tif _, err := wl.idxw.Write(wl.scratch[:nk+len(rec.hash)+no]); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn offset, nil\n}", "func (p *SimplePipeline) DoN(n int, fs ...ProcessFunc) (total uint) {\n\ttotal = uint(0)\n\tread := p.BlockSize()\n\tfor i := 0; i < n && read != p.BlockSize(); i++ {\n\t\t// TODO(jwall): Is it safe to share the buffer?\n\t\tout := NewSimpleBuffer(p.BufSize())\n\t\tdefer out.Free()\n\t\tread = p.do(fs)\n\t\ttotal += read\n\t}\n\treturn\n}", "func (b *Buffer) Store(record *data.Record) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.records = append(b.records, record)\n\n\tif len(b.records) >= b.bufferSize {\n\t\tb.flush()\n\t}\n}", "func (o *EntryTracker) Record() *EntryRecord {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\n\tvar r EntryRecord\n\tif len(o.streams) > 0 {\n\t\tr.Streams = make(map[types.StreamPath]*StreamEntryRecord, len(o.streams))\n\t\tfor k, v := range o.streams {\n\t\t\tr.Streams[k] = v.record()\n\t\t}\n\t}\n\treturn &r\n}", "func FixedLengthRecordDataset(scope *Scope, filenames tf.Output, header_bytes tf.Output, record_bytes tf.Output, footer_bytes tf.Output, buffer_size tf.Output, optional ...FixedLengthRecordDatasetAttr) (handle tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"FixedLengthRecordDataset\",\n\t\tInput: []tf.Input{\n\t\t\tfilenames, header_bytes, record_bytes, footer_bytes, buffer_size,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (f *flusher) RecordNumeric64(mtype int, name string, value num64.Numeric64, flush bool) {\n\tf.mu.Lock()\n\tf.sink.RecordNumeric64(mtype, name, value)\n\tif flush {\n\t\tf.sink.Flush()\n\t}\n\tf.mu.Unlock()\n}", "func (err *DuplicatedRecord) DuplicatedRecord() {}", "func addValuesAtIndex(store *btts.BigTableTraceStore, index int32, keyValues map[string]float32, filename string, ts time.Time) error {\n\tps := paramtools.ParamSet{}\n\tparams := []paramtools.Params{}\n\tvalues := []float32{}\n\tfor k, v := range keyValues {\n\t\tp, err := query.ParseKey(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tps.AddParams(p)\n\t\tparams = append(params, p)\n\t\tvalues = append(values, v)\n\t}\n\treturn store.WriteTraces(index, params, values, ps, filename, ts)\n}", "func NewRecord(body string, values map[string]interface{}) Record {\n\td := make(Record, len(values)+1)\n\tfor k, v := range values {\n\t\td[k] = v\n\t}\n\td[BodyField] = body\n\treturn d\n}", "func TestRecord(t *testing.T) {\n\terr := testDbf.GoTo(1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// test if the record is deleted\n\tdeleted, err := testDbf.Deleted()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !deleted {\n\t\tt.Fatal(\"Record should be deleted\")\n\t}\n\n\t// read the same record using Record() and RecordAt()\n\trecs := [2]*Record{}\n\trecs[0], err = testDbf.Record()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trecs[1], err = testDbf.RecordAt(1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor irec, rec := range recs {\n\t\tfor _, want := range wantValues {\n\t\t\tval, err := rec.Field(want.pos)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tstrval := strings.TrimSpace(fmt.Sprintf(\"%v\", val))\n\t\t\tstrtype := fmt.Sprintf(\"%T\", val)\n\n\t\t\tif want.strval != strval || want.strtype != strtype {\n\t\t\t\tt.Errorf(\"Record %d: Wanted value %s with type %s, have value %s with type %s\", irec, want.strval, want.strtype, strval, strtype)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestRecordTooBig(t *testing.T) {\n\tvar r Record\n\tkey := randomString(10)\n\n\t// set a big value for random key, expect error\n\tstr := msg.String(randomString(SizeLimit))\n\tr.Set(WithEntry(key, &str))\n\tif err := signTest([]byte{5}, &r); err != errTooBig {\n\t\tt.Fatalf(\"expected to get errTooBig, got %#v\", err)\n\t}\n\tstr2 := msg.String(randomString(100))\n\t// set an acceptable value for random key, expect no error\n\tr.Set(WithEntry(key, &str2))\n\trequire.NoError(t, signTest([]byte{5}, &r))\n}", "func BenchmarkLastNSumWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastNSum\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func runTrial(n int, t *testing.T) float64 {\n\tb := newBloom()\n\tkeys := make(map[string]struct{})\n\n\tfor i := 0; i < n; i++ {\n\t\tkey := fmt.Sprint(rand.Int31())\n\t\tkeys[key] = struct{}{}\n\t\tb.Add([]byte(key))\n\t}\n\n\t// Validate all added keys still test ok.\n\tfor k := range keys {\n\t\tif !b.Test([]byte(k)) {\n\t\t\tt.Fatalf(\"b.Test(%v)=false, expected true for added key\", string(k))\n\t\t}\n\t}\n\n\t// Validate random keys\n\tvar hits, total int\n\tfor i := 0; i < 5000; i++ {\n\t\tkey := fmt.Sprint(rand.Int31())\n\t\tif _, found := keys[key]; !found {\n\t\t\tif b.Test([]byte(key)) {\n\t\t\t\thits++\n\t\t\t}\n\t\t}\n\t\ttotal++\n\t}\n\n\treturn float64(hits) / float64(total)\n}", "func (cache *Cache) Store(seqno uint16, timestamp uint32, keyframe bool, marker bool, buf []byte) (uint16, uint16) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\n\tif !cache.lastValid || seqnoInvalid(seqno, cache.last) {\n\t\tcache.last = seqno\n\t\tcache.lastValid = true\n\t\tcache.expected++\n\t\tcache.received++\n\t} else {\n\t\tcmp := compare(cache.last, seqno)\n\t\tif cmp < 0 {\n\t\t\tcache.received++\n\t\t\tcache.expected += uint32(seqno - cache.last)\n\t\t\tif seqno < cache.last {\n\t\t\t\tcache.cycle++\n\t\t\t}\n\t\t\tcache.last = seqno\n\t\t\tif cache.keyframeValid &&\n\t\t\t\tcompare(cache.keyframe, seqno) > 0 {\n\t\t\t\tcache.keyframeValid = false\n\t\t\t}\n\t\t} else if cmp > 0 {\n\t\t\tif cache.received < cache.expected {\n\t\t\t\tcache.received++\n\t\t\t}\n\t\t}\n\t}\n\tcache.bitmap.set(seqno)\n\n\tif keyframe {\n\t\tcache.keyframe = seqno\n\t\tcache.keyframeValid = true\n\t}\n\n\ti := cache.tail\n\tcache.entries[i].seqno = seqno\n\tcopy(cache.entries[i].buf[:], buf)\n\tlam := uint16(len(buf))\n\tif marker {\n\t\tlam |= 0x8000\n\t}\n\tcache.entries[i].lengthAndMarker = lam\n\tcache.entries[i].timestamp = timestamp\n\tcache.tail = (i + 1) % uint16(len(cache.entries))\n\n\treturn cache.bitmap.first, i\n}", "func Record(pin uint8) {\n\tif err := rpio.Open(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rpio.Close()\n\n\ttype Edge struct {\n\t\tV uint8\n\t\tT time.Time\n\t}\n\txs := make([]Edge, 0, 2000)\n\n\tp := rpio.Pin(pin)\n\tp.Input()\n\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGINT)\n\n\tx := p.Read()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-ch:\n\t\t\trpio.Close()\n\t\t\tbreak loop\n\t\tdefault:\n\t\t}\n\n\t\tv := p.Read()\n\t\tif v == x {\n\t\t\tcontinue\n\t\t}\n\t\tx = v\n\n\t\t// Do as little as possible in this loop, or we'll miss\n\t\t// some edges. For instance, fmt.Println is way, way too\n\t\t// slow.\n\t\txs = append(xs, Edge{\n\t\t\tT: time.Now(),\n\t\t\tV: uint8(v),\n\t\t})\n\t}\n\n\tif len(xs) < 2 {\n\t\tlog.Println(\"No edges detected\")\n\t\treturn\n\t}\n\n\tfor i := 1; i < len(xs); i++ {\n\t\td := xs[i].T.Sub(xs[i-1].T)\n\t\tfmt.Printf(\"%d %6d\\n\", xs[i-1].V, int(d/time.Microsecond))\n\t}\n}", "func (e *LogLoss) Record(probability float64, weight float64) {\n\te.mu.Lock()\n\te.weight += weight\n\te.sum += weight * math.Log(probability+e.Epsilon)\n\te.mu.Unlock()\n}", "func (h *timeHistogram) record(duration int64) {\n\t// If the duration is negative, capture that in underflow.\n\tif duration < 0 {\n\t\th.underflow.Add(1)\n\t\treturn\n\t}\n\t// bucketBit is the target bit for the bucket which is usually the\n\t// highest 1 bit, but if we're less than the minimum, is the highest\n\t// 1 bit of the minimum (which will be zero in the duration).\n\t//\n\t// bucket is the bucket index, which is the bucketBit minus the\n\t// highest bit of the minimum, plus one to leave room for the catch-all\n\t// bucket for samples lower than the minimum.\n\tvar bucketBit, bucket uint\n\tif l := sys.Len64(uint64(duration)); l < timeHistMinBucketBits {\n\t\tbucketBit = timeHistMinBucketBits\n\t\tbucket = 0 // bucketBit - timeHistMinBucketBits\n\t} else {\n\t\tbucketBit = uint(l)\n\t\tbucket = bucketBit - timeHistMinBucketBits + 1\n\t}\n\t// If the bucket we computed is greater than the number of buckets,\n\t// count that in overflow.\n\tif bucket >= timeHistNumBuckets {\n\t\th.overflow.Add(1)\n\t\treturn\n\t}\n\t// The sub-bucket index is just next timeHistSubBucketBits after the bucketBit.\n\tsubBucket := uint(duration>>(bucketBit-1-timeHistSubBucketBits)) % timeHistNumSubBuckets\n\th.counts[bucket*timeHistNumSubBuckets+subBucket].Add(1)\n}", "func (f *VRFTest) RecordValues(b ginkgo.Benchmarker) error {\n\t// can't estimate perf metrics in soak mode\n\tif f.TestOptions.NumberOfRounds == 0 {\n\t\treturn nil\n\t}\n\tactions.SetChainlinkAPIPageSize(f.chainlinkClients, f.TestOptions.NumberOfRounds*f.TestOptions.NumberOfContracts)\n\tif err := f.testResults.setResultStartTimes(f.chainlinkClients, f.jobMap); err != nil {\n\t\treturn err\n\t}\n\treturn f.testResults.calculateLatencies(b)\n}", "func (t *tableCommon) UpdateRecord(ctx sessionctx.Context, h int64, oldData, newData []types.Datum, touched []bool) error {\n\ttrace_util_0.Count(_tables_00000, 65)\n\ttxn, err := ctx.Txn(true)\n\tif err != nil {\n\t\ttrace_util_0.Count(_tables_00000, 75)\n\t\treturn err\n\t}\n\n\t// TODO: reuse bs, like AddRecord does.\n\ttrace_util_0.Count(_tables_00000, 66)\n\tbs := kv.NewBufferStore(txn, kv.DefaultTxnMembufCap)\n\n\t// rebuild index\n\terr = t.rebuildIndices(ctx, bs, h, touched, oldData, newData)\n\tif err != nil {\n\t\ttrace_util_0.Count(_tables_00000, 76)\n\t\treturn err\n\t}\n\ttrace_util_0.Count(_tables_00000, 67)\n\tnumColsCap := len(newData) + 1 // +1 for the extra handle column that we may need to append.\n\n\tvar colIDs, binlogColIDs []int64\n\tvar row, binlogOldRow, binlogNewRow []types.Datum\n\tcolIDs = make([]int64, 0, numColsCap)\n\trow = make([]types.Datum, 0, numColsCap)\n\tif shouldWriteBinlog(ctx) {\n\t\ttrace_util_0.Count(_tables_00000, 77)\n\t\tbinlogColIDs = make([]int64, 0, numColsCap)\n\t\tbinlogOldRow = make([]types.Datum, 0, numColsCap)\n\t\tbinlogNewRow = make([]types.Datum, 0, numColsCap)\n\t}\n\n\ttrace_util_0.Count(_tables_00000, 68)\n\tfor _, col := range t.WritableCols() {\n\t\ttrace_util_0.Count(_tables_00000, 78)\n\t\tvar value types.Datum\n\t\tif col.State != model.StatePublic {\n\t\t\ttrace_util_0.Count(_tables_00000, 81)\n\t\t\t// If col is in write only or write reorganization state we should keep the oldData.\n\t\t\t// Because the oldData must be the orignal data(it's changed by other TiDBs.) or the orignal default value.\n\t\t\t// TODO: Use newData directly.\n\t\t\tvalue = oldData[col.Offset]\n\t\t} else {\n\t\t\ttrace_util_0.Count(_tables_00000, 82)\n\t\t\t{\n\t\t\t\tvalue = newData[col.Offset]\n\t\t\t}\n\t\t}\n\t\ttrace_util_0.Count(_tables_00000, 79)\n\t\tif !t.canSkip(col, value) {\n\t\t\ttrace_util_0.Count(_tables_00000, 83)\n\t\t\tcolIDs = append(colIDs, col.ID)\n\t\t\trow = append(row, value)\n\t\t}\n\t\ttrace_util_0.Count(_tables_00000, 80)\n\t\tif shouldWriteBinlog(ctx) && !t.canSkipUpdateBinlog(col, value) {\n\t\t\ttrace_util_0.Count(_tables_00000, 84)\n\t\t\tbinlogColIDs = append(binlogColIDs, col.ID)\n\t\t\tbinlogOldRow = append(binlogOldRow, oldData[col.Offset])\n\t\t\tbinlogNewRow = append(binlogNewRow, value)\n\t\t}\n\t}\n\n\ttrace_util_0.Count(_tables_00000, 69)\n\tkey := t.RecordKey(h)\n\tvalue, err := tablecodec.EncodeRow(ctx.GetSessionVars().StmtCtx, row, colIDs, nil, nil)\n\tif err != nil {\n\t\ttrace_util_0.Count(_tables_00000, 85)\n\t\treturn err\n\t}\n\ttrace_util_0.Count(_tables_00000, 70)\n\tif err = bs.Set(key, value); err != nil {\n\t\ttrace_util_0.Count(_tables_00000, 86)\n\t\treturn err\n\t}\n\ttrace_util_0.Count(_tables_00000, 71)\n\tif err = bs.SaveTo(txn); err != nil {\n\t\ttrace_util_0.Count(_tables_00000, 87)\n\t\treturn err\n\t}\n\ttrace_util_0.Count(_tables_00000, 72)\n\tctx.StmtAddDirtyTableOP(table.DirtyTableDeleteRow, t.physicalTableID, h, nil)\n\tctx.StmtAddDirtyTableOP(table.DirtyTableAddRow, t.physicalTableID, h, newData)\n\tif shouldWriteBinlog(ctx) {\n\t\ttrace_util_0.Count(_tables_00000, 88)\n\t\tif !t.meta.PKIsHandle {\n\t\t\ttrace_util_0.Count(_tables_00000, 90)\n\t\t\tbinlogColIDs = append(binlogColIDs, model.ExtraHandleID)\n\t\t\tbinlogOldRow = append(binlogOldRow, types.NewIntDatum(h))\n\t\t\tbinlogNewRow = append(binlogNewRow, types.NewIntDatum(h))\n\t\t}\n\t\ttrace_util_0.Count(_tables_00000, 89)\n\t\terr = t.addUpdateBinlog(ctx, binlogOldRow, binlogNewRow, binlogColIDs)\n\t\tif err != nil {\n\t\t\ttrace_util_0.Count(_tables_00000, 91)\n\t\t\treturn err\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 73)\n\tcolSize := make(map[int64]int64)\n\tfor id, col := range t.Cols() {\n\t\ttrace_util_0.Count(_tables_00000, 92)\n\t\tval := int64(len(newData[id].GetBytes()) - len(oldData[id].GetBytes()))\n\t\tif val != 0 {\n\t\t\ttrace_util_0.Count(_tables_00000, 93)\n\t\t\tcolSize[col.ID] = val\n\t\t}\n\t}\n\ttrace_util_0.Count(_tables_00000, 74)\n\tctx.GetSessionVars().TxnCtx.UpdateDeltaForTable(t.physicalTableID, 0, 1, colSize)\n\treturn nil\n}", "func (b *profBuf) canWriteTwoRecords(nstk1, nstk2 int) bool {\n\tbr := b.r.load()\n\tbw := b.w.load()\n\n\t// room for tag?\n\tif countSub(br.tagCount(), bw.tagCount())+len(b.tags) < 2 {\n\t\treturn false\n\t}\n\n\t// room for data?\n\tnd := countSub(br.dataCount(), bw.dataCount()) + len(b.data)\n\n\t// first record\n\twant := 2 + int(b.hdrsize) + nstk1\n\ti := int(bw.dataCount() % uint32(len(b.data)))\n\tif i+want > len(b.data) {\n\t\t// Can't fit in trailing fragment of slice.\n\t\t// Skip over that and start over at beginning of slice.\n\t\tnd -= len(b.data) - i\n\t\ti = 0\n\t}\n\ti += want\n\tnd -= want\n\n\t// second record\n\twant = 2 + int(b.hdrsize) + nstk2\n\tif i+want > len(b.data) {\n\t\t// Can't fit in trailing fragment of slice.\n\t\t// Skip over that and start over at beginning of slice.\n\t\tnd -= len(b.data) - i\n\t\ti = 0\n\t}\n\treturn nd >= want\n}", "func (st *Store) overwriteRecord(ip, host, recordType, netview, cidr string) {\n\tst.Records[ip] = make(HostSet)\n\tst.Records[ip][host] = recordType\n\tst.Netviews[ip] = netview\n\tst.Cidrs[ip] = cidr\n}", "func (g *Gauge) Record(value int64) {\n\tatomic.StoreInt64(&g.value, value)\n}", "func writeRecords(\n\tclient *as.Client,\n\tsize int,\n) {\n var hospitals []string\n var insurers []string\n\n\tfor i := 0; i < size; i++ {\n // A new claims record\n var claim shared.Claim\n rand.Seed(time.Now().UnixNano())\n \n /*\n * Populate the fields of this claim record\n */\n claim.ClaimID = uuid.New().String()\n\n // HospitalID\n // Add entries with exisiting HospID or create a new HospID?\n if (rand.Intn(2) == 1) && len(hospitals) > 0 {\n // Pick from existing entries\n claim.HospitalID = hospitals[rand.Intn(len(hospitals))] \n } else {\n // New Hospital ID\n claim.HospitalID = uuid.New().String()\n hospitals = append(hospitals, claim.HospitalID)\n }\n\n // InsurerID\n // Add entries with exisiting InsurerID or create a new InsurerID?\n if (rand.Intn(2)==1) && len(insurers) > 0 {\n // Pick from existing entries\n claim.InsurerID = insurers[rand.Intn(len(insurers))] \n } else {\n // New Insurer ID\n claim.InsurerID =uuid.New().String() \n insurers = append(insurers, claim.InsurerID)\n }\n\n //ClaimFileTime - Subratract years,months and days from today\n claimTime := time.Now().AddDate(-1*rand.Intn(2), -1*rand.Intn(11), -1*rand.Intn(31))\n claim.ClaimFileTime = claimTime.Unix() \n\n //DischargeTime - a random hour between [0,25] subtracted from claim file time\n //25 is chosen so that some records wil exceed the 24 hour discharge filing period\n claim.DischargeTime = claimTime.Add(time.Duration(-1*rand.Intn(25))*time.Hour).Unix()\n \n //ClaimAmt - Minimum is Rs.10, Maximum Rs. 1cr\n minAmt := 10\n maxAmt := 10000000\n claim.ClaimAmt = float32(minAmt + rand.Intn(maxAmt)) * rand.Float32()\n\n //Penalty, to a maximum of the claimAmt\n claim.Penalty = 0.01*claim.ClaimAmt*float32(rand.Intn(100))\n\n //ClaimState\n claim.ClaimState = shared.ClaimState(int(shared.ClaimFiled) + rand.Intn(int(shared.MaxClaimState)))\n\n //ClaimType\n switch claim.ClaimState {\n case shared.ClaimFiled: \n fallthrough\n case shared.ClaimDocumented:\n fallthrough\n case shared.ClaimOnHold:\n claim.ClaimType = shared.ClaimNoActionType\n\n case shared.ClaimApproved:\n fallthrough\n case shared.ClaimPaid:\n claim.ClaimType = shared.ClaimAcceptedType\n\n case shared.ClaimRejected:\n claim.ClaimType = shared.ClaimRejectedType\n \n\n default: // ClaimAcknowledged, or ClaimContested\n if rand.Float32() >= 0.5 {\n claim.ClaimType = shared.ClaimAcceptedType\n } else {\n claim.ClaimType = shared.ClaimRejectedType\n }\n }\n\n //Audit Status\n if (claim.ClaimState != shared.ClaimFiled &&\n claim.ClaimState != shared.ClaimDocumented) {\n numAudited := float32(0.1) //10% get audited\n numFraud := float32(0.01) //1% are fradulent\n auditRand := rand.Float32()\n if auditRand < numFraud/2 {\n claim.AuditStatus = shared.AuditedAndFraud\n } else if auditRand < numFraud {\n claim.AuditStatus = shared.AuditedAndNotFraud\n } else if auditRand < numAudited {\n claim.AuditStatus = shared.AuditUnderway\n } else {\n claim.AuditStatus = shared.NotAudited\n }\n }\n\n //AuditLog\n if (claim.AuditStatus != shared.NotAudited) {\n claim.AuditLog = \"The case was audited\"\n }\n \n //logTrail - This is updated as the claim's state changes.\n // This is used in debugging, but will be left empty in this dummy DB\n\n //rejectCode\n if claim.ClaimType == shared.ClaimRejectedType { \n claim.RejectCode = shared.RejectCode(rand.Intn(int(shared.MaxRejectCodes)) + 1)\n }\n\n //TDS Head\n if claim.ClaimType == shared.ClaimAcceptedType {\n claim.TDSHead = \"Dr. Rajeev Kapoor\"\n }\n\n //AckTime\n ackTime := claimTime.AddDate(0, rand.Intn(2),rand.Intn(31))\n claim.AckTime = ackTime.Unix()\n\n //PaymentInfo\n paymentInfo := shared.PaymentInfo{123456.70, ackTime.Add(time.Duration(-3)*time.Hour).Unix(), \n claim.InsurerID, claim.HospitalID, \"YHO2648721KSA\", \"Paid and Approved by Admin of Insurer\" }\n\n //Marshal PaymentInfo\n var err error\n claim.PaymentInfo, err = json.Marshal(paymentInfo)\n if err != nil {\n log.Println(\"Marshalling error:\", err)\n }\n\n\t\tkey, _ := as.NewKey(*shared.Namespace, *shared.Set, claim.ClaimID)\n\n // Write all field names and values into the corresponding index of a binMap\n binsMap := make(map[string]interface{})\n\t\tval := reflect.Indirect(reflect.ValueOf(claim))\n for i := 0; i < val.NumField(); i++ {\n binName := val.Type().Field(i).Name\n binValue := val.Field(i).Interface()\n binsMap[binName] = binValue\n\t\t //log.Printf(\"Put: ns=%s set=%s key=%s bin=%s value=%s\",\n\t\t\t// key.Namespace(), key.SetName(), key.Value(), \n // binName, binsMap[binName])\n }\n\t\terr = client.Put(shared.WritePolicy, key, binsMap)\n if err != nil {\n shared.PanicOnError(err)\n }\n\t}\n}", "func (t *BoundedTable) AddRecord(ctx context.Context, r []types.Datum) (int64, error) {\n\tvar recordID int64\n\tvar err error\n\tif t.pkHandleCol != nil {\n\t\trecordID, err = r[t.pkHandleCol.Offset].ToInt64()\n\t\tif err != nil {\n\t\t\treturn invalidRecordID, errors.Trace(err)\n\t\t}\n\t} else {\n\t\trecordID, err = t.alloc.Alloc(t.ID)\n\t\tif err != nil {\n\t\t\treturn invalidRecordID, errors.Trace(err)\n\t\t}\n\t}\n\tcursor := atomic.AddInt64(&t.cursor, 1) - 1\n\tindex := int64(cursor % t.capacity)\n\trecord := newBoundedItem(recordID+initialRecordID, r)\n\tatomic.StorePointer(&t.records[index], unsafe.Pointer(record))\n\treturn recordID + initialRecordID, nil\n}", "func (counter *counter) addCount(n int64) {\n\tcounter.Lock()\n\tdefer counter.Unlock()\n\n\tif n <= 0 {\n\t\treturn\n\t}\n\n\t// Add the ops read and increase the count of operation.\n\t// bytes Number of ops.\n\tcounter.bytes += n\n\tcounter.ops++\n}", "func (n *ns1) upsertRecordWorker(wg *sync.WaitGroup, recID string, rec *dns.Record, count *int32) {\n\terr := n.upsertRecord(recID, rec)\n\tif err != nil {\n\t\tn.log.Error(\"cannot create or update record for service\", \"domain\", rec.Domain, \"type\", rec.Type, \"error\", err.Error())\n\t} else {\n\t\tatomic.AddInt32(count, 1)\n\t}\n\twg.Done()\n}", "func (s Stream) NewTimes(n int32) (capnp.Int64List, error) {\n\tl, err := capnp.NewInt64List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Int64List{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func (records AggregationRecords) Add(raw map[string]interface{}) {\n\tts, ok := raw[\"Timestamp\"]\n\tif !ok {\n\t\treturn\n\t}\n\n\tkey, keys := buildAggregationKey(raw)\n\n\trecord, ok := records[key]\n\tif !ok {\n\t\trecord = NewAggregationRecord()\n\n\t\tms := int64(ts.(float64))\n\t\tt := time.Unix(ms/msToSec, (ms%msToSec)*msToNs)\n\t\t// TODO: 60 is the default. Will eventually be overriden by configuration\n\n\t\trecord.Timestamp = t\n\t\trecord.Keys = keys\n\t}\n\n\taggIntervalEnd := record.Timestamp.Add(defaultIntervalPeriod)\n\trecord.Expiry = max(time.Now(), aggIntervalEnd).Add(transformAggregationRecordDelay)\n\tcfg := providers.Config.RetrieveAgentConfig()\n\n\teventType, ok := raw[\"Type\"].(string)\n\tif !ok {\n\t\tlog.Println(fmt.Sprintf(\"E! 'Type' needs to be a string: %T\", raw[\"Type\"]))\n\t}\n\n\teventDef, hasEventDef := cfg.Definitions.Events.Get(eventType)\n\tfor k, v := range raw {\n\t\tif hasEventDef && record.Samples.ShouldAdd(eventDef.SampleRate) {\n\t\t\tsignature := getSampleSignature(cfg.Definitions, raw)\n\t\t\tif ok := record.Samples.Count(signature); !ok && record.Samples.Len() < eventDef.MaxSampleCount {\n\t\t\t\trecord.Samples.Add(raw)\n\t\t\t}\n\t\t}\n\n\t\tdef, ok := cfg.Definitions.Entries.Get(k)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif def.Type.IsFrequency() {\n\t\t\tswitch val := v.(type) {\n\t\t\tcase string:\n\t\t\t\trecord.addFrequency(k, val)\n\t\t\tcase float64:\n\t\t\t\trecord.addFrequency(k, strconv.Itoa(int(val)))\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if def.Type.IsSEH() {\n\t\t\tswitch val := v.(type) {\n\t\t\tcase int:\n\t\t\t\trecord.addSEH(k, float64(val), defaultSEHMetricWeight)\n\t\t\tcase float64:\n\t\t\t\trecord.addSEH(k, val, defaultSEHMetricWeight)\n\t\t\t}\n\t\t}\n\n\t}\n\n\trecords[key] = record\n}", "func (me *I16HEXFile) AddRecords(r ...Record) error {\n\tfor _, record := range r {\n\t\tif err := me.Add(record); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RecordStats(db *sql.DB) func() {\n\treturn ocsql.RecordStats(db, 10*time.Second)\n}", "func RecordSerializerBenchmark(b *testing.B, newSerializer func() rangedb.RecordSerializer) {\n\tb.Helper()\n\n\tserializer := newSerializer()\n\tBindEvents(serializer)\n\trecord := &rangedb.Record{\n\t\tStreamName: \"thing-c2077176843a49189ae0d746eb131e05\",\n\t\tAggregateType: \"thing\",\n\t\tAggregateID: \"c2077176843a49189ae0d746eb131e05\",\n\t\tGlobalSequenceNumber: 1,\n\t\tStreamSequenceNumber: 1,\n\t\tInsertTimestamp: 0,\n\t\tEventID: \"0899fed048964c2f9c398d7ef623f0c7\",\n\t\tEventType: \"ThingWasDone\",\n\t\tData: ThingWasDone{\n\t\t\tID: \"c2077176843a49189ae0d746eb131e05\",\n\t\t\tNumber: 100,\n\t\t},\n\t\tMetadata: nil,\n\t}\n\tserializedRecord, err := serializer.Serialize(record)\n\trequire.NoError(b, err)\n\n\tb.Run(\"Serialize\", func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, err := serializer.Serialize(record)\n\t\t\tif err != nil {\n\t\t\t\trequire.NoError(b, err)\n\t\t\t}\n\t\t}\n\t})\n\n\tb.Run(\"Deserialize\", func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, err := serializer.Deserialize(serializedRecord)\n\t\t\tif err != nil {\n\t\t\t\trequire.NoError(b, err)\n\t\t\t}\n\t\t}\n\t})\n}", "func (rw *recordWriter) Write(data []byte) (int, error) {\n\n\tif rw.err != nil {\n\t\treturn int(rw.n), nil\n\t}\n\n\tvar n int\n\tn, rw.err = rw.w.Write(data)\n\trw.n += uint64(n)\n\treturn n, nil\n}", "func (s *GameServer) recordWin(winnerId, loserId PlayerId) {\n\tfor _, player := range s.players {\n\t\tif player.PlayerId == winnerId {\n\t\t\tplayer.Rank++\n\t\t\treturn\n\t\t}\n\t}\n}", "func BenchmarkLastNMeanWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastNMean\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func TestUpdateScanRecord(t *testing.T) {\n\ttests := []struct {\n\t\tnumRecords int\n\t\texpectedRecords int\n\t}{\n\t\t{0, 1}, {uptimeMaxNumScanRecords, uptimeMaxNumScanRecords},\n\t}\n\tfor _, test := range tests {\n\t\tinfo := storage.HostInfo{}\n\t\tfor i := 0; i != test.numRecords; i++ {\n\t\t\tinfo.ScanRecords = append(info.ScanRecords, storage.HostPoolScan{\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t\tSuccess: true,\n\t\t\t})\n\t\t}\n\t\tupdateScanRecord(&info, true, uint64(time.Now().Unix()))\n\t\tif len(info.ScanRecords) != test.expectedRecords {\n\t\t\tt.Errorf(\"scan record number not expected. Got %v, Expect %v\", len(info.ScanRecords), test.expectedRecords)\n\t\t}\n\t}\n}", "func (m *HeavySyncMock) StoreRecords(p context.Context, p1 insolar.ID, p2 insolar.PulseNumber, p3 [][]byte) {\n\tcounter := atomic.AddUint64(&m.StoreRecordsPreCounter, 1)\n\tdefer atomic.AddUint64(&m.StoreRecordsCounter, 1)\n\n\tif len(m.StoreRecordsMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.StoreRecordsMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to HeavySyncMock.StoreRecords. %v %v %v %v\", p, p1, p2, p3)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.StoreRecordsMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, HeavySyncMockStoreRecordsInput{p, p1, p2, p3}, \"HeavySync.StoreRecords got unexpected parameters\")\n\n\t\treturn\n\t}\n\n\tif m.StoreRecordsMock.mainExpectation != nil {\n\n\t\tinput := m.StoreRecordsMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, HeavySyncMockStoreRecordsInput{p, p1, p2, p3}, \"HeavySync.StoreRecords got unexpected parameters\")\n\t\t}\n\n\t\treturn\n\t}\n\n\tif m.StoreRecordsFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to HeavySyncMock.StoreRecords. %v %v %v %v\", p, p1, p2, p3)\n\t\treturn\n\t}\n\n\tm.StoreRecordsFunc(p, p1, p2, p3)\n}", "func ReaderNumRecordsProducedV2(scope *Scope, reader_handle tf.Output) (records_produced tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"ReaderNumRecordsProducedV2\",\n\t\tInput: []tf.Input{\n\t\t\treader_handle,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}" ]
[ "0.71943164", "0.7072831", "0.6477091", "0.6475133", "0.6234947", "0.5999816", "0.5793503", "0.5729439", "0.5686127", "0.5629613", "0.5531872", "0.5474315", "0.54651713", "0.5447087", "0.5436784", "0.54320043", "0.5397417", "0.5395058", "0.5277061", "0.52648646", "0.5211917", "0.51828724", "0.5168418", "0.51658994", "0.5161812", "0.5110762", "0.50905806", "0.50624156", "0.504387", "0.5040371", "0.50240874", "0.5020315", "0.5019863", "0.4981038", "0.49639156", "0.48980987", "0.48916903", "0.48739836", "0.485613", "0.48398787", "0.48238406", "0.48215944", "0.48179838", "0.47993731", "0.4792676", "0.4792272", "0.47727448", "0.47720855", "0.47546723", "0.474529", "0.4729158", "0.4728832", "0.47245163", "0.46901217", "0.46890438", "0.46856192", "0.4671223", "0.4668562", "0.4667716", "0.4657862", "0.4657221", "0.4656798", "0.46563527", "0.46504116", "0.46445736", "0.4631257", "0.46128732", "0.46120393", "0.46098116", "0.46071258", "0.45997965", "0.45994815", "0.459907", "0.45921776", "0.45897543", "0.45869333", "0.4584157", "0.45760155", "0.45630318", "0.45607087", "0.45553538", "0.45524764", "0.45445532", "0.45444998", "0.45381624", "0.45381573", "0.45324743", "0.453229", "0.4527546", "0.45269576", "0.452519", "0.45246303", "0.45161483", "0.4513894", "0.4509733", "0.45057252", "0.45041612", "0.44910577", "0.448834", "0.4487676" ]
0.70000136
2
Avg returns the average.
func (c *Counter) Avg() float64 { return c.Sum / float64(c.Count) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cma *CMA) Avg() float64 {\n\treturn cma.avg\n}", "func average(arr []float64) float64 {\n\treturn sum(arr) / float64(len(arr))\n}", "func ExampleAverage() {\n\tvar f float64\n\tf = Average([]float64{1, 2})\n\tfmt.Println(f)\n\t// Output:\n\t// 1.5\n}", "func Average(items []Value) float64 {\n\tif len(items) == 0 {\n\t\treturn 0\n\t}\n\treturn float64(Sum(items)) / float64(len(items))\n}", "func (baseball_player *BaseballPlayer) average() float32 {\n\treturn float32(baseball_player.hits) / float32(baseball_player.atBats)\n}", "func (c *Clac) Avg() error {\n\treturn c.applyFloat(variadic, func(vals []value.Value) (value.Value, error) {\n\t\tsum, _ := reduceFloat(zero, vals, func(a, b value.Value) (value.Value, error) {\n\t\t\treturn binary(a, \"+\", b)\n\t\t})\n\t\treturn binary(sum, \"/\", value.Int(len(vals)))\n\t})\n}", "func (c *AverageDuration) Average() int64 {\n\tcount := c.Count()\n\tif count > 0 {\n\t\treturn c.Sum() / count\n\t}\n\treturn 0\n}", "func Average(values ...float64) float64 {\n\tsum := Sum(values...)\n\treturn sum / float64(len(values))\n}", "func (sc *slidingCounter) Avg() float64 {\n\treturn sc.Sum() / float64(sc.interval)\n}", "func Average(series []Series) (Series, error) {\n\treturn applyOperator(series, OperatorAverage)\n}", "func (s *TrialComponentMetricSummary) SetAvg(v float64) *TrialComponentMetricSummary {\n\ts.Avg = &v\n\treturn s\n}", "func avg(list []int) int {\n\treturn sum(list) / len(list)\n}", "func average(sf ...float64) float64 {\n\ttotal := 0.0\n\tfor _, v := range sf {\n\t\ttotal = total + v\n\n\t}\n\treturn total / float64(len(sf))\n}", "func Average(arr []float64) float64 {\n\tvar total float64\n\tfor _, value := range arr {\n\t\ttotal += value\n\t}\n\treturn total / float64(len(arr))\n}", "func (ws Weights) Avg() float64 {\n\tavg := 0.0\n\tfor _, w := range ws {\n\t\tavg += float64(len(w.Bits)) * w.Value\n\t}\n\treturn avg\n}", "func Average(audiences []db.Audience) int64 {\n\tvar rv int64\n\tfor _, a := range audiences {\n\t\trv += int64(a.Audience)\n\t}\n\n\tif len(audiences) == 0 {\n\t\treturn 0\n\t}\n\n\treturn rv / int64(len(audiences))\n}", "func (r *ImageRef) Average() (float64, error) {\n\tout, err := vipsAverage(r.image)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn out, nil\n}", "func Avg(first Decimal, rest ...Decimal) Decimal {\n\tcount := New(int64(len(rest)+1), 0)\n\tsum := Sum(first, rest...)\n\treturn sum.Div(count)\n}", "func average(data []float64) float64 {\n\tvar average float64\n\tif len(data) == 0 {\n\t\treturn average\n\t}\n\tfor index := 0; index < len(data); index++ {\n\t\taverage += data[index]\n\t}\n\treturn average / float64(len(data))\n}", "func Avg(first Decimal, rest ...Decimal) Decimal {\n\tcount := NewDec(int64(len(rest)+1), 0)\n\tsum := Sum(first, rest...)\n\treturn sum.Div(count)\n}", "func (m *movingAverage) average() (float64, error) {\n\n\tsum := .0\n\n\tif !m.samplingComplete {\n\t\treturn sum, fmt.Errorf(\"cannot compute average without a full sampling\")\n\t}\n\n\tfor _, value := range m.ring {\n\t\tsum += value\n\t}\n\n\treturn sum / float64(m.sampleSize), nil\n}", "func Average(input []float64) float64 {\n\treturn SumFloat64s(input) / float64(len(input))\n}", "func Average(xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\treturn 0\n\t}\n\n\ttotal := 0.0\n\tfor _, v := range xs {\n\t\ttotal += v\n\t}\n\treturn total / float64(len(xs))\n}", "func (m *MovingAverage) Average(dur time.Duration) float64 {\n\taverages := m.Averages(dur)\n\tif len(averages) == 0 {\n\t\treturn 0\n\t}\n\tsum := 0.0\n\tfor _, avg := range averages {\n\t\tsum += avg\n\t}\n\treturn sum / float64(len(averages))\n}", "func avg(dps Series, args ...float64) (a float64) {\n\tfor _, v := range dps {\n\t\ta += float64(v)\n\t}\n\ta /= float64(len(dps))\n\treturn\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func Average(xs []float64) float64 {\n\ttotal := float64(0)\n\tfor _, x := range xs {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(xs))\n}", "func ArithmeticAverage(data []float64) float64 {\r\n\treturn Accumulate(data, 0, func(a float64, b float64) float64 {\r\n\t\treturn a + b\r\n\t}) / float64(len(data))\r\n}", "func average(n ...float64) float64 {\n\tvar total float64\n\tfor _, v := range n {\n\t\ttotal += v\n\t}\n\n\treturn total / float64(len(n))\n}", "func average(arg1, arg2, arg3 float64) float64 {\n\ttotal := arg1 + arg2 + arg3\n\treturn total/3\n}", "func (c *TimeAvgAggregator) Mean() float64 {\n\tif !c.initialized {\n\t\treturn math.NaN()\n\t}\n\tif c.startTime == c.endTime {\n\t\treturn float64(c.endValue)\n\t}\n\treturn float64(c.integral) / float64(c.endTime-c.startTime)\n}", "func Avg(n int64) Option {\n\treturn func(opts *Options) {\n\t\topts.AvgDiv = n\n\t}\n}", "func Average(nums []float64) float64 {\n\ttotal := float64(0)\n\tfor _, num := range nums {\n\t\ttotal += num\n\t}\n\treturn total / float64(len(nums))\n}", "func ComputeAverage(dataPoints []float64) (float64, error) {\n\tif !(len(dataPoints) > 0) {\n\t\treturn 0.0, fmt.Errorf(\"Must provide a non empty collection of data points\")\n\t}\n\n\treturn stat.Mean(dataPoints, nil), nil\n}", "func (t *TTFB) Average(group string) float64 {\n\tvar total float64\n\tvar values []float64\n\n\tfor _, data := range t.Results {\n\t\tif group == connectionTime {\n\t\t\tvalues = append(values, data.Output.ConnectTime)\n\t\t\tcontinue\n\t\t}\n\n\t\tif group == timeToFirstByte {\n\t\t\tvalues = append(values, data.Output.FirstByteTime)\n\t\t\tcontinue\n\t\t}\n\n\t\tif group == totalTime {\n\t\t\tvalues = append(values, data.Output.TotalTime)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// There is no enough data to average.\n\tif len(values) < 3 {\n\t\treturn 0.0\n\t}\n\n\tsort.Float64s(values)\n\n\t// Drop first and last values for accuracy.\n\tfor i := 1; i < len(values)-1; i++ {\n\t\ttotal += values[i]\n\t}\n\n\treturn total / float64(len(values)-2)\n}", "func Average(numbers []float64) float64 {\n\tif len(numbers) == 0 {\n\t\treturn 0\n\t}\n\ttotal := float64(0)\n\tfor _, x := range numbers {\n\t\ttotal += x\n\t}\n\treturn total / float64(len(numbers))\n}", "func main() {\n xs := []float64{98,93,77,82,83}\n fmt.Println(average(xs))\n}", "func Avg(field string) *AggrItem {\n\treturn NewAggrItem(field, AggrAvg, field)\n}", "func (s *SpeedInfo) Average() float64 {\n\tsum := 0.0\n\ti := 0\n\ts.reports.Do(func(rep interface{}) {\n\t\tif rep == nil {\n\t\t\treturn\n\t\t}\n\n\t\tsum += rep.(float64)\n\t\ti++\n\t})\n\n\tif i == 0 {\n\t\treturn 0\n\t}\n\n\treturn sum / float64(i)\n}", "func (s *studentState) avg(q Question) float64 {\n\ttotal := 0.0\n\tconcepts := q.getTrainingConcepts(nil)\n\tfor _, c := range concepts {\n\t\ttotal += s.scores[c]\n\t}\n\treturn total / float64(len(concepts))\n}", "func (epoch *Generation) Average() (fitness, age, complexity float64) {\n\tfitness = epoch.Fitness.Mean()\n\tage = epoch.Age.Mean()\n\tcomplexity = epoch.Compexity.Mean()\n\treturn fitness, age, complexity\n}", "func computeAverage(array []float64) float64 {\n\tresult := 0.0\n\tfor _, item := range array {\n\t\tresult += item\n\t}\n\treturn result / float64(len(array))\n}", "func AVG(hist []float64) float64 {\n\tif len(hist) == 0 {\n\t\treturn 0\n\t}\n\n\tvar sum float64\n\tfor _, v := range hist {\n\t\tsum += v\n\t}\n\n\tsum /= float64(len(hist))\n\treturn sum\n}", "func Average(xs []float64) float64 {\n total := float64(0)\n if len(xs) == 0 {\n return total\n }\n for _, x := range xs {\n total += x\n }\n return total / float64(len(xs))\n}", "func Avg(payments []types.Payment) types.Money {\n\tvar avg, sum types.Money = 0, 0\n\tvar exc = 0\n\tfor _, p := range payments {\n\t\tif p.Status == types.StatusFail {\n\t\t\texc++\n\t\t\tcontinue\n\t\t}\n\t\tsum += p.Amount\n\t}\n\tavg = sum / types.Money(len(payments)-exc)\n\treturn avg\n}", "func Average(slice []float64) (float64, error) {\n\n\tif len(slice) == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Empty\")\n\t}\n\n\tvar sum float64\n\tfor _, n := range slice {\n\t\tsum += n\n\t}\n\n\tavg := sum / float64(len(slice))\n\t// log.Println(\"Slice average\", avg)\n\treturn math.Round(avg*100) / 100, nil\n}", "func average (xs []int) int {\n total := 0\n for _, val := range xs {\n total += val\n }\n return total / len(xs)\n}", "func main() {\n xs := []float64{1,2,3,4}\n avg := m.Average(xs)\n fmt.Println(avg)\n}", "func Average(tas ...*TA) *TA {\n\tln := tas[0].Len()\n\tfor i := 1; i < len(tas); i++ {\n\t\tif n := tas[i].Len(); n > ln {\n\t\t\tln = n\n\t\t}\n\t}\n\n\tout := NewSize(ln, true)\n\tfor i := 0; i < ln; i++ {\n\t\tvar v Decimal\n\t\tfor _, ta := range tas {\n\t\t\tif i < ta.Len() {\n\t\t\t\tv = v.Add(ta.Get(i))\n\t\t\t}\n\t\t}\n\t\tout.Append(v / Decimal(ln))\n\t}\n\n\treturn out\n}", "func average(numbers ...float64) float64 {\n\tvar sum float64 = 0\n\n\tfor _, number := range numbers {\n\t\tsum += number\n\t}\n\n\treturn sum / float64(len(numbers))\n}", "func (a *Average) Get() float64 {\n\treturn a.avg\n}", "func (records DataRecs) Mean() (float64) {\n\n\ttotal := 0.0\n\tfor _, record := range records {\n\t\t//fmt.Printf(\"converting to float: %s\", record.RecordedValue)\n\t\trecordedValue := fromStringToFloat(record.RecordedValue)\n\t\ttotal += recordedValue\n\t}\n\n\tif total == 0.0 {\n\t\treturn total\n\t}\n\n\tmeanValue := total / float64(len(records))\n\tmeanValue = fromStringToFloat(fmt.Sprintf(\"%.2f\", meanValue))\n\treturn meanValue\n}", "func (ff Features) AverageScore() float64 {\n\tif len(ff) == 0 {\n\t\treturn 0\n\t}\n\n\ttotalScore := 0.0\n\tfor _, f := range ff {\n\t\ttotalScore += f.Score\n\t}\n\n\tif totalScore == 0 {\n\t\treturn 0\n\t}\n\n\treturn totalScore / float64(len(ff))\n}", "func avgAggregatedMeasurement(agg []AggregatedMeasurement) AggregatedMeasurement {\n avg := AggregatedMeasurement{}\n t := int64(0)\n for _,v := range agg {\n avg.Name = v.Name\n avg.Jaccard += v.Jaccard\n t += int64(v.ElapsedTime)\n }\n avg.Jaccard = avg.Jaccard / float64(len(agg))\n avg.ElapsedTime = time.Duration(t / int64(len(agg)))\n return avg\n}", "func Average(s *discordgo.Session, m *discordgo.MessageCreate) {\n\tnums := strings.Split(m.Content, \" \")[1:]\n\tvar actualNums []float64\n\n\t// Get numbers\n\tfor _, num := range nums {\n\t\tactualNum, err := strconv.ParseFloat(num, 64)\n\t\tif err == nil {\n\t\t\tactualNums = append(actualNums, actualNum)\n\t\t}\n\t}\n\n\t// Check for more than 1 number\n\tif len(actualNums) <= 1 {\n\t\ts.ChannelMessageSend(m.ChannelID, \"Please provide 2 or more numbers to get the average for!\")\n\t}\n\n\tharmonicMean := mathtools.HarmonicMean(actualNums)\n\tgeometricMean := mathtools.GeometricMean(actualNums)\n\tarithmeticMean := mathtools.ArithmeticMean(actualNums)\n\n\ttext := \"Averages for: \"\n\tfor _, num := range actualNums {\n\t\ttext += strconv.FormatFloat(num, 'f', 2, 64) + \", \"\n\t}\n\ttext = strings.TrimSuffix(text, \", \") + \"\\n\\n\"\n\n\ttext += \"Arithmetic Mean: **\" + strconv.FormatFloat(arithmeticMean, 'f', 2, 64) + \"**\\n\" +\n\t\t\"Geometric Mean: **\" + strconv.FormatFloat(geometricMean, 'f', 2, 64) + \"**\\n\" +\n\t\t\"Harmonic Mean: **\" + strconv.FormatFloat(harmonicMean, 'f', 2, 64) + \"**\\n\"\n\n\ts.ChannelMessageSend(m.ChannelID, text)\n}", "func (sma *SimpleMovingAverage) GetAverage() float64 {\n\treturn sma.average\n}", "func (result Result) Avg() time.Duration {\n\tif result.SuccessCounter == 0 {\n\t\treturn 0\n\t}\n\treturn result.TotalDuration / time.Duration(result.SuccessCounter)\n}", "func Avg(col Columnar) ColumnElem {\n\treturn Function(AVG, col)\n}", "func getAverage(points []Point) Point {\n\tnewPoint := make(Point, len(points[0]))\n\tfor _, point := range points {\n\t\tfor j, val := range point {\n\t\t\tnewPoint[j] += val\n\t\t}\n\t}\n\tfor i := range newPoint {\n\t\tnewPoint[i] = newPoint[i]/float64(len(points))\n\t}\n\treturn newPoint\n}", "func average(numbers ...int) int {\n\ttotal := 0\n\tfor _, v := range numbers {\n\t\ttotal += v\n\t}\n\treturn total / len(numbers)\n}", "func mean(a []float64) (m float64) {\n\tfor _, v := range a {\n\t\tm += v / float64(len(a))\n\t}\n\treturn\n}", "func averageOf(decimalPlaces int, floats ...*float64) string {\n\tvar total, num float64\n\n\tfor _, f := range floats {\n\t\tif f == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnum++\n\n\t\ttotal += *f\n\t}\n\n\tif num == 0 {\n\t\treturn nan\n\t}\n\n\treturn strconv.FormatFloat(total/num, 'f', decimalPlaces, 64)\n}", "func CalculateMean(appNum int, zoneNum int) float64 {\n\tx := float64(appNum / zoneNum)\n\treturn x\n}", "func Mean(v []float64) float64 {\n\ttotal := Sum(v)\n\treturn total / float64(len(v))\n}", "func Avg(pointsPerSide int, dimension int, fn BzFunc) float64 {\n\tN := math.Pow(float64(pointsPerSide), float64(dimension))\n\treturn Sum(pointsPerSide, dimension, fn) / N\n}", "func (s Student) AverageVA() VAScore {\n\n\texp, ach := 0.0, 0.0\n\tn := 0\n\tfor _, r := range s.Results {\n\t\tva := s.SubjectVA(r.Subj)\n\t\tif va.Err == nil {\n\t\t\texp += va.Expected\n\t\t\tach += va.Achieved\n\t\t\tn++\n\t\t}\n\t}\n\n\tif n == 0 {\n\t\treturn VAScore{0.0, 0.0, fmt.Errorf(\"No VA scores\")}\n\t}\n\n\treturn VAScore{exp / float64(n), ach / float64(n), nil}\n}", "func GetAvgStat(rw http.ResponseWriter) error {\n\tavgstat, r := load.Avg()\n\tif r != nil {\n\t\treturn r\n\t}\n\n\treturn share.JSONResponse(avgstat, rw)\n}", "func (a TransactionAmountPerType) GetAverageAmount() float64 {\n\treturn a.average\n}", "func average(x ...float64) (float64, float64) {\n\t// variables for average and total\n\tvar sum, avg float64\n\t// looping for total value\n\tfor _, i := range x {\n\t\tsum += i\n\t}\n\n\t// return total values and average with len function\n\tavg = sum / float64(len(x))\n\treturn sum, avg\n}", "func (indis Individuals) FitAvg() float64 {\n\treturn meanFloat64s(indis.getFitnesses())\n}", "func (c Cell) AverageArea() float64 {\n\treturn AvgAreaMetric.Value(int(c.level))\n}", "func main() {\n\tn := average(43, 56, 87, 12, 45, 57)\n\tfmt.Println(n)\n}", "func main() {\n\tn := average(43, 56, 87, 12, 45, 57)\n\tfmt.Println(n)\n}", "func RecomputeAverage(newSample, oldAvg float64, oldSampleCount uint64) float64 {\n\tnewTotal := (oldAvg * float64(oldSampleCount)) + newSample\n\treturn newTotal / float64((oldSampleCount + 1))\n}", "func (m *Model) FieldAvg(column string, as ...string) *Model {\n\tasStr := \"\"\n\tif len(as) > 0 && as[0] != \"\" {\n\t\tasStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))\n\t}\n\treturn m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.QuoteWord(column), asStr))\n}", "func Mean(field string) Aggregate {\n\treturn Aggregate{\n\t\tSQL: func(s *sql.Selector) string {\n\t\t\treturn sql.Avg(s.C(field))\n\t\t},\n\t}\n}", "func (ma *MovingAverage) CalcAvg() Churn {\n\n\tvar total Churn\n\tfor i := 0; i < ma.WindowSize; i++ {\n\t\ttotal.Online += ma.Window[i].Online\n\t\ttotal.Offline += ma.Window[i].Offline\n\t}\n\ttotal.Online /= float64(ma.WindowSize)\n\ttotal.Offline /= float64(ma.WindowSize)\n\n\treturn total\n}", "func Average(arg1 float64, arg2 float64) float64 { // take arguments from the main go program and returns average value in float64\n fmt.Println(\"Calculating Average:\")\n avg := (arg1 + arg2)/2\n return avg\n}", "func HandleAvg(w http.ResponseWriter, req *http.Request) {\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar numbers Numbers\n\n\terr := decoder.Decode(&numbers)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prevent division by zero\n\tvar average float64 = 0\n\n\tif len(numbers.Numbers) != 0 {\n\t\taverage = Average(numbers.Numbers)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tjsonRes, _ := json.Marshal(&Response{Result: average})\n\n\tw.Write(jsonRes)\n}", "func (ph *PHash) mean(img [][]float32) float32 {\n\tvar c int\n\tvar s float32\n\tfor i := range img {\n\t\tc += len(img[i])\n\t\tfor j := range img[i] {\n\t\t\ts += img[i][j]\n\t\t}\n\t}\n\treturn s / float32(c)\n}", "func FindAverage(data []int) float64 {\n\tsize := len(data)\n\tsum := 0\n\tfor _, v := range data {\n\t\tsum += v\n\t}\n\treturn float64(sum) / float64(size)\n}", "func NewAverageAggregator() AverageAggregator {\n\treturn AverageAggregator{}\n}", "func averageAroundInfected(data CountryData) (averageRate float64) {\n\tincreaseRatio := data.PreviousCases[0] / data.PreviousCases[1]\n\tpopulationRatio := data.PreviousCases[0] / data.Population\n\taverageRate = (increaseRatio - 1) / (1 - populationRatio)\n\treturn averageRate\n}", "func (p *partitionImpl) AverageKeyValue() (uint64, error) {\n\tif p.GetNumRows() == 0 {\n\t\treturn 0, nil\n\t}\n\tsum := uint64(0)\n\tfirstKey, err := p.GetKey(0)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor _, k := range p.keys {\n\t\tsum += k - firstKey\n\t}\n\treturn sum/uint64(len(p.keys)) + firstKey, nil\n}", "func average(data []int64) string {\n var total int64\n for _, n := range data {\n total += n\n }\n duration, _ := time.ParseDuration(fmt.Sprintf(\"%dns\", (total / int64(len(data)))))\n return fmt.Sprintf(\"%.3f\", duration.Seconds())\n}", "func (a *Array64) Mean(axis ...int) *Array64 {\n\tswitch {\n\tcase a.valAxis(&axis, \"Mean\"):\n\t\treturn a\n\t}\n\treturn a.C().Sum(axis...).DivC(a.count(axis...))\n}", "func average(sf ...float64) float64 {\n fmt.Println(sf, \"\\n\")\n fmt.Printf(\"%T\", sf)\n fmt.Println(\"\\n\")\n total := 0.0\n for _ , v := range sf {\n total += v\n }\n return total / float64(len(sf))\n}", "func (c *Counter) Mean() float64 {\n\tif c.count == 0 {\n\t\treturn 0\n\t}\n\treturn float64(c.sum) / float64(c.count)\n}", "func (ds *Dataset) ArithmeticMean() float64 {\n\tds.mustNotEmpty()\n\treturn ds.total / float64(len(ds.values))\n}", "func TestFindAverage(t *testing.T) {\n\tinput := []int{1, 3, 2, 6, -1, 4, 1, 8, 2}\n\tk := 5\n\texpectedOutput := []float64{2.2, 2.8, 2.4, 3.6, 2.8}\n\n\toutput := FindAverage(input, k)\n\tfmt.Println(\"Output : \", output)\n\n\tif !reflect.DeepEqual(output, expectedOutput) {\n\t\tt.Error(\"Output and expected output do not match : \", output, expectedOutput)\n\t}\n}", "func PostAvg(w http.ResponseWriter, r *http.Request) {\n\n\t// Very basic parameter checking.\n\tif r.Body == nil {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"missing parameter\")))\n\t\treturn\n\t}\n\n\tvar dataBody mytypes.DataBody\n\tjsonErr := json.NewDecoder(r.Body).Decode(&dataBody)\n\tif jsonErr != nil {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"no data given\")))\n\t\treturn\n\t}\n\n\t// FIXME: Error handling.\n\tdataRaw := dataBody.Data[:]\n\tdata := convert.StringtoFloat64(dataRaw)\n\n\tl := len(data)\n\tif l > 0 {\n\t\tavg := stat.Mean(data, nil)\n\t\tw.Write([]byte(fmt.Sprintf(\"%f\", avg)))\n\t} else {\n\t\trender.Render(w, r, srverrors.ErrInvalidRequest(errors.New(\"invalid data\")))\n\t\treturn\n\t}\n}", "func (s Student) getAverageGrade() float32 {\n\tsum := 0\n\tfor _, v := range s.grades {\n\t\tsum += v\n\t}\n\treturn float32(sum) / float32(len(s.grades))\n}", "func Mean(xs ...float64) float64 {\n\treturn Sum(xs...) / float64(len(xs))\n}", "func CalculateAverage(grades map[string]Module) float64 {\n\tvar teamprojekt Module\n\t// var thesis Module\n\t// var research []Module\n\tvar csFundamentals []Module\n\tvar ieFundamentals []Module\n\tvar mmmFundamentals []Module\n\tvar specs []Module\n\tvar grade float64\n\tvar credits float64\n\tfor _, v := range grades {\n\t\t// Teamproject\n\t\tif v.ExamID == 420500 {\n\t\t\tteamprojekt = v\n\t\t\t// Scientific Research Seminar\n\t\t} else if v.ExamID == 420000 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course CS\n\t\t} else if 400499 < v.ExamID && v.ExamID < 400600 {\n\t\t\tcsFundamentals = append(csFundamentals, v)\n\t\t\t// Specialization Course CS\n\t\t} else if 400599 < v.ExamID && v.ExamID < 400700 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course IE\n\t\t} else if 410499 < v.ExamID && v.ExamID < 410600 {\n\t\t\tieFundamentals = append(ieFundamentals, v)\n\t\t\t// Specialization Course IE\n\t\t} else if 410599 < v.ExamID && v.ExamID < 410700 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Fundamental Course MMM\n\t\t} else if 140000 < v.ExamID && v.ExamID < 140900 {\n\t\t\tmmmFundamentals = append(mmmFundamentals, v)\n\t\t\t// Specialization Course Area IS\n\t\t} else if 170000 < v.ExamID && v.ExamID < 170999 {\n\t\t\tspecs = append(specs, v)\n\t\t\t// Specialization Course Seminar\n\t\t} else if 430000 < v.ExamID && v.ExamID < 430999 {\n\t\t\tspecs = append(specs, v)\n\t\t}\n\t}\n\tgrade += teamprojekt.Grade * teamprojekt.Bonus\n\tcredits += teamprojekt.Bonus\n\tc, a := AverageGroup(csFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(ieFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(mmmFundamentals...)\n\tcredits += c\n\tgrade += a * c\n\tc, a = AverageGroup(specs...)\n\tcredits += c\n\tgrade += a * c\n\treturn truncate(grade/credits, 2)\n}", "func getAverage(numbers []int, ch chan float64) {\n\tvar sum = 0\n\tfor _, e := range numbers {\n\t\tsum += e\n\t}\n\tch <- float64(sum) / float64(len(numbers))\n}", "func (a *Average) Feed(value interface{}) {\n\tfloatVal, fSuccess := value.(float64)\n\trationalVal, rSuccess := value.(rational.Rational)\n\n\tintVal, intSuccess := value.(int)\n\tif intSuccess {\n\t\tfloatVal = float64(intVal)\n\t\tfSuccess = true\n\t}\n\n\tint64Val, int64Success := value.(int64)\n\tif int64Success {\n\t\tfloatVal = float64(int64Val)\n\t\tfSuccess = true\n\t}\n\n\tvar err error\n\n\ta.num++\n\n\tswitch {\n\tcase fSuccess:\n\t\tif a.num == 1 {\n\t\t\ta.avgR, err = rational.NewFromFloat(floatVal)\n\t\t\tif err != nil {\n\t\t\t\ta.num--\n\t\t\t\treturn\n\t\t\t}\n\t\t\ta.avg = floatVal\n\t\t} else {\n\t\t\tvar rVal rational.Rational\n\t\t\trVal, err = rational.NewFromFloat(floatVal)\n\t\t\tif err != nil {\n\t\t\t\ta.num--\n\t\t\t\treturn\n\t\t\t}\n\t\t\ta.avg = (a.avg*float64(a.num-1) + floatVal) / float64(a.num)\n\t\t\ta.avgR = a.avgR.MultiplyByNum(int64(a.num - 1)).Add(rVal).DivideByNum(int64(a.num))\n\t\t}\n\tcase rSuccess:\n\t\tif a.num == 1 {\n\t\t\ta.avg = rationalVal.Float64()\n\t\t\ta.avgR = rationalVal\n\t\t} else {\n\t\t\ta.avg = (a.avg*float64(a.num-1) + rationalVal.Float64()) / float64(a.num)\n\t\t\ta.avgR = a.avgR.MultiplyByNum(int64(a.num - 1)).Add(rationalVal).DivideByNum(int64(a.num))\n\t\t}\n\tdefault:\n\t\ta.num--\n\t\treturn\n\t}\n}", "func (b *MetricsBPFMap) AvgValue() float64 {\n\ttmp := b.Values.Next()\n\tvar sum float64\n\tvar n float64 = 0.0\n\tfor i := 0; i < b.Values.Len(); i++ {\n\t\tif tmp.Value != nil {\n\t\t\tsum = sum + tmp.Value.(float64)\n\t\t\tn = n + 1\n\t\t}\n\t\ttmp = tmp.Next()\n\t}\n\treturn sum / n\n}", "func incomeAverage(users []*sentinel.UserReq) string {\n\tvar total float64\n\tvar b bytes.Buffer\n\n\tfor _, u := range users {\n\t\ttotal += u.GetActivateInfo().YesWKB\n\t}\n\n\tb.WriteString(fmt.Sprintf(\"共%d台机器 总收益 %.3f链克 \\n\", len(users), total))\n\tb.WriteString(fmt.Sprintf(\"平均%.3f 链克/台 \\n\", total/float64(len(users))))\n\n\treturn b.String()\n}", "func (a AverageAggregator) Aggregate(values []float64) float64 {\n\tif len(values) == 0 {\n\t\treturn 0.0\n\t}\n\n\tresult := 0.0\n\tfor _, v := range values {\n\t\tresult += v\n\t}\n\treturn result / float64(len(values))\n}", "func TestMyInts_Average(t *testing.T) {\n\tassert.Equal(t, 0.0, myInts(nil).Average())\n\tassert.Equal(t, 4.333333333333333, myInts{1, 5, 7}.Average())\n}" ]
[ "0.7075979", "0.7029537", "0.69840676", "0.6962224", "0.6883427", "0.68685544", "0.6860039", "0.6850291", "0.6805076", "0.6804174", "0.67915916", "0.67889154", "0.67111546", "0.67024124", "0.66777295", "0.6672587", "0.66583467", "0.6640339", "0.6636939", "0.6632304", "0.66219366", "0.6581973", "0.6571818", "0.65623844", "0.6553496", "0.6516284", "0.6516284", "0.65010357", "0.6498045", "0.6470916", "0.64673114", "0.6446161", "0.6435853", "0.6433521", "0.64220554", "0.64022964", "0.6365458", "0.6355914", "0.63374645", "0.63368666", "0.6335133", "0.6307536", "0.62783444", "0.6258619", "0.623289", "0.6214785", "0.62142694", "0.61950916", "0.6190818", "0.61233723", "0.611277", "0.6054777", "0.60382694", "0.60254514", "0.6022693", "0.60218924", "0.6000147", "0.5975163", "0.59358096", "0.59235495", "0.59206843", "0.5919308", "0.59152764", "0.59149766", "0.5914511", "0.5899941", "0.5896151", "0.5887692", "0.5872851", "0.58533037", "0.58312094", "0.5823877", "0.5823877", "0.5807236", "0.5805212", "0.5803525", "0.5800697", "0.58002955", "0.57951355", "0.5770904", "0.5770464", "0.57650375", "0.5722704", "0.5709173", "0.56906825", "0.5673732", "0.5672501", "0.56689614", "0.56579834", "0.56566674", "0.56380785", "0.56139165", "0.56081706", "0.55957323", "0.5587485", "0.5583805", "0.55723816", "0.5570731", "0.55653465", "0.5557724" ]
0.67577
12
StdDev returns the standard deviation.
func (c *Counter) StdDev() float64 { fC := float64(c.Count) sigma := (c.sumOfSquares - c.Sum*c.Sum/fC) / fC // should never happen but it does if sigma < 0 { log.Warnf("Unexpected negative sigma for %+v: %g", c, sigma) return 0 } return math.Sqrt(sigma) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunningStats) Stddev() float64 {\n\treturn math.Sqrt(r.Var())\n}", "func (s *NumSeries) StdDev() float64 {\n\treturn math.Sqrt(s.Variance())\n}", "func (s Series) StdDev() (float64, error) {\n\tvals, err := s.Float(false)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstdDev := stat.StdDev(vals, nil)\n\treturn stdDev, nil\n}", "func (n *Normal) StdDev() float64 {\n\treturn n.stddev\n}", "func (h *pingHistory) stdDev() float64 {\n\treturn math.Sqrt(h.variance())\n}", "func (norm Normal) StdDev() float64 {\n\treturn norm.Sigma\n}", "func (s *UniformSample) StdDev() float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SampleStdDev(s.values)\n}", "func (t *StandardTimer) StdDev() float64 {\n\treturn t.histogram.StdDev()\n}", "func (f F) StdDev() float64 {\n\tif f.D2 <= 4 {\n\t\treturn math.NaN()\n\t}\n\treturn math.Sqrt(f.Variance())\n}", "func (p Pareto) StdDev() float64 {\n\treturn math.Sqrt(p.Variance())\n}", "func (b Binomial) StdDev() float64 {\n\treturn math.Sqrt(b.Variance())\n}", "func (g GumbelRight) StdDev() float64 {\n\treturn (math.Pi / math.Sqrt(6)) * g.Beta\n}", "func (a AlphaStable) StdDev() float64 {\n\treturn math.Sqrt(a.Variance())\n}", "func (c ChiSquared) StdDev() float64 {\n\treturn math.Sqrt(c.Variance())\n}", "func (ds *Dataset) StandardDeviation() float64 {\n\treturn math.Sqrt(ds.Variance())\n}", "func (t *TimerSnapshot) StdDev() float64 { return t.histogram.StdDev() }", "func StdDev(col Columnar) ColumnElem {\n\treturn Function(STDDEV, col)\n}", "func (d DelphiEstimate) GetStandardDeviation() float64 {\n\treturn (d.WorstCase - d.BestCase) / 6\n}", "func (e Exponential) StdDev() float64 {\n\treturn 1 / e.Rate\n}", "func StdDevS(input Float64Data) (sdev float64, err error) {\n\treturn StandardDeviationSample(input)\n}", "func StDev(xs ...float64) float64 {\n\treturn gomath.Sqrt(Var(xs...))\n}", "func (c *Counter) Stdev() float64 {\n\treturn stdev(c.count, float64(c.sumSq), float64(c.sum))\n}", "func (s *TrialComponentMetricSummary) SetStdDev(v float64) *TrialComponentMetricSummary {\n\ts.StdDev = &v\n\treturn s\n}", "func stDev(a []float64) (s float64) {\n\tm := mean(a)\n\tfor _, v := range a {\n\t\ts += (v - m) * (v - m)\n\t}\n\treturn math.Sqrt(s / float64(len(a)))\n}", "func Stdev(input []float64) float64 {\n\tvariance := Variance(input)\n\treturn math.Pow(variance, 0.5)\n}", "func StandardDeviation(values []float64) float64 {\n\tarithmeticMean := ArithmeticMean(values)\n\tvar squaredDifferences []float64\n\tfor _, v := range values {\n\t\tdifference := v - arithmeticMean\n\t\tsquaredDifferences = append(squaredDifferences, difference*difference)\n\t}\n\treturn math.Sqrt((1 / float64(len(values)-1)) * Sum(squaredDifferences))\n}", "func StandardDeviation(nums []int) (dev float64) {\n\tif len(nums) == 0 {\n\t\treturn 0.0\n\t}\n\n\tm := Mean(nums)\n\tfor _, n := range nums {\n\t\tdev += (float64(n) - m) * (float64(n) - m)\n\t}\n\tdev = math.Pow(dev/float64(len(nums)), 0.5)\n\treturn dev\n}", "func (s *NumSeries) SampleStdDev() float64 {\n\treturn math.Sqrt(s.SampleVariance())\n}", "func (s FloatList) StandardDeviation() float64 {\n\treturn math.Sqrt(s.Variance())\n}", "func (s *Stat) GetStdDevS() float64 {\n\treturn math.Sqrt(s.GetVarS())\n}", "func StdDev(by []string, input []*oproto.ValueStream) []*oproto.ValueStream {\n\toutput := []*oproto.ValueStream{{Variable: input[0].Variable}}\n\tiPos := make([]int, len(input))\n\tfor {\n\t\tvalues := []float64{}\n\t\ttimestamps := []uint64{}\n\t\tfor i := 0; i < len(input); i++ {\n\t\t\tif iPos[i] >= len(input[i].Value) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif input[i] != nil {\n\t\t\t\tvalues = append(values, input[i].Value[iPos[i]].GetDouble())\n\t\t\t\ttimestamps = append(timestamps, input[i].Value[iPos[i]].Timestamp)\n\t\t\t}\n\t\t\tiPos[i]++\n\t\t}\n\t\tif len(values) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tvar total float64\n\t\tfor _, i := range values {\n\t\t\ttotal += i\n\t\t}\n\t\tvar variances float64\n\t\tfor _, i := range values {\n\t\t\tvariances += math.Pow(((total / float64(len(values))) - i), 2)\n\t\t}\n\n\t\tvar tsTotal uint64\n\t\tfor _, i := range timestamps {\n\t\t\ttsTotal += i\n\t\t}\n\t\toutput[0].Value = append(output[0].Value, value.NewDouble(tsTotal/uint64(len(timestamps)),\n\t\t\tmath.Sqrt(variances/float64(len(values)))))\n\t}\n\treturn output\n}", "func (NilTimer) StdDev() float64 { return 0.0 }", "func (h *PCPHistogram) StandardDeviation() float64 {\n\th.mutex.RLock()\n\tdefer h.mutex.RUnlock()\n\treturn h.vals[\"standard_deviation\"].val.(float64)\n}", "func CalculateStdev(data []int) float64 {\n\tmean := CalculateMean(data)\n\tvar squareSum float64\n\tfor _, value := range data {\n\t\tsquareSum += math.Pow((float64(value) - mean), 2)\n\t}\n\treturn math.Sqrt(squareSum / (float64(len(data) - 1)))\n}", "func StandardDeviation(values []float64) float64 {\n\tvar sum, sumSq, length float64 = 0.0, 0.0, 0.0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t\tsumSq += d * d\n\t\t\tlength++\n\t\t}\n\t}\n\treturn math.Sqrt((math.Abs(sumSq-sum*sum) /\n\t\t((length) * (length - 1))))\n}", "func TestGet_StandardDeviation(t *testing.T) {\n\tdata := []float64{1345, 1301, 1368, 1322, 1310, 1370, 1318, 1350, 1303, 1299}\n\tmean, stdev_s := normality.Get_AverageAndStandardDeviation(&data)\n\t// Expected values (Correct answer)\n\t// mean = 1328.6\n\t// stdev_s = 27.46391571984349\n\tfmt.Println(\" Mean : \", mean)\n\tfmt.Println(\"Standard Deviation : \", stdev_s)\n}", "func (s *Stat) GetStdDevP() float64 {\n\treturn math.Sqrt(s.GetVarP())\n}", "func stdev(img image.Image) float64 {\n\tw, h := dim(img)\n\n\tn := float64((w * h) - 1)\n\tsum := 0.0\n\tavg := mean(img)\n\n\tfor x := 0; x < w; x++ {\n\t\tfor y := 0; y < h; y++ {\n\t\t\tpix := getPixVal(img.At(x, y))\n\t\t\tsum += math.Pow((pix - avg), 2.0)\n\t\t}\n\t}\n\treturn math.Sqrt(sum / n)\n}", "func (e *exemplarSampler) standardDeviation() float64 {\n\tif e.count < 2 {\n\t\treturn 0\n\t}\n\treturn math.Sqrt(e.m2 / float64(e.count-1))\n}", "func ReduceStddev(values []interface{}) interface{} {\n\tvar data []float64\n\t// Collect all the data points\n\tfor _, value := range values {\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdata = append(data, value.([]float64)...)\n\t}\n\n\t// If no data or we only have one point, it's nil or undefined\n\tif len(data) < 2 {\n\t\treturn nil\n\t}\n\n\t// Get the mean\n\tvar mean float64\n\tvar count int\n\tfor _, v := range data {\n\t\tcount++\n\t\tmean += (v - mean) / float64(count)\n\t}\n\t// Get the variance\n\tvar variance float64\n\tfor _, v := range data {\n\t\tdif := v - mean\n\t\tsq := math.Pow(dif, 2)\n\t\tvariance += sq\n\t}\n\tvariance = variance / float64(count-1)\n\tstddev := math.Sqrt(variance)\n\n\treturn stddev\n}", "func StdDevP(input Float64Data) (sdev float64, err error) {\n\treturn StandardDeviationPopulation(input)\n}", "func (m *Measurement) StdDevLatency() float64 {\n\tavg := m.AvgLatency()\n\tdev := 0.\n\tfor _, d := range m.data {\n\t\tdiff := d.Latency - avg\n\t\tdev += diff * diff\n\t}\n\tdev /= float64(m.successful)\n\tdev = math.Sqrt(dev)\n\treturn dev\n}", "func (s Set) GetStd() float64 {\r\n\treturn math.Sqrt(s.GetVariance())\r\n}", "func (ds *Dataset) SampleStandardDeviation() float64 {\n\treturn math.Sqrt(ds.SampleVariance())\n}", "func (fn *formulaFuncs) STDEV(argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"STDEV requires at least 1 argument\")\n\t}\n\treturn fn.stdev(false, argsList)\n}", "func (indis Individuals) FitStd() float64 {\n\treturn math.Sqrt(varianceFloat64s(indis.getFitnesses()))\n}", "func (p *P1D) XStdDev() float64 {\n\treturn p.bng.dist.xStdDev()\n}", "func dev(dps Series, args ...float64) (d float64) {\n\tif len(dps) == 1 {\n\t\treturn 0\n\t}\n\ta := avg(dps)\n\tfor _, v := range dps {\n\t\td += math.Pow(float64(v)-a, 2)\n\t}\n\td /= float64(len(dps) - 1)\n\treturn math.Sqrt(d)\n}", "func (fn *formulaFuncs) stdev(stdeva bool, argsList *list.List) formulaArg {\n\tcount, result := -1.0, -1.0\n\tvar mean formulaArg\n\tif stdeva {\n\t\tmean = fn.AVERAGEA(argsList)\n\t} else {\n\t\tmean = fn.AVERAGE(argsList)\n\t}\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\ttoken := arg.Value.(formulaArg)\n\t\tswitch token.Type {\n\t\tcase ArgString, ArgNumber:\n\t\t\tif !stdeva && (token.Value() == \"TRUE\" || token.Value() == \"FALSE\") {\n\t\t\t\tcontinue\n\t\t\t} else if stdeva && (token.Value() == \"TRUE\" || token.Value() == \"FALSE\") {\n\t\t\t\tnum := token.ToBool()\n\t\t\t\tif num.Type == ArgNumber {\n\t\t\t\t\tresult, count = calcStdevPow(result, count, num, mean)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnum := token.ToNumber()\n\t\t\t\tif num.Type == ArgNumber {\n\t\t\t\t\tresult, count = calcStdevPow(result, count, num, mean)\n\t\t\t\t}\n\t\t\t}\n\t\tcase ArgList, ArgMatrix:\n\t\t\tresult, count = calcStdev(stdeva, result, count, mean, token)\n\t\t}\n\t}\n\tif count > 0 && result >= 0 {\n\t\treturn newNumberFormulaArg(math.Sqrt(result / count))\n\t}\n\treturn newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)\n}", "func (b *BinP1D) XStdDev() float64 {\n\treturn b.dist.xStdDev()\n}", "func StandardDeviationPopulation(data []f64, mu f64) f64 {\n\treturn math.Sqrt(VariancePopulation(data, mu))\n}", "func (b *Box) MeanStd() {\n\tb.MeanL, b.StdL = stat.MeanStdDev(b.values, nil)\n}", "func measureStdDev(endpoints []string, hashesPerEndpoint int) float64 {\n\tch := newConsistentHashInternal(endpoints, hashesPerEndpoint).(*consistentHash)\n\tringOwnership := map[int]uint64{}\n\tprevPartitionEndHash := uint64(0)\n\tfor i := 0; i < len(ch.hashRing); i++ {\n\t\tendpointIndex := ch.hashRing[i].index\n\t\tpartitionEndHash := ch.hashRing[i].hash\n\t\tringOwnership[endpointIndex] += partitionEndHash - prevPartitionEndHash\n\t\tprevPartitionEndHash = partitionEndHash\n\t}\n\tringOwnership[ch.hashRing[0].index] += math.MaxUint64 - prevPartitionEndHash\n\treturn stdDeviation(ringOwnership)\n}", "func funcHistogramStdDev(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tmean := sample.H.Sum / sample.H.Count\n\t\tvar variance, cVariance float64\n\t\tit := sample.H.AllBucketIterator()\n\t\tfor it.Next() {\n\t\t\tbucket := it.At()\n\t\t\tvar val float64\n\t\t\tif bucket.Lower <= 0 && 0 <= bucket.Upper {\n\t\t\t\tval = 0\n\t\t\t} else {\n\t\t\t\tval = math.Sqrt(bucket.Upper * bucket.Lower)\n\t\t\t}\n\t\t\tdelta := val - mean\n\t\t\tvariance, cVariance = kahanSumInc(bucket.Count*delta*delta, variance, cVariance)\n\t\t}\n\t\tvariance += cVariance\n\t\tvariance /= sample.H.Count\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: math.Sqrt(variance),\n\t\t})\n\t}\n\treturn enh.Out\n}", "func permStDev(a, b []float64) float64 {\n\tn := float64(len(a))\n\treturn n / math.Sqrt(n-1) * stDev(a) * stDev(b)\n}", "func MapStddev(itr Iterator) interface{} {\n\tvar values []float64\n\n\tfor k, v := itr.Next(); k != -1; k, v = itr.Next() {\n\t\tswitch n := v.(type) {\n\t\tcase float64:\n\t\t\tvalues = append(values, n)\n\t\tcase int64:\n\t\t\tvalues = append(values, float64(n))\n\t\t}\n\t}\n\n\treturn values\n}", "func meanSd(data []float64) (mean, sd float64) {\n\tn := 0.0\n\tmean = 0.0\n\tm2 := 0.0\n\tfor _, x := range data {\n\t\tn++\n\t\tdelta := x - mean\n\t\tmean += delta / n\n\t\tif n > 1 {\n\t\t\tm2 += delta * (x - mean)\n\t\t}\n\t}\n\tsd = sqrt(m2 / (n - 1))\n\treturn\n}", "func (ds *Dataset) MeanDeviation() float64 {\n\tmean := ds.ArithmeticMean()\n\tvar diffs float64\n\tfor _, value := range ds.values {\n\t\tdiffs += math.Abs(mean - value)\n\t}\n\treturn diffs / float64(len(ds.values))\n}", "func Deviation(generator *rand.Rand, factor float64) Transformation {\n\trandom := fallbackNewRandom(generator)\n\n\treturn func(duration time.Duration) time.Duration {\n\t\tmin := int64(math.Floor(float64(duration) * (1 - factor)))\n\t\tmax := int64(math.Ceil(float64(duration) * (1 + factor)))\n\n\t\treturn time.Duration(random.Int63n(max-min) + min)\n\t}\n}", "func funcStddevOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tif len(vals[0].(Matrix)[0].Floats) == 0 {\n\t\t// TODO(beorn7): The passed values only contain\n\t\t// histograms. stddev_over_time ignores histograms for now. If\n\t\t// there are only histograms, we have to return without adding\n\t\t// anything to enh.Out.\n\t\treturn enh.Out\n\t}\n\treturn aggrOverTime(vals, enh, func(s Series) float64 {\n\t\tvar count float64\n\t\tvar mean, cMean float64\n\t\tvar aux, cAux float64\n\t\tfor _, f := range s.Floats {\n\t\t\tcount++\n\t\t\tdelta := f.F - (mean + cMean)\n\t\t\tmean, cMean = kahanSumInc(delta/count, mean, cMean)\n\t\t\taux, cAux = kahanSumInc(delta*(f.F-(mean+cMean)), aux, cAux)\n\t\t}\n\t\treturn math.Sqrt((aux + cAux) / count)\n\t})\n}", "func calcStdev(stdeva bool, result, count float64, mean, token formulaArg) (float64, float64) {\n\tfor _, row := range token.ToList() {\n\t\tif row.Type == ArgNumber || row.Type == ArgString {\n\t\t\tif !stdeva && (row.Value() == \"TRUE\" || row.Value() == \"FALSE\") {\n\t\t\t\tcontinue\n\t\t\t} else if stdeva && (row.Value() == \"TRUE\" || row.Value() == \"FALSE\") {\n\t\t\t\tnum := row.ToBool()\n\t\t\t\tif num.Type == ArgNumber {\n\t\t\t\t\tresult, count = calcStdevPow(result, count, num, mean)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnum := row.ToNumber()\n\t\t\t\tif num.Type == ArgNumber {\n\t\t\t\t\tresult, count = calcStdevPow(result, count, num, mean)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result, count\n}", "func (fn *formulaFuncs) STDEVP(argsList *list.List) formulaArg {\n\treturn fn.stdevp(\"STDEVP\", argsList)\n}", "func (fn *formulaFuncs) STDEVA(argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"STDEVA requires at least 1 argument\")\n\t}\n\treturn fn.stdev(true, argsList)\n}", "func (fn *formulaFuncs) stdevp(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires at least 1 argument\", name))\n\t}\n\tfnName := \"VARP\"\n\tif name == \"STDEVPA\" {\n\t\tfnName = \"VARPA\"\n\t}\n\tvarp := fn.vars(fnName, argsList)\n\tif varp.Type != ArgNumber {\n\t\treturn varp\n\t}\n\treturn newNumberFormulaArg(math.Sqrt(varp.Number))\n}", "func (_TellorMesosphere *TellorMesosphereSession) MaximumDeviation() (*big.Int, error) {\n\treturn _TellorMesosphere.Contract.MaximumDeviation(&_TellorMesosphere.CallOpts)\n}", "func (p *P1D) XStdErr() float64 {\n\treturn p.bng.dist.xStdErr()\n}", "func (s Series) Mean() (float64, error) {\n\tvals, err := s.Float(false)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstdDev := stat.Mean(vals, nil)\n\treturn stdDev, nil\n}", "func (b BrokerMap) StorageStdDev() float64 {\n\tvar m float64\n\tvar t float64\n\tvar s float64\n\tvar l float64\n\n\tfor id := range b {\n\t\tif id == StubBrokerID {\n\t\t\tcontinue\n\t\t}\n\t\tl++\n\t\tt += b[id].StorageFree\n\t}\n\n\tm = t / l\n\n\tfor id := range b {\n\t\tif id == StubBrokerID {\n\t\t\tcontinue\n\t\t}\n\t\ts += math.Pow(m-b[id].StorageFree, 2)\n\t}\n\n\tmsq := s / l\n\n\treturn math.Sqrt(msq)\n}", "func Deviation(data []float64, holeIndices []int, dim int, triangles []int) float64 {\n\thasHoles := holeIndices != nil && len(holeIndices) > 0\n\tvar outerLen int\n\tif hasHoles {\n\t\touterLen = holeIndices[0] * dim\n\t} else {\n\t\touterLen = len(data)\n\t}\n\n\tpolygonArea := math.Abs(signedArea(data, 0, outerLen, dim))\n\tvar start, end int\n\tif hasHoles {\n\t\tfor i, l := 0, len(holeIndices); i < l; i++ {\n\t\t\tstart = holeIndices[i] * dim\n\t\t\tif i < l-1 {\n\t\t\t\tend = holeIndices[i+1] * dim\n\t\t\t} else {\n\t\t\t\tend = len(data)\n\t\t\t}\n\t\t\tpolygonArea -= math.Abs(signedArea(data, start, end, dim))\n\t\t}\n\t}\n\n\tvar trianglesArea float64\n\tfor i := 0; i < len(triangles); i += 3 {\n\t\ta := triangles[i] * dim\n\t\tb := triangles[i+1] * dim\n\t\tc := triangles[i+2] * dim\n\t\ttrianglesArea += math.Abs(\n\t\t\t(data[a]-data[c])*(data[b+1]-data[a+1]) -\n\t\t\t\t(data[a]-data[b])*(data[c+1]-data[a+1]))\n\t}\n\n\tif polygonArea == 0.0 && trianglesArea == 0.0 {\n\t\treturn 0.0\n\t}\n\tif polygonArea == 0.0 {\n\t\treturn math.Inf(1)\n\t}\n\treturn math.Abs((trianglesArea - polygonArea) / polygonArea)\n}", "func (b *BinP1D) XStdErr() float64 {\n\treturn b.dist.xStdErr()\n}", "func (_TellorMesosphere *TellorMesosphereCallerSession) MaximumDeviation() (*big.Int, error) {\n\treturn _TellorMesosphere.Contract.MaximumDeviation(&_TellorMesosphere.CallOpts)\n}", "func SD(list []interface{}) (float64, error) {\n\ta, err := ds.NewArrayFrom(list)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn a.SD(), nil\n}", "func (h *pingHistory) variance() float64 {\n\tvar sqDevSum float64\n\n\tmean := h.mean()\n\n\tfor _, t := range *h {\n\t\tsqDevSum = sqDevSum + math.Pow((float64(t)-mean), 2)\n\t}\n\treturn sqDevSum / float64(len(*h))\n}", "func (r *results) GetStdErr() string {\n\treturn r.stdErr\n}", "func LogNormalStd(μ, σ float64) float64 {\n\treturn sqrt(LogNormalVar(μ, σ))\n}", "func (fn *formulaFuncs) STDEVPA(argsList *list.List) formulaArg {\n\treturn fn.stdevp(\"STDEVPA\", argsList)\n}", "func SQRTSD(mx, x operand.Op) { ctx.SQRTSD(mx, x) }", "func (fn *formulaFuncs) STDEVdotS(argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"STDEV.S requires at least 1 argument\")\n\t}\n\treturn fn.stdev(false, argsList)\n}", "func (n *Normal) Median() float64 {\n\treturn n.mean\n}", "func (statistics *Statistics) CalcStdev(busdayVolumes, weekendVolumes map[int][]int) {\n\tstatistics.Stdev = DayTypeTimeseries{\n\t\tBusinessDays: CalculateStdevPerHour(busdayVolumes),\n\t\tWeekendDays: CalculateStdevPerHour(weekendVolumes),\n\t}\n}", "func PDF(x, avg, stddev float64) float64 {\n\treturn math.Exp(-math.Pow(((x-avg)/stddev), 2)/2) / (stddev * math.Sqrt(2*math.Pi))\n}", "func SDFloat(slice []float64) float64 {\n\tif len(slice) == 1 {\n\t\treturn 0\n\t}\n\n\tmean := MeanFloat(slice)\n\tsum := float64(0)\n\tfor _, value := range slice {\n\t\tsum += math.Pow(value-mean, float64(2))\n\t}\n\n\treturn math.Sqrt(sum / float64(len(slice)-1))\n}", "func CalculateSD(appNuminEacZone map[string]int, appNum int, zoneNum int, mean float64) float64 {\n\tvar sum, x float64\n\tfor _, v := range appNuminEacZone {\n\t\tx = float64(v) - mean\n\t\tsum = sum + math.Pow(x, 2)\n\t}\n\tfmt.Println(\"sum=\", sum)\n\tsd := float64(math.Sqrt(sum / float64(zoneNum)))\n\treturn sd\n}", "func NewStdNorm() (x *Norm){\n x = NewNorm(0.,1.)\n return\n}", "func CDF(x, avg, stddev float64) float64 {\n\treturn (1 + math.Erf(((x-avg)/stddev)/math.Sqrt2)) / 2\n}", "func SDInt(slice []int) float64 {\n\tif len(slice) == 1 {\n\t\treturn 0\n\t}\n\n\tmean := MeanInt(slice)\n\tsum := float64(0)\n\tfor _, value := range slice {\n\t\tsum += math.Pow(float64(value)-mean, float64(2))\n\t}\n\n\treturn math.Sqrt(sum / float64(len(slice)-1))\n}", "func Variance(data []float64, mean float64) float64 {\r\n\treturn Reduce(data, mean, 2) / (float64(len(data)) - 1)\r\n}", "func (t *StandardTimer) Variance() float64 {\n\treturn t.histogram.Variance()\n}", "func MakeMeanStdAV(d []float64, m int) []float64 {\n\tav := make([]float64, len(d)-m+1)\n\t_, std, _ := movmeanstd(d, m)\n\tmu := stat.Mean(std, nil)\n\tfor i := 0; i < len(d)-m+1; i++ {\n\t\tif std[i] < mu {\n\t\t\tav[i] = 1\n\t\t}\n\t}\n\treturn av\n}", "func (t *Test) StdErr() *bytes.Buffer {\n\treturn t.stdErr\n}", "func sd_a(list []int) [2]float64 {\r\n\tvar average float64 = 0.0\r\n\tvar sd float64 = 0.0\r\n\tvar result [2]float64\r\n\r\n\tfor _, item := range list {\r\n\t\taverage += float64(item)\r\n\t}\r\n\r\n\taverage = average / float64(len(list))\r\n\r\n\tfor _, item := range list {\r\n\t\tsd += math.Pow((float64(item) - average), 2.0)\r\n\t}\r\n\tsd = math.Sqrt(sd / float64(len(list)))\r\n\r\n\tresult[0] = average\r\n\tresult[1] = sd\r\n\r\n\treturn result\r\n}", "func (e HybridKFEstimate) ObservationDev() *mat64.Vector {\n\treturn e.Δobs\n}", "func Normal(mean, sd float64) float64 {\n\treturn rand.NormFloat64()*sd + mean\n}", "func (fn *formulaFuncs) STDEVdotP(argsList *list.List) formulaArg {\n\treturn fn.stdevp(\"STDEV.P\", argsList)\n}", "func (o OutlierDetectionOutput) SuccessRateStdevFactor() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v OutlierDetection) *int { return v.SuccessRateStdevFactor }).(pulumi.IntPtrOutput)\n}", "func (fn *formulaFuncs) AVEDEV(argsList *list.List) formulaArg {\n\tif argsList.Len() == 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"AVEDEV requires at least 1 argument\")\n\t}\n\taverage := fn.AVERAGE(argsList)\n\tif average.Type != ArgNumber {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t}\n\tresult, count := 0.0, 0.0\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\tnum := arg.Value.(formulaArg).ToNumber()\n\t\tif num.Type != ArgNumber {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t\t}\n\t\tresult += math.Abs(num.Number - average.Number)\n\t\tcount++\n\t}\n\treturn newNumberFormulaArg(result / count)\n}", "func (o OutlierDetectionResponseOutput) SuccessRateStdevFactor() pulumi.IntOutput {\n\treturn o.ApplyT(func(v OutlierDetectionResponse) int { return v.SuccessRateStdevFactor }).(pulumi.IntOutput)\n}", "func (n *Normal) Variance() float64 {\n\treturn n.variance\n}", "func calcStdevPow(result, count float64, n, m formulaArg) (float64, float64) {\n\tif result == -1 {\n\t\tresult = math.Pow(n.Number-m.Number, 2)\n\t} else {\n\t\tresult += math.Pow(n.Number-m.Number, 2)\n\t}\n\tcount++\n\treturn result, count\n}", "func (cmd *ExecCommandImpl) Stderr() *OutputStream {\n\treturn cmd.stderr\n}" ]
[ "0.8537519", "0.84938926", "0.83655524", "0.82760817", "0.82111365", "0.8201574", "0.8150904", "0.80937123", "0.80443895", "0.80137736", "0.7954435", "0.79488546", "0.78447735", "0.77971447", "0.7786753", "0.7727118", "0.7710873", "0.7691103", "0.7656157", "0.75673616", "0.7562807", "0.75019675", "0.74590814", "0.74282366", "0.74277866", "0.74159557", "0.7375382", "0.7351755", "0.72648585", "0.72537285", "0.7251082", "0.72143644", "0.71915203", "0.7154569", "0.7143798", "0.713303", "0.70820016", "0.701364", "0.7007925", "0.6926693", "0.6822136", "0.6809756", "0.680748", "0.664905", "0.6580608", "0.65249854", "0.6515483", "0.6480763", "0.6445237", "0.64084774", "0.63202804", "0.62773496", "0.6208335", "0.60610837", "0.60194016", "0.5954292", "0.59466416", "0.5941444", "0.590284", "0.5872917", "0.568721", "0.5589182", "0.5581186", "0.5559038", "0.55273396", "0.55009943", "0.5484593", "0.5478416", "0.54352355", "0.5420885", "0.5398626", "0.53672725", "0.535472", "0.5327592", "0.53141564", "0.5298479", "0.52980506", "0.5272102", "0.5271478", "0.5254853", "0.52402866", "0.5232398", "0.51564443", "0.51373035", "0.509556", "0.50866073", "0.5064385", "0.5056577", "0.5047011", "0.5029115", "0.50227726", "0.5015659", "0.501246", "0.49392992", "0.49349192", "0.49205947", "0.4899308", "0.4891327", "0.4882988", "0.48686424" ]
0.7836182
13
Log outputs the stats to the logger.
func (c *Counter) Log(msg string) { log.Infof("%s : count %d avg %.8g +/- %.4g min %g max %g sum %.9g", msg, c.Count, c.Avg(), c.StdDev(), c.Min, c.Max, c.Sum) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) LogStats(out io.Writer) {\n\tif !c.LoggingStats {\n\t\treturn\n\t}\n\n\tfmt.Fprintf(out, \"concurrent=%d time=%d version=%s\\n\", c.ConcurrentTransfers, time.Now().Unix(), UserAgent)\n\n\tfor key, responses := range c.transferBuckets {\n\t\tfor _, response := range responses {\n\t\t\tstats := c.transfers[response]\n\t\t\tfmt.Fprintf(out, \"key=%s reqheader=%d reqbody=%d resheader=%d resbody=%d restime=%d status=%d url=%s\\n\",\n\t\t\t\tkey,\n\t\t\t\tstats.requestStats.HeaderSize,\n\t\t\t\tstats.requestStats.BodySize,\n\t\t\t\tstats.responseStats.HeaderSize,\n\t\t\t\tstats.responseStats.BodySize,\n\t\t\t\tstats.responseStats.Stop.Sub(stats.responseStats.Start).Nanoseconds(),\n\t\t\t\tresponse.StatusCode,\n\t\t\t\tresponse.Request.URL)\n\t\t}\n\t}\n}", "func (g *GCMMessageHandler) LogStats() {\n\tl := g.Logger.WithFields(log.Fields{\n\t\t\"method\": \"logStats\",\n\t\t\"interval(ns)\": g.LogStatsInterval,\n\t})\n\n\tticker := time.NewTicker(g.LogStatsInterval)\n\tfor range ticker.C {\n\t\tapnsResMutex.Lock()\n\t\tif g.sentMessages > 0 || g.responsesReceived > 0 || g.ignoredMessages > 0 || g.successesReceived > 0 || g.failuresReceived > 0 {\n\t\t\tl.WithFields(log.Fields{\n\t\t\t\t\"sentMessages\": g.sentMessages,\n\t\t\t\t\"responsesReceived\": g.responsesReceived,\n\t\t\t\t\"ignoredMessages\": g.ignoredMessages,\n\t\t\t\t\"successesReceived\": g.successesReceived,\n\t\t\t\t\"failuresReceived\": g.failuresReceived,\n\t\t\t}).Info(\"flushing stats\")\n\t\t\tg.sentMessages = 0\n\t\t\tg.responsesReceived = 0\n\t\t\tg.successesReceived = 0\n\t\t\tg.ignoredMessages = 0\n\t\t\tg.failuresReceived = 0\n\t\t}\n\t\tapnsResMutex.Unlock()\n\t}\n}", "func logStats() {\n\tif requestsReceived > 0 {\n\t\tavgRequestMs := strconv.FormatFloat(totalRequestTime/float64(requestsReceived), 'f', 3, 64)\n\t\tlogger.Printf(\"%d requests, %d bytes received (avg. %sms)\\n\", requestsReceived, bytesReceived, avgRequestMs)\n\t}\n\trequestsReceived = 0\n\tbytesReceived = 0\n\ttotalRequestTime = 0.0\n}", "func (backends Backends) log_stats() {\n\tfor _, backend := range backends {\n\t\tdowntime := backend.downtime\n\t\tif backend.failed {\n\t\t\tdowntime += time.Now().Sub(backend.failedTime)\n\t\t}\n\t\tlog.Printf(\"STATS: <%s> failed=%v (downtime=%v) requests=%d bytes=%d errors=%d last=%s\",\n\t\t\tbackend.address, backend.failed, downtime, backend.requests,\n\t\t\tbackend.transferred, backend.errors, backend.timestamp)\n\t}\n}", "func (log *logger) output(pool *bufferPool, level logLevel, format string, a ...interface{}) {\n\tif level < log.minLevel {\n\t\treturn\n\t}\n\tvar msg string\n\tif len(a) == 0 {\n\t\tmsg = format\n\t} else {\n\t\tmsg = fmt.Sprintf(format, a...)\n\t}\n\tvar buf = log.formatter.Format(pool, level, msg)\n\tfor _, dev := range log.devices {\n\t\tdev.Write(buf.Bytes())\n\t}\n\tpool.put(buf)\n}", "func (m *Metrics) Log(l Logger, all bool) {\n\tif !m.config.Enable {\n\t\treturn\n\t}\n\n\tw := writer{l, all}\n\n\tenc := expfmt.NewEncoder(w, expfmt.FmtText)\n\n\tmfs, err := prometheus.DefaultGatherer.Gather()\n\tif err != nil {\n\t\tfmt.Println(\"error gathering metrics:\", err)\n\t\treturn\n\t}\n\n\tfor _, mf := range mfs {\n\t\tif err := enc.Encode(mf); err != nil {\n\t\t\tfmt.Println(\"error encoding and sending metric family:\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (e *executor) output(opts opts, output []string) {\n\tif opts.verbose {\n\t\tfor _, line := range output {\n\t\t\te.logLine(line)\n\t\t}\n\t}\n}", "func (s *DBStore) LogStats() {\n\tvar requestCount, statisticCount int\n\ts.db.Table(\"requests\").Count(&requestCount)\n\ts.db.Table(\"statistics\").Count(&statisticCount)\n\tdbLogger.Infof(\"Cached requests: %d. Statistic entries count: %d\", requestCount, statisticCount)\n}", "func (l *loggingT) output(s severity.Severity, logger *logWriter, buf *buffer.Buffer, depth int, file string, line int, alsoToStderr bool) {\n\tvar isLocked = true\n\tl.mu.Lock()\n\tdefer func() {\n\t\tif isLocked {\n\t\t\t// Unlock before returning in case that it wasn't done already.\n\t\t\tl.mu.Unlock()\n\t\t}\n\t}()\n\n\tif l.traceLocation.isSet() {\n\t\tif l.traceLocation.match(file, line) {\n\t\t\tbuf.Write(dbg.Stacks(false))\n\t\t}\n\t}\n\tdata := buf.Bytes()\n\tif logger != nil {\n\t\tif logger.writeKlogBuffer != nil {\n\t\t\tlogger.writeKlogBuffer(data)\n\t\t} else {\n\t\t\t// TODO: set 'severity' and caller information as structured log info\n\t\t\t// keysAndValues := []interface{}{\"severity\", severityName[s], \"file\", file, \"line\", line}\n\t\t\tif s == severity.ErrorLog {\n\t\t\t\tlogger.WithCallDepth(depth+3).Error(nil, string(data))\n\t\t\t} else {\n\t\t\t\tlogger.WithCallDepth(depth + 3).Info(string(data))\n\t\t\t}\n\t\t}\n\t} else if l.toStderr {\n\t\tos.Stderr.Write(data)\n\t} else {\n\t\tif alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {\n\t\t\tos.Stderr.Write(data)\n\t\t}\n\n\t\tif logging.logFile != \"\" {\n\t\t\t// Since we are using a single log file, all of the items in l.file array\n\t\t\t// will point to the same file, so just use one of them to write data.\n\t\t\tif l.file[severity.InfoLog] == nil {\n\t\t\t\tif err := l.createFiles(severity.InfoLog); err != nil {\n\t\t\t\t\tos.Stderr.Write(data) // Make sure the message appears somewhere.\n\t\t\t\t\tl.exit(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tl.file[severity.InfoLog].Write(data)\n\t\t} else {\n\t\t\tif l.file[s] == nil {\n\t\t\t\tif err := l.createFiles(s); err != nil {\n\t\t\t\t\tos.Stderr.Write(data) // Make sure the message appears somewhere.\n\t\t\t\t\tl.exit(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif l.oneOutput {\n\t\t\t\tl.file[s].Write(data)\n\t\t\t} else {\n\t\t\t\tswitch s {\n\t\t\t\tcase severity.FatalLog:\n\t\t\t\t\tl.file[severity.FatalLog].Write(data)\n\t\t\t\t\tfallthrough\n\t\t\t\tcase severity.ErrorLog:\n\t\t\t\t\tl.file[severity.ErrorLog].Write(data)\n\t\t\t\t\tfallthrough\n\t\t\t\tcase severity.WarningLog:\n\t\t\t\t\tl.file[severity.WarningLog].Write(data)\n\t\t\t\t\tfallthrough\n\t\t\t\tcase severity.InfoLog:\n\t\t\t\t\tl.file[severity.InfoLog].Write(data)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif s == severity.FatalLog {\n\t\t// If we got here via Exit rather than Fatal, print no stacks.\n\t\tif atomic.LoadUint32(&fatalNoStacks) > 0 {\n\t\t\tl.mu.Unlock()\n\t\t\tisLocked = false\n\t\t\ttimeoutFlush(ExitFlushTimeout)\n\t\t\tOsExit(1)\n\t\t}\n\t\t// Dump all goroutine stacks before exiting.\n\t\t// First, make sure we see the trace for the current goroutine on standard error.\n\t\t// If -logtostderr has been specified, the loop below will do that anyway\n\t\t// as the first stack in the full dump.\n\t\tif !l.toStderr {\n\t\t\tos.Stderr.Write(dbg.Stacks(false))\n\t\t}\n\n\t\t// Write the stack trace for all goroutines to the files.\n\t\ttrace := dbg.Stacks(true)\n\t\tlogExitFunc = func(error) {} // If we get a write error, we'll still exit below.\n\t\tfor log := severity.FatalLog; log >= severity.InfoLog; log-- {\n\t\t\tif f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.\n\t\t\t\tf.Write(trace)\n\t\t\t}\n\t\t}\n\t\tl.mu.Unlock()\n\t\tisLocked = false\n\t\ttimeoutFlush(ExitFlushTimeout)\n\t\tOsExit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.\n\t}\n\tbuffer.PutBuffer(buf)\n\n\tif stats := severityStats[s]; stats != nil {\n\t\tatomic.AddInt64(&stats.lines, 1)\n\t\tatomic.AddInt64(&stats.bytes, int64(len(data)))\n\t}\n}", "func (c *Client) Log(lvl level, message string, extra map[string]string) error {\n\tfor _, o := range c.cfg.Outputs {\n\t\terr := o.output(newLogBody(lvl.toString(), message, extra))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (svr *Saver) LogCacheStats(localCount, errCount int) {\n\tstats := svr.stats.Copy() // Get a copy\n\tlog.Printf(\"Cache info total %d local %d same %d diff %d new %d err %d\\n\",\n\t\tstats.TotalCount+(int64)(localCount), localCount,\n\t\tstats.TotalCount-((int64)(errCount)+stats.NewCount+stats.DiffCount+(int64)(localCount)),\n\t\tstats.DiffCount, stats.NewCount, errCount)\n}", "func (w *StatsDWriter) Write(results Summary) error {\n\tfor k, v := range results {\n\t\t_, err := fmt.Fprintf(w.writer, \"%s:%d|s\\n\", k, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (l *Logger) Output(ctx context.Context, calldepth int, msg string) {\n\t// This is the bottom of the logger; everything calls this to do writes.\n\t// Handling nil here means everything should be able to be called on a nil\n\t// *Logger and not explode.\n\tif l == nil || l.emitter == nil {\n\t\treturn\n\t}\n\tif l.now == nil {\n\t\tl.now = time.Now\n\t}\n\te := Entry{\n\t\tTime: l.now(),\n\t\tTags: fromContext(ctx),\n\t\tMsg: msg,\n\t}\n\n\tif l.caller {\n\t\tvar ok bool\n\t\t_, e.File, e.Line, ok = runtime.Caller(calldepth)\n\t\tif !ok {\n\t\t\te.File = \"???\"\n\t\t\te.Line = 0\n\t\t}\n\t}\n\n\tl.emitter.Emit(ctx, &e)\n}", "func (manager *Manager) DebugOutput() {\n\tlog.Debugf(\"-------------------------\\n\")\n\tlog.Debugf(\"| Times and Commit Counts|\\n\")\n\tlog.Debugf(\"-------------------------\\n\")\n\tfmt.Println(\"totalScanTime: \", durafmt.Parse(time.Duration(manager.metadata.ScanTime)*time.Nanosecond))\n\tfmt.Println(\"totalPatchTime: \", durafmt.Parse(time.Duration(manager.metadata.patchTime)*time.Nanosecond))\n\tfmt.Println(\"totalCloneTime: \", durafmt.Parse(time.Duration(manager.metadata.cloneTime)*time.Nanosecond))\n\tfmt.Println(\"totalCommits: \", manager.metadata.Commits)\n\n\tconst padding = 6\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, padding, '.', 0)\n\n\tlog.Debugf(\"--------------------------\\n\")\n\tlog.Debugf(\"| Individual Regexes Times |\\n\")\n\tlog.Debugf(\"--------------------------\\n\")\n\tfor k, v := range manager.metadata.RegexTime {\n\t\t_, _ = fmt.Fprintf(w, \"%s\\t%s\\n\", k, durafmt.Parse(time.Duration(v)*time.Nanosecond))\n\t}\n\t_ = w.Flush()\n\n}", "func LogStats() {\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\tlog.Infof(\"Alloc=%v TotalAlloc=%v Sys=%v NumGC=%v Goroutines=%d\",\n\t\tm.Alloc/1024, m.TotalAlloc/1024, m.Sys/1024, m.NumGC, runtime.NumGoroutine())\n\n}", "func StatsOutput(c *VsmStatsCommand, annotations *Annotations, args []string, statusArray []string, stats1 VolumeStats, stats2 VolumeStats) error {\n\n\tvar (\n\t\terr error\n\n\t\tReadLatency int64\n\t\tWriteLatency int64\n\n\t\tAvgReadBlockCountPS int64\n\t\tAvgWriteBlockCountPS int64\n\t)\n\n\t// 10 and 64 represents decimal and bits respectively\n\ti_riops, _ := strconv.ParseInt(stats1.ReadIOPS, 10, 64) // Initial\n\tf_riops, _ := strconv.ParseInt(stats2.ReadIOPS, 10, 64) // Final\n\treadIOPS := f_riops - i_riops\n\n\ti_rtps, _ := strconv.ParseInt(stats1.TotalReadTime, 10, 64)\n\tf_rtps, _ := strconv.ParseInt(stats2.TotalReadTime, 10, 64)\n\treadTimePS := f_rtps - i_rtps\n\n\ti_rbps, _ := strconv.ParseInt(stats1.TotalReadBlockCount, 10, 64)\n\tf_rbps, _ := strconv.ParseInt(stats2.TotalReadBlockCount, 10, 64)\n\treadBlockCountPS := f_rbps - i_rbps\n\n\trThroughput := readBlockCountPS\n\tif readIOPS != 0 {\n\t\tReadLatency = readTimePS / readIOPS\n\t\tAvgReadBlockCountPS = readBlockCountPS / readIOPS\n\t} else {\n\t\tReadLatency = 0\n\t\tAvgReadBlockCountPS = 0\n\t}\n\n\ti_wiops, _ := strconv.ParseInt(stats1.WriteIOPS, 10, 64)\n\tf_wiops, _ := strconv.ParseInt(stats2.WriteIOPS, 10, 64)\n\twriteIOPS := f_wiops - i_wiops\n\n\ti_wtps, _ := strconv.ParseInt(stats1.TotalWriteTime, 10, 64)\n\tf_wtps, _ := strconv.ParseInt(stats2.TotalWriteTime, 10, 64)\n\twriteTimePS := f_wtps - i_wtps\n\n\ti_wbcps, _ := strconv.ParseInt(stats1.TotalWriteBlockCount, 10, 64)\n\tf_wbcps, _ := strconv.ParseInt(stats2.TotalWriteBlockCount, 10, 64)\n\twriteBlockCountPS := f_wbcps - i_wbcps\n\n\twThroughput := writeBlockCountPS\n\tif writeIOPS != 0 {\n\t\tWriteLatency = writeTimePS / writeIOPS\n\t\tAvgWriteBlockCountPS = writeBlockCountPS / writeIOPS\n\t} else {\n\t\tWriteLatency = 0\n\t\tAvgWriteBlockCountPS = 0\n\t}\n\n\tss, _ := strconv.ParseFloat(stats2.SectorSize, 64) // Sector Size\n\tss = ss / bytesToMB\n\n\tls, _ := strconv.ParseFloat(stats2.UsedBlocks, 64) // Logical Size\n\tls = ls * ss\n\n\tau, _ := strconv.ParseFloat(stats2.UsedLogicalBlocks, 64) // Actual Used\n\tau = au * ss\n\n\tannotation := Annotation{\n\t\tIQN: annotations.Iqn,\n\t\tVolume: args[0],\n\t\tPortal: annotations.TargetPortal,\n\t\tSize: annotations.VolSize,\n\t}\n\n\t// json formatting and showing default output\n\tif c.Json == \"json\" {\n\n\t\tstat1 := StatsArr{\n\n\t\t\tIQN: annotations.Iqn,\n\t\t\tVolume: args[0],\n\t\t\tPortal: annotations.TargetPortal,\n\t\t\tSize: annotations.VolSize,\n\n\t\t\tReadIOPS: readIOPS,\n\t\t\tWriteIOPS: writeIOPS,\n\n\t\t\tReadThroughput: float64(rThroughput) / bytesToMB, // bytes to MB\n\t\t\tWriteThroughput: float64(wThroughput) / bytesToMB,\n\n\t\t\tReadLatency: float64(ReadLatency) / mic_sec, // Microsecond\n\t\t\tWriteLatency: float64(WriteLatency) / mic_sec,\n\n\t\t\tAvgReadBlockSize: AvgReadBlockCountPS / bytesToKB, // Bytes to KB\n\t\t\tAvgWriteBlockSize: AvgWriteBlockCountPS / bytesToKB,\n\n\t\t\tSectorSize: ss,\n\t\t\tActualUsed: au,\n\t\t\tLogicalSize: ls,\n\t\t}\n\n\t\tdata, err := json.MarshalIndent(stat1, \"\", \"\\t\")\n\n\t\tif err != nil {\n\n\t\t\tpanic(err)\n\t\t}\n\n\t\tos.Stdout.Write(data)\n\n\t} else {\n\n\t\t// Printing in tabular form\n\t\t//\tfmt.Printf(\"%+v\\n\\n\", annotation)\n\t\tdata, err := json.MarshalIndent(annotation, \"\", \"\\t\")\n\n\t\tif err != nil {\n\n\t\t\tpanic(err)\n\t\t}\n\n\t\tos.Stdout.Write(data)\n\n\t\tq := tabwriter.NewWriter(os.Stdout, minwidth, maxwidth, padding, ' ', tabwriter.AlignRight|tabwriter.Debug)\n\n\t\tfmt.Fprintf(q, \"\\n\\nReplica\\tStatus\\tDataUpdateIndex\\t\\n\")\n\t\tfmt.Fprintf(q, \"\\t\\t\\t\\n\")\n\t\tfor i := 0; i < 4; i += 3 {\n\n\t\t\tfmt.Fprintf(q, \"%s\\t%s\\t%s\\t\\n\", statusArray[i], statusArray[i+1], statusArray[i+2])\n\t\t}\n\n\t\tq.Flush()\n\n\t\tw := tabwriter.NewWriter(os.Stdout, minwidth, maxwidth, padding, ' ', tabwriter.AlignRight|tabwriter.Debug)\n\t\tfmt.Println(\"\\n----------- Performance Stats -----------\\n\")\n\t\tfmt.Fprintf(w, \"r/s\\tw/s\\tr(MB/s)\\tw(MB/s)\\trLat(ms)\\twLat(ms)\\t\\n\")\n\t\tfmt.Fprintf(w, \"%d\\t%d\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t\\n\", readIOPS, writeIOPS, float64(rThroughput)/bytesToMB, float64(wThroughput)/bytesToMB, float64(ReadLatency)/mic_sec, float64(WriteLatency)/mic_sec)\n\t\tw.Flush()\n\n\t\tx := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.AlignRight|tabwriter.Debug)\n\t\tfmt.Println(\"\\n------------ Capacity Stats -------------\\n\")\n\t\tfmt.Fprintf(x, \"Logical(GB)\\tUsed(GB)\\t\\n\")\n\t\tfmt.Fprintf(x, \"%f\\t%f\\t\\n\", ls, au)\n\t\tx.Flush()\n\t}\n\n\treturn err\n}", "func (cb *printcb) outputStat(stats map[string]string) error {\n\tidx := len(*cb)\n\t*cb = append(*cb, FileDetails{})\n\tdetails := &(*cb)[idx]\n\tfor key, value := range stats {\n\t\tif err := setTaggedField(details, key, value, false); err != nil {\n\t\t\tglog.Warningf(\"Couldn't set field %v: %v\", key, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Measurement) PrintStats(w io.Writer) {\n\ttype Hist struct {\n\t\t*Result\n\t\t*hrtime.Histogram\n\t}\n\n\thists := []Hist{}\n\tfor _, result := range m.Results {\n\t\thists = append(hists, Hist{\n\t\t\tResult: result,\n\t\t\tHistogram: hrtime.NewDurationHistogram(result.Durations, &hrtime.HistogramOptions{\n\t\t\t\tBinCount: 10,\n\t\t\t\tNiceRange: true,\n\t\t\t\tClampMaximum: 0,\n\t\t\t\tClampPercentile: 0.999,\n\t\t\t}),\n\t\t})\n\t}\n\n\tmsec := func(ns float64) string {\n\t\treturn fmt.Sprintf(\"%.2f\", ns/1e6)\n\t}\n\n\tfor _, hist := range hists {\n\t\tfmt.Fprintf(w, \"%v\\t%v\\t%v\\t%v\\t%v\\t%v\\t%v\\t%v\\n\",\n\t\t\tm.Parts, m.Segments, hist.Name,\n\t\t\tmsec(hist.Average),\n\t\t\tmsec(hist.Maximum),\n\t\t\tmsec(hist.P50),\n\t\t\tmsec(hist.P90),\n\t\t\tmsec(hist.P99),\n\t\t)\n\t}\n}", "func (l *StdLogger) output(level LogLevel, stackAdjust int, format string, args ...interface{}) {\n\tif level < Level {\n\t\treturn\n\t} \n\tll := l.dlog\n\tswitch level {\n\t\tcase Error: fallthrough\n\t\tcase Warning: ll = l.elog\n\t}\n\tif int(level) < len(headers) && int(level) >= 0 {\n\t\tformat = headers[int(level)] + format\n\t}\n\tll.Output(stackAdjust + 2, fmt.Sprintf(format, args...))\n}", "func (d *InfoResult) EachOutput(h func(r *InfoOutput)) {\n\tfor _, resp := range d.outputs {\n\t\th(resp)\n\t}\n}", "func Write(logtype string, message string) {\n\tsuccess := false\n\tfor _, v := range logsOutput.File {\n\t\tif v.Logtype == logtype {\n\t\t\tlog.SetOutput(v.Logoutput)\n\t\t\tlog.Println(message)\n\t\t\tsuccess = true\n\t\t}\n\t}\n\tlog.SetOutput(os.Stderr)\n\tif !success {\n\t\tlog.Println(\"Type\", logtype, \"was not assigned for log output\")\n\t}\n}", "func writeStats(to *os.File, final bool, s, t stats.Stats) {\n\tp := fmt.Fprintf\n\tpn := prettyNumber\n\tpb := prettyNumBytes\n\tpl := prettyLatency\n\tpt := prettyTimeStamp\n\tif final {\n\t\twriteStatsHeader(to)\n\t\tp(to, statsPrintHeader, pt(), \"Put\",\n\t\t\tpn(t.TotalPuts()),\n\t\t\tpb(t.TotalPutBytes()),\n\t\t\tpl(t.MinPutLatency(), t.AvgPutLatency(), t.MaxPutLatency()),\n\t\t\tpb(t.PutThroughput(time.Now())),\n\t\t\tpn(t.TotalErrPuts()))\n\t\tp(to, statsPrintHeader, pt(), \"Get\",\n\t\t\tpn(t.TotalGets()),\n\t\t\tpb(t.TotalGetBytes()),\n\t\t\tpl(t.MinGetLatency(), t.AvgGetLatency(), t.MaxGetLatency()),\n\t\t\tpb(t.GetThroughput(time.Now())),\n\t\t\tpn(t.TotalErrGets()))\n\t} else {\n\t\t// show interval stats; some fields are shown of both interval and total, for example, gets, puts, etc\n\t\tif s.TotalPuts() != 0 {\n\t\t\tp(to, statsPrintHeader, pt(), \"Put\",\n\t\t\t\tpn(s.TotalPuts())+\"(\"+pn(t.TotalPuts())+\")\",\n\t\t\t\tpb(s.TotalPutBytes())+\"(\"+pb(t.TotalPutBytes())+\")\",\n\t\t\t\tpl(s.MinPutLatency(), s.AvgPutLatency(), s.MaxPutLatency()),\n\t\t\t\tpb(s.PutThroughput(time.Now()))+\"(\"+pb(t.PutThroughput(time.Now()))+\")\",\n\t\t\t\tpn(s.TotalErrPuts())+\"(\"+pn(t.TotalErrPuts())+\")\")\n\t\t}\n\t\tif s.TotalGets() != 0 {\n\t\t\tp(to, statsPrintHeader, pt(), \"Get\",\n\t\t\t\tpn(s.TotalGets())+\"(\"+pn(t.TotalGets())+\")\",\n\t\t\t\tpb(s.TotalGetBytes())+\"(\"+pb(t.TotalGetBytes())+\")\",\n\t\t\t\tpl(s.MinGetLatency(), s.AvgGetLatency(), s.MaxGetLatency()),\n\t\t\t\tpb(s.GetThroughput(time.Now()))+\"(\"+pb(t.GetThroughput(time.Now()))+\")\",\n\t\t\t\tpn(s.TotalErrGets())+\"(\"+pn(t.TotalErrGets())+\")\")\n\t\t}\n\t}\n}", "func (sa *ScanAPI) Log() {\n\t// Check access permissions\n\tif !sa.RequireProjectAccess(sa.pro.ProjectID, rbac.ActionRead, rbac.ResourceScan) {\n\t\treturn\n\t}\n\n\tuuid := sa.GetString(\":uuid\")\n\tbytes, err := scan.DefaultController.GetScanLog(uuid)\n\tif err != nil {\n\t\tsa.SendInternalServerError(errors.Wrap(err, \"scan API: log\"))\n\t\treturn\n\t}\n\n\tif bytes == nil {\n\t\t// Not found\n\t\tsa.SendNotFoundError(errors.Errorf(\"report with uuid %s does not exist\", uuid))\n\t\treturn\n\t}\n\n\tsa.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey(\"Content-Length\"), strconv.Itoa(len(bytes)))\n\tsa.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey(\"Content-Type\"), \"text/plain\")\n\t_, err = sa.Ctx.ResponseWriter.Write(bytes)\n\tif err != nil {\n\t\tsa.SendInternalServerError(errors.Wrap(err, \"scan API: log\"))\n\t}\n}", "func writeLog(msg ...interface{}) {\n\tlogLocker.Lock()\n\tdefer logLocker.Unlock()\n\tif *confVerbose {\n\t\tcolor.Green(fmt.Sprint(time.Now().Format(\"02_01_06-15.04.05\"), \"[WRITE] ->\", msg))\n\t}\n}", "func (r *Results) OutputRunStats() {\n\ts := make([][]string, 0)\n\ts = statStr(s, \"Hard linking statistics\")\n\ts = statStr(s, \"-----------------------\")\n\tif !r.RunSuccessful {\n\t\tvar phase string\n\t\tswitch r.Phase {\n\t\tcase StartPhase:\n\t\t\tphase = \"Start\"\n\t\tcase WalkPhase:\n\t\t\tphase = \"File walk\"\n\t\tcase LinkPhase:\n\t\t\tphase = \"Linking\"\n\t\tdefault:\n\t\t\tphase = \"End\"\n\t\t}\n\t\ts = statStr(s, \"Run stopped early in phase\", phase)\n\t}\n\ts = statStr(s, \"Directories\", r.DirCount)\n\ts = statStr(s, \"Files\", r.FileCount)\n\tif r.Opts.LinkingEnabled {\n\t\ts = statStr(s, \"Hardlinked this run\", r.NewLinkCount)\n\t\ts = statStr(s, \"Removed inodes\", r.InodeRemovedCount)\n\t} else {\n\t\ts = statStr(s, \"Hardlinkable this run\", r.NewLinkCount)\n\t\ts = statStr(s, \"Removable inodes\", r.InodeRemovedCount)\n\t}\n\ts = statStr(s, \"Currently linked bytes\", r.ExistingLinkByteAmount, humanizeParens(r.ExistingLinkByteAmount))\n\ttotalBytes := r.ExistingLinkByteAmount + r.InodeRemovedByteAmount\n\tvar s1, s2 string\n\tif r.Opts.LinkingEnabled {\n\t\ts1 = \"Additional saved bytes\"\n\t\ts2 = \"Total saved bytes\"\n\t} else {\n\t\ts1 = \"Additional saveable bytes\"\n\t\ts2 = \"Total saveable bytes\"\n\t}\n\t// Append some humanized size values to the byte string outputs\n\ts = statStr(s, s1, r.InodeRemovedByteAmount, humanizeParens(r.InodeRemovedByteAmount))\n\ts = statStr(s, s2, totalBytes, humanizeParens(totalBytes))\n\n\ts = statStr(s, \"Total run time\", r.RunTime)\n\n\ttotalLinks := r.ExistingLinkCount + r.NewLinkCount\n\tif r.Opts.ShowExtendedRunStats || r.Opts.DebugLevel > 0 {\n\t\ts = statStr(s, \"Comparisons\", r.ComparisonCount)\n\t\ts = statStr(s, \"Inodes\", r.InodeCount)\n\t\tunwalkedNlinks := r.NlinkCount - r.FileCount\n\t\tif unwalkedNlinks > 0 {\n\t\t\tunwalkedNlinkStr := fmt.Sprintf(\"(Unwalked Nlinks: %v)\", unwalkedNlinks)\n\t\t\ts = statStr(s, \"Inode total nlinks\", r.NlinkCount, unwalkedNlinkStr)\n\t\t}\n\t\ts = statStr(s, \"Existing links\", r.ExistingLinkCount)\n\t\ts = statStr(s, \"Total old + new links\", totalLinks)\n\t\tif r.FileTooLargeCount > 0 {\n\t\t\ts = statStr(s, \"Total too large files\", r.FileTooLargeCount)\n\t\t}\n\t\tif r.FileTooSmallCount > 0 {\n\t\t\ts = statStr(s, \"Total too small files\", r.FileTooSmallCount)\n\t\t}\n\t\tif r.ExcludedDirCount > 0 {\n\t\t\ts = statStr(s, \"Total excluded dirs\", r.ExcludedDirCount)\n\t\t}\n\t\tif r.ExcludedFileCount > 0 {\n\t\t\ts = statStr(s, \"Total excluded files\", r.ExcludedFileCount)\n\t\t}\n\t\tif r.IncludedFileCount > 0 {\n\t\t\ts = statStr(s, \"Total included files\", r.IncludedFileCount)\n\t\t}\n\t\tif r.MismatchedMtimeCount > 0 {\n\t\t\ts = statStr(s, \"Equal files w/ unequal time\", r.MismatchedMtimeCount,\n\t\t\t\thumanizeParens(r.MismatchedMtimeBytes))\n\t\t}\n\t\tif r.MismatchedModeCount > 0 {\n\t\t\ts = statStr(s, \"Equal files w/ unequal mode\", r.MismatchedModeCount,\n\t\t\t\thumanizeParens(r.MismatchedModeBytes))\n\t\t}\n\t\tif r.MismatchedUIDCount > 0 {\n\t\t\ts = statStr(s, \"Equal files w/ unequal uid\", r.MismatchedUIDCount,\n\t\t\t\thumanizeParens(r.MismatchedUIDBytes))\n\t\t}\n\t\tif r.MismatchedGIDCount > 0 {\n\t\t\ts = statStr(s, \"Equal files w/ unequal gid\", r.MismatchedGIDCount,\n\t\t\t\thumanizeParens(r.MismatchedGIDBytes))\n\t\t}\n\t\tif r.MismatchedXAttrCount > 0 {\n\t\t\ts = statStr(s, \"Equal files w/ unequal xattr\", r.MismatchedXAttrCount,\n\t\t\t\thumanizeParens(r.MismatchedXAttrBytes))\n\t\t}\n\t\tif r.MismatchedTotalBytes > 0 {\n\t\t\ts = statStr(s, \"Total equal file mismatches\", r.MismatchedTotalCount,\n\t\t\t\thumanizeParens(r.MismatchedTotalBytes))\n\t\t}\n\t\tif r.BytesCompared > 0 {\n\t\t\ts = statStr(s, \"Total bytes compared\", r.BytesCompared,\n\t\t\t\thumanizeParens(r.BytesCompared))\n\t\t}\n\n\t\tremainingInodes := r.InodeCount - r.InodeRemovedCount\n\t\ts = statStr(s, \"Total remaining inodes\", remainingInodes)\n\n\t\tif r.SkippedSetuidCount > 0 {\n\t\t\ts = statStr(s, \"Skipped setuid files\", r.SkippedSetuidCount)\n\t\t}\n\t\tif r.SkippedSetgidCount > 0 {\n\t\t\ts = statStr(s, \"Skipped setgid files\", r.SkippedSetgidCount)\n\t\t}\n\t\tif r.SkippedNonPermBitCount > 0 {\n\t\t\ts = statStr(s, \"Skipped files with non-perm bits set\", r.SkippedNonPermBitCount)\n\t\t}\n\t\tif r.SkippedDirErrCount > 0 {\n\t\t\ts = statStr(s, \"Dir errors this run\", r.SkippedDirErrCount)\n\t\t}\n\t\tif r.SkippedFileErrCount > 0 {\n\t\t\ts = statStr(s, \"File errors this run\", r.SkippedFileErrCount)\n\t\t}\n\t\tif r.SkippedLinkErrCount > 0 {\n\t\t\ts = statStr(s, \"Link errors this run\", r.SkippedLinkErrCount)\n\t\t}\n\t}\n\n\tif r.Opts.DebugLevel > 0 {\n\t\t// add additional stat output onto the last string\n\t\ts = statStr(s, \"Total file hash hits\", r.FoundHashCount,\n\t\t\tfmt.Sprintf(\"misses: %v sum total: %v\", r.MissedHashCount,\n\t\t\t\tr.FoundHashCount+r.MissedHashCount))\n\t\ts = statStr(s, \"Total hash mismatches\", r.HashMismatchCount,\n\t\t\tfmt.Sprintf(\"(+ total links: %v)\", r.HashMismatchCount+totalLinks))\n\t\ts = statStr(s, \"Total hash list searches\", r.InoSeqSearchCount)\n\t\tavgItersPerSearch := \"N/A\"\n\t\tif r.InoSeqIterationCount > 0 {\n\t\t\tavg := float64(r.InoSeqIterationCount) / float64(r.InoSeqSearchCount)\n\t\t\tavgItersPerSearch = fmt.Sprintf(\"%.1f\", avg)\n\t\t}\n\t\ts = statStr(s, \"Total hash list iterations\", r.InoSeqIterationCount,\n\t\t\tfmt.Sprintf(\"(avg per search: %v)\", avgItersPerSearch))\n\t\ts = statStr(s, \"Total equal comparisons\", r.EqualComparisonCount)\n\t\ts = statStr(s, \"Total digests computed\", r.DigestComputedCount)\n\t\tif r.FailedLinkChtimesCount > 0 {\n\t\t\ts = statStr(s, \"Failed link Chtimes\", r.FailedLinkChtimesCount)\n\t\t}\n\t\tif r.FailedLinkChownCount > 0 {\n\t\t\ts = statStr(s, \"Failed link Chown\", r.FailedLinkChownCount)\n\t\t}\n\t}\n\n\tif r.Opts.DebugLevel > 1 {\n\t\truntime.GC()\n\t\tvar m runtime.MemStats\n\t\truntime.ReadMemStats(&m)\n\t\ts = statStr(s, \"Mem Alloc\", Humanize(m.Alloc))\n\t\ts = statStr(s, \"Mem Sys\", Humanize(m.Sys))\n\t\ts = statStr(s, \"Num live objects\", m.Mallocs-m.Frees)\n\t}\n\tprintSlices(s)\n\n\tif r.Opts.DebugLevel > 2 {\n\t\tfmt.Printf(\"\\nOptions%+v\\n\", r.Opts)\n\t}\n}", "func output(w io.Writer, l Level, v ...interface{}) error {\n\tif l < level {\n\t\treturn nil\n\t}\n\t_, err := fmt.Fprint(w, colorize(l, timestamp(levelPrefix[l]+fmt.Sprintln(v...))))\n\treturn err\n}", "func (m *RoadMap) Log(rank int) {\n\tfmt.Println()\n\tzlog.Info().\n\t\tFloat64(\"distance\", m.Distance).\n\t\tMsgf(\"%dº\", rank)\n\n\tfor _, r := range m.Routes {\n\t\tr.Log()\n\t}\n}", "func (h *Histogram) Log(msg string, percentiles []float64) {\n\tvar b bytes.Buffer\n\tw := bufio.NewWriter(&b)\n\th.Print(w, msg, percentiles)\n\tw.Flush() // nolint: gas,errcheck\n\tlog.Infof(\"%s\", b.Bytes())\n}", "func (l *Logger) Flush() {\n\tfor _, l := range l.outputs {\n\t\tl.Flush()\n\t}\n}", "func (p *HTTPPool) Log(format string,v ...interface{}) {\n\tlog.Printf(\"[Server %s]%s\",p.self,fmt.Sprintf(format,v...))\n}", "func (l *logHandler) Output(calldepth int, s string) error {\n\treturn l.w.Output(calldepth+1, s)\n}", "func PrintStats(w http.ResponseWriter, r *http.Request) {\n var b bytes.Buffer\n // Print the totals\n b.WriteString(\"# HELP logstat_request_total logstat_request_total\\n\")\n b.WriteString(\"# TYPE logstat_request_total counter\\n\")\n for service, sdata := range Stats {\n for status, stdata := range sdata {\n for method, mdata := range stdata {\n b.WriteString(\"logstat_request_total\")\n b.WriteString(\"{service=\\\"\")\n b.WriteString(service)\n b.WriteString(\"\\\",status=\\\"\")\n b.WriteString(strconv.Itoa(status))\n b.WriteString(\"\\\",method=\\\"\")\n b.WriteString(method)\n b.WriteString(\"\\\"} \")\n b.WriteString(strconv.Itoa(int(mdata[CounterRequests])))\n b.WriteString(\"\\n\")\n }\n }\n }\n // Print the time to serve\n b.WriteString(\"# HELP logstat_request_tts_total logstat_request_tts_total\\n\")\n b.WriteString(\"# TYPE logstat_request_tts_total counter\\n\")\n for service, sdata := range Stats {\n for status, stdata := range sdata {\n for method, mdata := range stdata {\n b.WriteString(\"logstat_request_tts_total\")\n b.WriteString(\"{service=\\\"\")\n b.WriteString(service)\n b.WriteString(\"\\\",status=\\\"\")\n b.WriteString(strconv.Itoa(status))\n b.WriteString(\"\\\",method=\\\"\")\n b.WriteString(method)\n b.WriteString(\"\\\"} \")\n b.WriteString(strconv.FormatFloat(mdata[CounterTts], 'f', 3, 64))\n b.WriteString(\"\\n\")\n }\n }\n }\n w.Write([]byte(b.String()))\n}", "func Info(v ...interface{}) {\n std.logger.Output(2, fmt.Sprintln(v...))\n}", "func SetLogOutput(w io.Writer) {\n\tlogger = log.New(w, \"\", log.Lshortfile+log.Lmicroseconds)\n}", "func (rc *ReadContext) LogStats(optimized bool) {\n\n\tlog := log.Stats\n\n\ttextSize := rc.FileSize - rc.BinaryTotalSize // = non binary content = non stream data\n\n\tlog.Println(\"Original:\")\n\tlog.Printf(\"File Size : %s (%d bytes)\\n\", ByteSize(rc.FileSize), rc.FileSize)\n\tlog.Printf(\"Total Binary Data : %s (%d bytes) %4.1f%%\\n\", ByteSize(rc.BinaryTotalSize), rc.BinaryTotalSize, float32(rc.BinaryTotalSize)/float32(rc.FileSize)*100)\n\tlog.Printf(\"Total Text Data : %s (%d bytes) %4.1f%%\\n\\n\", ByteSize(textSize), textSize, float32(textSize)/float32(rc.FileSize)*100)\n\n\t// Only when optimizing we get details about resource data usage.\n\tif optimized {\n\n\t\t// Image stream data of original file.\n\t\tbinaryImageSize := rc.BinaryImageSize + rc.BinaryImageDuplSize\n\n\t\t// Font stream data of original file. (just font files)\n\t\tbinaryFontSize := rc.BinaryFontSize + rc.BinaryFontDuplSize\n\n\t\t// Content stream data, other font related stream data.\n\t\tbinaryOtherSize := rc.BinaryTotalSize - binaryImageSize - binaryFontSize\n\n\t\tlog.Println(\"Breakup of binary data:\")\n\t\tlog.Printf(\"images : %s (%d bytes) %4.1f%%\\n\", ByteSize(binaryImageSize), binaryImageSize, float32(binaryImageSize)/float32(rc.BinaryTotalSize)*100)\n\t\tlog.Printf(\"fonts : %s (%d bytes) %4.1f%%\\n\", ByteSize(binaryFontSize), binaryFontSize, float32(binaryFontSize)/float32(rc.BinaryTotalSize)*100)\n\t\tlog.Printf(\"other : %s (%d bytes) %4.1f%%\\n\\n\", ByteSize(binaryOtherSize), binaryOtherSize, float32(binaryOtherSize)/float32(rc.BinaryTotalSize)*100)\n\t}\n}", "func (t *Tracker) Log() {\n\tlog.Printf(\n\t\t\"track time:\\n\"+\n\t\t\t\" - label [%v]\\n\"+\n\t\t\t\" - run at [%v]\\n\"+\n\t\t\t\" - finish at [%v]\\n\"+\n\t\t\t\" - duration [%v]\\n\",\n\t\tt.Label,\n\t\tt.Run,\n\t\tt.Finish,\n\t\tt.Duration,\n\t)\n}", "func (sl *StdOutLogger) LogInfo(m ...interface{}) {\n\tsl.stdlog(fmt.Sprintf(\"%v\", fmt.Sprint(m...)))\n}", "func (l *logWrapper) Output(calldepth int, s string) error {\n\treturn log.Output(calldepth+1, s)\n}", "func printStats(stats []statisic, hash string) {\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight|tabwriter.Debug)\n\n\tfmt.Fprintf(w, \"%s(w=%d):\\n\", hash, sketchWidth)\n\tfmt.Fprintf(w, \"data set\\tmax. abs.\\tavg. abs.\\tmax. rel.\\tavg. rel.\\t# exact\\n\")\n\n\tfor i := 0; i < len(stats); i++ {\n\t\tstat := stats[i]\n\t\tfmt.Fprintf(w, \"%s\\t%d\\t%d\\t%.2f\\t%.2f\\t%d\\n\", filePaths[i], stat.maxAbs, stat.avgAbs, stat.maxRel, stat.avgRel, 100-stat.misses)\n\t}\n\tfmt.Fprintln(w)\n\tw.Flush()\n}", "func (stats *LogStats) Logf(w io.Writer, params url.Values) error {\n\tif !streamlog.ShouldEmitLog(stats.SQL, stats.RowsAffected, stats.RowsReturned) {\n\t\treturn nil\n\t}\n\n\t// FormatBindVariables call might panic so we're going to catch it here\n\t// and print out the stack trace for debugging.\n\tdefer func() {\n\t\tif x := recover(); x != nil {\n\t\t\tlog.Errorf(\"Uncaught panic:\\n%v\\n%s\", x, tb.Stack(4))\n\t\t}\n\t}()\n\n\tformattedBindVars := \"\\\"[REDACTED]\\\"\"\n\tif !streamlog.GetRedactDebugUIQueries() {\n\t\t_, fullBindParams := params[\"full\"]\n\t\tformattedBindVars = sqltypes.FormatBindVariables(\n\t\t\tstats.BindVariables,\n\t\t\tfullBindParams,\n\t\t\tstreamlog.GetQueryLogFormat() == streamlog.QueryLogFormatJSON,\n\t\t)\n\t}\n\n\t// TODO: remove username here we fully enforce immediate caller id\n\tremoteAddr, username := stats.RemoteAddrUsername()\n\n\tvar fmtString string\n\tswitch streamlog.GetQueryLogFormat() {\n\tcase streamlog.QueryLogFormatText:\n\t\tfmtString = \"%v\\t%v\\t%v\\t'%v'\\t'%v'\\t%v\\t%v\\t%.6f\\t%.6f\\t%.6f\\t%.6f\\t%v\\t%q\\t%v\\t%v\\t%v\\t%q\\t%q\\t%q\\t%v\\t%v\\t%q\\n\"\n\tcase streamlog.QueryLogFormatJSON:\n\t\tfmtString = \"{\\\"Method\\\": %q, \\\"RemoteAddr\\\": %q, \\\"Username\\\": %q, \\\"ImmediateCaller\\\": %q, \\\"Effective Caller\\\": %q, \\\"Start\\\": \\\"%v\\\", \\\"End\\\": \\\"%v\\\", \\\"TotalTime\\\": %.6f, \\\"PlanTime\\\": %v, \\\"ExecuteTime\\\": %v, \\\"CommitTime\\\": %v, \\\"StmtType\\\": %q, \\\"SQL\\\": %q, \\\"BindVars\\\": %v, \\\"ShardQueries\\\": %v, \\\"RowsAffected\\\": %v, \\\"Error\\\": %q, \\\"TabletType\\\": %q, \\\"SessionUUID\\\": %q, \\\"Cached Plan\\\": %v, \\\"TablesUsed\\\": %v, \\\"ActiveKeyspace\\\": %q}\\n\"\n\t}\n\n\ttables := stats.TablesUsed\n\tif tables == nil {\n\t\ttables = []string{}\n\t}\n\ttablesUsed, marshalErr := json.Marshal(tables)\n\tif marshalErr != nil {\n\t\treturn marshalErr\n\t}\n\t_, err := fmt.Fprintf(\n\t\tw,\n\t\tfmtString,\n\t\tstats.Method,\n\t\tremoteAddr,\n\t\tusername,\n\t\tstats.ImmediateCaller(),\n\t\tstats.EffectiveCaller(),\n\t\tstats.StartTime.Format(\"2006-01-02 15:04:05.000000\"),\n\t\tstats.EndTime.Format(\"2006-01-02 15:04:05.000000\"),\n\t\tstats.TotalTime().Seconds(),\n\t\tstats.PlanTime.Seconds(),\n\t\tstats.ExecuteTime.Seconds(),\n\t\tstats.CommitTime.Seconds(),\n\t\tstats.StmtType,\n\t\tstats.SQL,\n\t\tformattedBindVars,\n\t\tstats.ShardQueries,\n\t\tstats.RowsAffected,\n\t\tstats.ErrorStr(),\n\t\tstats.TabletType,\n\t\tstats.SessionUUID,\n\t\tstats.CachedPlan,\n\t\tstring(tablesUsed),\n\t\tstats.ActiveKeyspace,\n\t)\n\n\treturn err\n}", "func (l *Logger) SetOutput(level LogLevel, w io.Writer) {\n\tswitch level {\n\tcase Info:\n\t\tl.logInfo.SetOutput(w)\n\tcase Notice:\n\t\tl.logNotice.SetOutput(w)\n\tcase Warning:\n\t\tl.logWarning.SetOutput(w)\n\tcase Debug:\n\t\tl.logDebug.SetOutput(w)\n\tcase Trace:\n\t\tl.logTrace.SetOutput(w)\n\tcase Error:\n\t\tl.logError.SetOutput(w)\n\tcase Critical:\n\t\tl.logCritical.SetOutput(w)\n\tcase All:\n\t\tl.logInfo.SetOutput(w)\n\t\tl.logNotice.SetOutput(w)\n\t\tl.logWarning.SetOutput(w)\n\t\tl.logDebug.SetOutput(w)\n\t\tl.logTrace.SetOutput(w)\n\t\tl.logError.SetOutput(w)\n\t\tl.logCritical.SetOutput(w)\n\t}\n}", "func (lc StdoutLogger) Log(text string) {\n\tlc(text)\n}", "func (l *Logger) Output(lv Level, calldepth int, s string) error {\n\tif lv >= l.min {\n\t\tif (l.flag & Llevel) != 0 {\n\t\t\treturn l.lg.Output(calldepth, fmt.Sprintf(\"[%v] %s\", lv, s))\n\t\t}\n\t\treturn l.lg.Output(calldepth, s)\n\t}\n\treturn nil\n}", "func (logger *DefaultLogger) WriteLog(log Log) {\n\t// Tiny format: \"Method Url Status Content-Length - Response-time ms\"\n\tstr := fmt.Sprintf(\"%s %s %s %d - %.3f ms\",\n\t\tColorMethod(log[\"Method\"].(string)),\n\t\tlog[\"URL\"],\n\t\tColorStatus(log[\"Status\"].(int)),\n\t\tlog[\"Length\"],\n\t\tfloat64(time.Now().Sub(log[\"Start\"].(time.Time)))/1e6,\n\t)\n\t// Don't block current process.\n\tgo func() {\n\t\tif _, err := fmt.Fprintln(logger.W, str); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}", "func StdoutLogger(format string, args ...interface{}) {\n\tfmt.Print(fmt.Sprintf(format, args...) + \"\\n\")\n}", "func SetOutput(level LogLevel, w io.Writer) func(*Logger) {\n\treturn func(l *Logger) {\n\t\tswitch level {\n\t\tcase Info:\n\t\t\tl.logInfo.SetOutput(w)\n\t\tcase Notice:\n\t\t\tl.logNotice.SetOutput(w)\n\t\tcase Warning:\n\t\t\tl.logWarning.SetOutput(w)\n\t\tcase Debug:\n\t\t\tl.logDebug.SetOutput(w)\n\t\tcase Trace:\n\t\t\tl.logTrace.SetOutput(w)\n\t\tcase Error:\n\t\t\tl.logError.SetOutput(w)\n\t\tcase Critical:\n\t\t\tl.logCritical.SetOutput(w)\n\t\tcase All:\n\t\t\tl.logInfo.SetOutput(w)\n\t\t\tl.logNotice.SetOutput(w)\n\t\t\tl.logWarning.SetOutput(w)\n\t\t\tl.logDebug.SetOutput(w)\n\t\t\tl.logTrace.SetOutput(w)\n\t\t\tl.logError.SetOutput(w)\n\t\t\tl.logCritical.SetOutput(w)\n\t\t}\n\t}\n}", "func SetOutput(w io.Writer, tag string) {\n\tbaseLogger = newJSONLogger(newWriterLogger(w, tag), syslog.LOG_DEBUG, -1)\n}", "func (r *reporter) Log(args ...interface{}) {\n\tr.logs.log(fmt.Sprint(args...))\n}", "func logTo(ctx context.Context, logLevel LogLevel, logKey LogKey, format string, args ...interface{}) {\n\t// Defensive bounds-check for log level. All callers of this function should be within this range.\n\tif logLevel < LevelNone || logLevel >= levelCount {\n\t\treturn\n\t}\n\n\tif logLevel == LevelError {\n\t\tSyncGatewayStats.GlobalStats.ResourceUtilizationStats().ErrorCount.Add(1)\n\t} else if logLevel == LevelWarn {\n\t\tSyncGatewayStats.GlobalStats.ResourceUtilizationStats().WarnCount.Add(1)\n\t}\n\n\tshouldLogConsole := consoleLogger.shouldLog(logLevel, logKey)\n\tshouldLogError := errorLogger.shouldLog(logLevel)\n\tshouldLogWarn := warnLogger.shouldLog(logLevel)\n\tshouldLogInfo := infoLogger.shouldLog(logLevel)\n\tshouldLogDebug := debugLogger.shouldLog(logLevel)\n\tshouldLogTrace := traceLogger.shouldLog(logLevel)\n\n\t// exit early if we aren't going to log anything anywhere.\n\tif !(shouldLogConsole || shouldLogError || shouldLogWarn || shouldLogInfo || shouldLogDebug || shouldLogTrace) {\n\t\treturn\n\t}\n\n\t// Prepend timestamp, level, log key.\n\tformat = addPrefixes(format, ctx, logLevel, logKey)\n\n\t// Warn and error logs also append caller name/line numbers.\n\tif logLevel <= LevelWarn && logLevel > LevelNone {\n\t\tformat += \" -- \" + GetCallersName(2, true)\n\t}\n\n\t// Perform log redaction, if necessary.\n\targs = redact(args)\n\n\tif shouldLogConsole {\n\t\tconsoleLogger.logf(color(format, logLevel), args...)\n\t}\n\tif shouldLogError {\n\t\terrorLogger.logf(format, args...)\n\t}\n\tif shouldLogWarn {\n\t\twarnLogger.logf(format, args...)\n\t}\n\tif shouldLogInfo {\n\t\tinfoLogger.logf(format, args...)\n\t}\n\tif shouldLogDebug {\n\t\tdebugLogger.logf(format, args...)\n\t}\n\tif shouldLogTrace {\n\t\ttraceLogger.logf(format, args...)\n\t}\n}", "func SetOutput(out io.Writer) {\n\tlog.Out = out\n}", "func (l *Logger) Stats(resolution time.Duration) (LogStats, error) {\n\tstats, err := l.client.readLogStats()\n\tif err != nil {\n\t\treturn LogStats{}, err\n\t}\n\tevents := make([]LogEvent, 0, len(stats.Events))\n\tvar last *LogEvent\n\tfor _, le := range stats.Events {\n\t\tnext := LogEvent{\n\t\t\tTime: time.Unix(le.Time, 0).UTC(),\n\t\t\tCount: le.Count,\n\t\t}\n\t\tif last != nil && next.Time.Before(last.Time.Add(resolution)) {\n\t\t\tlast.Count += next.Count\n\t\t} else {\n\t\t\tevents = append(events, next)\n\t\t\tlast = &events[len(events)-1]\n\t\t}\n\t}\n\treturn LogStats{\n\t\tSince: time.Unix(stats.Since, 0).UTC(),\n\t\tTotal: stats.Total,\n\t\tHijacked: stats.Hijacked,\n\t\tPendingTasks: len(l.queue),\n\t\tEvents: events,\n\t}, nil\n}", "func (m *metricSshcheckSftpDuration) emit(metrics pmetric.MetricSlice) {\n\tif m.settings.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func (l Logger) Log(args ...interface{}) {\n\tlog.SetOutput(os.Stdout)\n\tlog.Println(args...)\n}", "func (bagStorer *BagStorer) logResult() {\n\tfor helper := range bagStorer.ResultsChannel {\n\t\thelper.LogResult()\n\t\tbagStorer.CleanUpChannel <- helper\n\t}\n}", "func (ml *MemoryLogger) LogInfo(m ...interface{}) {\n\tml.RingBuffer.Add(fmt.Sprintf(\"%v\", fmt.Sprint(m...)))\n}", "func (aspect LogAspect) Log(level logLevel, format string, items ...interface{}) {\n\tfor _, logger := range aspect.loggers[level] {\n\t\tlogger.Printf(format, items...)\n\t}\n\tfor _, logger := range all.loggers[level] {\n\t\tlogger.Printf(format, items...)\n\t}\n}", "func (hist *Histogram) WriteStatsTo(w io.Writer) (int64, error) {\n\tn, err := fmt.Fprintf(w, \" avg %v; min %v; p50 %v; max %v;\\n p90 %v; p99 %v; p999 %v; p9999 %v;\\n\",\n\t\ttime.Duration(truncate(hist.Average, 3)),\n\t\ttime.Duration(truncate(hist.Minimum, 3)),\n\t\ttime.Duration(truncate(hist.P50, 3)),\n\t\ttime.Duration(truncate(hist.Maximum, 3)),\n\n\t\ttime.Duration(truncate(hist.P90, 3)),\n\t\ttime.Duration(truncate(hist.P99, 3)),\n\t\ttime.Duration(truncate(hist.P999, 3)),\n\t\ttime.Duration(truncate(hist.P9999, 3)),\n\t)\n\treturn int64(n), err\n}", "func LogSetOutput(iowr io.Writer) {\n\tmuLogt.Lock()\n\tdefer muLogt.Unlock()\n\tlogSetOutput(iowr)\n}", "func SetOutput(w io.Writer) {\n\tlogging.mu.Lock()\n\tdefer logging.mu.Unlock()\n\tfor s := severity.FatalLog; s >= severity.InfoLog; s-- {\n\t\trb := &redirectBuffer{\n\t\t\tw: w,\n\t\t}\n\t\tlogging.file[s] = rb\n\t}\n}", "func (l *Logger) Output(callDepth int, level int, format string, v ...interface{}) {\n\tif l.level > level {\n\t\treturn\n\t}\n\n\tbuf := l.popBuf()\n\n\tif l.flag&Ltime > 0 {\n\t\tnow := time.Now().Format(TimeFormat)\n\t\tbuf = append(buf, now...)\n\t\tbuf = append(buf, \" - \"...)\n\t}\n\n\tif l.flag&Llevel > 0 {\n\t\tbuf = append(buf, LevelName[level]...)\n\t\tbuf = append(buf, \" - \"...)\n\t}\n\n\tif l.flag&Lfile > 0 {\n\t\t_, file, line, ok := runtime.Caller(callDepth)\n\t\tif !ok {\n\t\t\tfile = \"???\"\n\t\t\tline = 0\n\t\t} else {\n\t\t\tfor i := len(file) - 1; i > 0; i-- {\n\t\t\t\tif file[i] == '/' {\n\t\t\t\t\tfile = file[i+1:]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbuf = append(buf, file...)\n\t\tbuf = append(buf, \":[\"...)\n\n\t\tbuf = strconv.AppendInt(buf, int64(line), 10)\n\t\tbuf = append(buf, \"] - \"...)\n\t}\n\n\ts := fmt.Sprintf(format, v...)\n\n\tbuf = append(buf, s...)\n\n\tif s[len(s)-1] != '\\n' {\n\t\tbuf = append(buf, '\\n')\n\t}\n\n\tl.msg <- buf\n}", "func logSetOutput(iowr io.Writer) {\n\tlogt.SetOutput(iowr)\n\tlogOutputCur = iowr\n}", "func Output(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg config.ClusterConfig, runner command.Runner, lines int, logOutput *os.File) error {\n\tcmds := logCommands(r, bs, cfg, lines, false)\n\tcmds[\"kernel\"] = \"uptime && uname -a && grep PRETTY /etc/os-release\"\n\n\tnames := []string{}\n\tfor k := range cmds {\n\t\tnames = append(names, k)\n\t}\n\n\tout.SetOutFile(logOutput)\n\tdefer out.SetOutFile(os.Stdout)\n\tout.SetErrFile(logOutput)\n\tdefer out.SetErrFile(os.Stderr)\n\n\tsort.Strings(names)\n\tfailed := []string{}\n\tfor i, name := range names {\n\t\tif i > 0 {\n\t\t\tout.Styled(style.Empty, \"\")\n\t\t}\n\t\tout.Styled(style.Empty, \"==> {{.name}} <==\", out.V{\"name\": name})\n\t\tvar b bytes.Buffer\n\t\tc := exec.Command(\"/bin/bash\", \"-c\", cmds[name])\n\t\tc.Stdout = &b\n\t\tc.Stderr = &b\n\t\tif rr, err := runner.RunCmd(c); err != nil {\n\t\t\tklog.Errorf(\"command %s failed with error: %v output: %q\", rr.Command(), err, rr.Output())\n\t\t\tfailed = append(failed, name)\n\t\t\tcontinue\n\t\t}\n\t\tl := \"\"\n\t\tscanner := bufio.NewScanner(&b)\n\t\tfor scanner.Scan() {\n\t\t\tl += scanner.Text() + \"\\n\"\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tklog.Errorf(\"failed to read output: %v\", err)\n\t\t\tfailed = append(failed, name)\n\t\t}\n\t\tout.Styled(style.Empty, l)\n\t}\n\n\tif len(failed) > 0 {\n\t\treturn fmt.Errorf(\"unable to fetch logs for: %s\", strings.Join(failed, \", \"))\n\t}\n\treturn nil\n}", "func Info(format string, a ...interface{}) {\n\tif currentLogger == nil {\n\t\treturn\n\t}\n\tcurrentLogger.output(currentPool, _InfoLevel, format, a...)\n}", "func (s *Server) Log(a ...interface{}) {\n\tif s.logger == nil {\n\t\treturn\n\t}\n\t_, _ = fmt.Fprintln(*s.logger, a...)\n}", "func (l *LoggerAsWriter) Write(p []byte) (int, error) {\n\tfor _, logger := range l.ourLoggers {\n\t\t// Skip = 3 because this presumes that we have been called by log.Println()\n\t\t// If the caller has used log.Output or the like this will be wrong\n\t\tlogger.Log(3, l.level, string(p))\n\t}\n\treturn len(p), nil\n}", "func (l *Lgr) Info(args ...interface{}) {\n l.Logger.Info(args...)\n}", "func writeStatsHeader(to *os.File) {\n\tfmt.Fprintln(to)\n\tfmt.Fprintf(to, statsPrintHeader,\n\t\t\"Time\", \"OP\", \"Count\", \"Total Bytes\", \"Latency(min, avg, max)\", \"Throughput\", \"Error\")\n}", "func (l *Logger) Output(level int, calldepth int, format string, v ...interface{}) error {\n\tif level < l.level {\n\t\treturn nil\n\t}\n\n\ts := fmt.Sprintf(format+\"\\n\", v...)\n\n\tlevelName := LlevelName[level]\n\n\tnow := time.Now() // get this early.\n\tvar funcName string\n\tvar pc uintptr\n\tvar file string\n\tvar line int\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tif l.flag&(Lshortfile|Llongfile) != 0 {\n\t\t// Release lock while getting caller info - it's expensive.\n\t\tl.mu.Unlock()\n\t\tvar ok bool\n\t\tpc, file, line, ok = runtime.Caller(calldepth)\n\t\tfuncName = runtime.FuncForPC(pc).Name()\n\t\tif !ok {\n\t\t\tfile = \"???\"\n\t\t\tline = 0\n\t\t}\n\t\tl.mu.Lock()\n\t}\n\n\tl.FormatHeader(now, funcName, file, line, levelName)\n\n\tl.buf = append(l.buf, \" | \"...)\n\tl.buf = append(l.buf, s...)\n\tif len(s) == 0 || s[len(s)-1] != '\\n' {\n\t\tl.buf = append(l.buf, '\\n')\n\t}\n\t_, err := l.out.Write(l.buf)\n\treturn err\n}", "func (ses *Ses) log(enabled bool, v ...interface{}) {\n\tLog := _drv.Cfg().Log\n\tif !Log.IsEnabled(enabled) {\n\t\treturn\n\t}\n\tif len(v) == 0 {\n\t\tLog.Logger.Infof(\"%v %v\", ses.sysName(), callInfo(2))\n\t} else {\n\t\tLog.Logger.Infof(\"%v %v %v\", ses.sysName(), callInfo(2), fmt.Sprint(v...))\n\t}\n}", "func (r *loggingWriter) Write(p []byte) (int, error) {\n\tif r.accessStats.status == 0 {\n\t\t// The status will be StatusOK if WriteHeader has not been called yet\n\t\tr.accessStats.status = http.StatusOK\n\t}\n\twritten, err := r.ResponseWriter.Write(p)\n\tr.accessStats.size += written\n\treturn written, err\n}", "func (sch *scheduler) logRedundantStats(s *session) {\n\n\tfilename := \"Server_scheduler_stats.json\"\n\tos.Remove(filename)\n\tlogStatsFile, _ := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)\n\n\tdupQuota := 0.0\n\tif sch.allSntBytes != 0 {\n\t\tdupQuota = float64(sch.duplicatedStreamBytes) / float64(sch.allSntBytes) * 100.0\n\t}\n\tutils.Debugf(\"Duplicated Stream Bytes %d (%f %%)\", sch.duplicatedStreamBytes, dupQuota)\n\n\tdropQuota := 0.0\n\tif sch.duplicatedPackets != 0 {\n\t\tdropQuota = float64(sch.droppedDuplicatedPackets) / float64(sch.duplicatedPackets) * 100.0\n\t}\n\tutils.Debugf(\"Total redundant droppings %d/%d (%f %%)\", sch.droppedDuplicatedPackets, sch.duplicatedPackets, dropQuota)\n\n\tsch.pathLogMapSync.RLock()\n\tpathStats := \"[\"\n\tfor pathID, pth := range s.paths {\n\t\tpackets, retransmissions, losses, sentStreamFrameBytes := pth.sentPacketHandler.GetStatistics()\n\t\tpathStats += \" { \\\"pathID\\\": \" + strconv.FormatUint(uint64(pathID), 10) +\n\t\t\t\", \\\"pathIP\\\" : \\\"\" + pth.conn.LocalAddr().String() + \"\\\"\" +\n\t\t\t\", \\\"sendPackets\\\" : \" + strconv.FormatUint(packets, 10) +\n\t\t\t\", \\\"retransmissions\\\" : \" + strconv.FormatUint(retransmissions, 10) +\n\t\t\t\", \\\"losses\\\" : \" + strconv.FormatUint(losses, 10) +\n\t\t\t\", \\\"sentStreamFrameBytes\\\" : \" + strconv.FormatUint(sentStreamFrameBytes, 10) +\n\t\t\t\", \\\"selectedAsBestPath\\\" : \" + strconv.FormatUint(sch.bestPathSelection[pathID], 10) +\n\t\t\t\"},\"\n\t}\n\tpathStats = pathStats[0 : len(pathStats)-1]\n\tpathStats += \"]\"\n\tsch.pathLogMapSync.RUnlock()\n\n\tlogStatsFile.WriteString(\n\t\t\"{ \\\"totalSentPackets\\\" : \" + strconv.FormatUint(s.allSntPackets, 10) +\n\t\t\t\", \\\"duplicatedPackets\\\" : \" + strconv.FormatUint(sch.duplicatedPackets, 10) +\n\t\t\t\", \\\"duplicatedDroppedPackets\\\" : \" + strconv.FormatUint(sch.droppedDuplicatedPackets, 10) +\n\t\t\t\", \\\"duplicatedPacketDropRate\\\" : \" + strconv.FormatFloat(dropQuota, 'g', -1, 64) +\n\t\t\t\", \\\"totalStreamBytes\\\" : \" + strconv.FormatUint(sch.allSntBytes, 10) +\n\t\t\t\", \\\"duplicatedStreamBytes\\\" : \" + strconv.FormatUint(sch.duplicatedStreamBytes, 10) +\n\t\t\t\", \\\"duplicateStreamRate\\\" : \" + strconv.FormatFloat(dupQuota, 'g', -1, 64) +\n\t\t\t\", \\\"blockedCWhighestTPPath\\\" : \" + strconv.FormatUint(sch.cwBlocks, 10) +\n\t\t\t\", \\\"lowerRTTSchedules\\\" : \" + strconv.FormatUint(sch.lowerRTTSchedules, 10) +\n\t\t\t\", \\\"pathSwitches\\\" : \" + strconv.FormatUint(sch.pathSwitches, 10) +\n\t\t\t\", \\\"pathStats\\\" : \" + pathStats +\n\t\t\t\"}\")\n\n\tlogStatsFile.Close()\n}", "func (e *Huobi) Log(msgs ...interface{}) {\n\te.logger.Log(constant.INFO, \"\", 0.0, 0.0, msgs...)\n}", "func (a API) Stats(c echo.Context) error {\n\tvar output []OutputStat\n\tvar err error\n\n\tif output, err = a.maxRecord(); err != nil {\n\t\tc.Logger().Error(err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, \"please contact administrator\")\n\t}\n\tif len(output) == 0 {\n\t\treturn c.NoContent(http.StatusNoContent)\n\t}\n\treturn c.JSON(http.StatusOK, output)\n}", "func (f *FakeOutput) Logger() *zap.SugaredLogger { return f.SugaredLogger }", "func (d *dispatcher) log(fmt string, v ...interface{}) {\n\tif d.logger != nil {\n\t\td.logger.Printf(fmt, v...)\n\t}\n}", "func setupLogOutput(verbosity verbosityLevel) {\n\tif verbosity == verbosityNormal {\n\t\tlogrus.SetOutput(ioutil.Discard)\n\t\treturn\n\t}\n\n\t// If we have any level of verbosity, start piping things to stderr\n\tlogrus.SetOutput(os.Stderr)\n\t// Any verbosity of very or higher (should one eventually exist) should emit debug logs.\n\tif verbosity >= verbosityVery {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t}\n}", "func (l *LoggerAsWriter) Log(msg string) {\n\tfor _, logger := range l.ourLoggers {\n\t\t// Set the skip to reference the call just above this\n\t\t_ = logger.Log(1, l.level, msg)\n\t}\n}", "func Info(v ...interface{}) error {\n\treturn output(os.Stdout, LevelInfo, v...)\n}", "func (writer GlogWriter) Write(data []byte) (n int, err error) {\n\tglog.Info(string(data))\n\treturn len(data), nil\n}", "func (l *Logger) Output(calldepth int, s string) error {\n\t// Get time early if we need it.\n\tvar now time.Time\n\tif l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {\n\t\tnow = time.Now()\n\t}\n\tvar file string\n\tvar line int\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tif l.flag&(Lshortfile|Llongfile) != 0 {\n\t\t// Release lock while getting caller info - it's expensive.\n\t\tl.mu.Unlock()\n\t\tvar ok bool\n\t\t_, file, line, ok = runtime.Caller(calldepth)\n\t\tif !ok {\n\t\t\tfile = \"???\"\n\t\t\tline = 0\n\t\t}\n\t\tl.mu.Lock()\n\t}\n\tl.buf = l.buf[:0]\n\tl.formatHeader(&l.buf, now, file, line)\n\tl.buf = append(l.buf, s...)\n\tif len(s) == 0 || s[len(s)-1] != '\\n' {\n\t\tl.buf = append(l.buf, '\\n')\n\t}\n\tl.openFile()\n\t_, err := l.out.Write(l.buf)\n\tl.closeFile()\n\treturn err\n}", "func (t *Tester) OutputDebugLogs() {\n\tklusterletes, err := t.OperatorClient.OperatorV1().Klusterlets().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list klusterlets. error: %v\", err)\n\t}\n\tfor _, klusterlet := range klusterletes.Items {\n\t\tklog.Infof(\"klusterlet %v : %#v \\n\", klusterlet.Name, klusterlet)\n\t}\n\n\tmanagedClusters, err := t.ClusterClient.ClusterV1().ManagedClusters().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list managedClusters. error: %v\", err)\n\t}\n\tfor _, managedCluster := range managedClusters.Items {\n\t\tklog.Infof(\"managedCluster %v : %#v \\n\", managedCluster.Name, managedCluster)\n\t}\n\n\tregistrationPods, err := t.KubeClient.CoreV1().Pods(\"\").List(context.Background(),\n\t\tmetav1.ListOptions{LabelSelector: \"app=klusterlet-registration-agent\"})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list registration pods. error: %v\", err)\n\t}\n\n\tmanifestWorkPods, err := t.KubeClient.CoreV1().Pods(\"\").List(context.Background(),\n\t\tmetav1.ListOptions{LabelSelector: \"app=klusterlet-manifestwork-agent\"})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get manifestwork pods. error: %v\", err)\n\t}\n\n\tagentPods := append(registrationPods.Items, manifestWorkPods.Items...)\n\tfor _, pod := range agentPods {\n\t\tklog.Infof(\"klusterlet agent pod %v/%v : %#v \\n\", pod.Namespace, pod.Name, pod)\n\t\tlogs, err := t.PodLog(pod.Name, pod.Namespace, int64(10))\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to get pod %v/%v log. error: %v\", pod.Namespace, pod.Name, err)\n\t\t\tcontinue\n\t\t}\n\t\tklog.Infof(\"pod %v/%v logs:\\n %v \\n\", pod.Namespace, pod.Name, logs)\n\t}\n\n\tmanifestWorks, err := t.WorkClient.WorkV1().ManifestWorks(\"\").List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list manifestWorks. error: %v\", err)\n\t}\n\tfor _, manifestWork := range manifestWorks.Items {\n\t\tklog.Infof(\"manifestWork %v/%v : %#v \\n\", manifestWork.Namespace, manifestWork.Name, manifestWork)\n\t}\n}", "func Log(values map[string]interface{}) {\n\t_, ok := values[LevelKey]\n\tif !ok {\n\t\tvalues[LevelKey] = LevelInfo\n\t}\n\n\tfor _, l := range loggers {\n\t\tl.Log(values)\n\t}\n}", "func RecordStats(statsJson string) {\n\tif statsLogger != nil {\n\t\tstatsLogger.logf(statsJson)\n\t}\n}", "func printStats(start time.Time, numFiles int64, totalFileSize int64, numErrors int) {\n\tfileSizeMB := totalFileSize / 1024 / 1024\n\texecTime := time.Since(start).Seconds()\n\tfmt.Println()\n\tfmt.Println(\"-------------- RUNTIME STATS -----------------\")\n\tfmt.Printf(\"hornet version : %s\\n\", version)\n\tfmt.Printf(\"date : %s\\n\", time.Now().Format(time.RFC1123))\n\tfmt.Printf(\"elapsed time : %f s\\n\", execTime)\n\tfmt.Printf(\"# file errors : %d\\n\", numErrors)\n\tfmt.Printf(\"files processed : %d\\n\", numFiles)\n\tfmt.Printf(\"data processed : %d MB\\n\", fileSizeMB)\n\tfmt.Printf(\"throughput : %f MB/s\\n\", float64(fileSizeMB)/execTime)\n}", "func logger(c *gin.Context) {\n\tvar start time.Time\n\tconst logFormat = \"%s \" + // Timestamp\n\t\t\"%s \" + // Client ip\n\t\t\"%d \" + // Response code\n\t\t\"%v \" + // Response Duration\n\t\t`\"%s %s %s\" ` + // Request method, path and protocol\n\t\t\"%d \" // Response size\n\n\tdefer func() {\n\t\tconst INTERNAL_SERVER_ERROR = 500\n\t\tif err := recover(); err != nil {\n\t\t\tduration := time.Now().Sub(start)\n\t\t\tlog.Printf(logFormat+\"\\n%v\\n%s\",\n\t\t\t\tstart.Format(timeFormat),\n\t\t\t\tc.ClientIP(),\n\t\t\t\tINTERNAL_SERVER_ERROR,\n\t\t\t\tduration,\n\t\t\t\tc.Request.Method,\n\t\t\t\tc.Request.URL.Path,\n\t\t\t\tc.Request.Proto,\n\t\t\t\tc.Writer.Size(),\n\t\t\t\terr,\n\t\t\t\tdebug.Stack(),\n\t\t\t)\n\t\t\tc.AbortWithStatus(INTERNAL_SERVER_ERROR)\n\t\t}\n\t}()\n\tstart = time.Now()\n\tc.Next()\n\tduration := time.Now().Sub(start)\n\tlog.Printf(logFormat+\"\\n%s\",\n\t\tstart.Format(timeFormat),\n\t\tc.ClientIP(),\n\t\tc.Writer.Status(),\n\t\tduration,\n\t\tc.Request.Method,\n\t\tc.Request.URL.Path,\n\t\tc.Request.Proto,\n\t\tc.Writer.Size(),\n\t\tc.Errors.String(),\n\t)\n}", "func Logger(next http.Handler) http.HandlerFunc {\n\tstdlogger := log.New(os.Stdout, \"\", 0)\n\t//errlogger := log.New(os.Stderr, \"\", 0)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\n\t\t// Process request\n\t\twriter := statusWriter{w, 0}\n\t\tnext.ServeHTTP(&writer, r)\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\n\t\tclientIP := r.RemoteAddr\n\t\tmethod := r.Method\n\t\tstatusCode := writer.status\n\t\tstatusColor := colorForStatus(statusCode)\n\t\tmethodColor := colorForMethod(method)\n\n\t\tstdlogger.Printf(\"[HTTP] %v |%s %3d %s| %12v | %s |%s %s %-7s %s\\n\",\n\t\t\tend.Format(\"2006/01/02 - 15:04:05\"),\n\t\t\tstatusColor, statusCode, reset,\n\t\t\tlatency,\n\t\t\tclientIP,\n\t\t\tmethodColor, reset, method,\n\t\t\tr.URL.Path,\n\t\t)\n\t}\n}", "func (a *Adapter) log(ctx context.Context, logLevel string, message string, options ...interface{}) {\n\n\t// check whether the message should be logged\n\tif !a.isLoggable(logLevel) {\n\t\treturn\n\t}\n\n\tm := a.formatMessage(ctx, logLevel, message, options...)\n\n\ta.toConsole(m)\n\ta.toFile(m)\n}", "func (r *Results) OutputResults() {\n\tshowStats := r.Opts.ShowRunStats || r.Opts.ShowExtendedRunStats\n\n\tr.OutputExistingLinks()\n\tif len(r.ExistingLinks) > 0 &&\n\t\t(len(r.LinkPaths) > 0 || len(r.SkippedLinkPaths) > 0 || showStats) {\n\t\tfmt.Println(\"\")\n\t}\n\n\tr.OutputNewLinks()\n\tif len(r.LinkPaths) > 0 && (len(r.SkippedLinkPaths) > 0 || showStats) {\n\t\tfmt.Println(\"\")\n\t}\n\n\tr.OutputSkippedNewLinks()\n\tif len(r.SkippedLinkPaths) > 0 && showStats {\n\t\tfmt.Println(\"\")\n\t}\n\n\tif showStats {\n\t\tr.OutputRunStats()\n\t}\n}", "func (l *logger) WriteLog(s ...interface{}) {\n\tl.Lock()\n\tdefer l.Unlock()\n\tl.buffer.WriteString(fmt.Sprintf(\"%s %s\", l.timeInterface.GetNow(), l.GetLogLevel()))\n\tl.makeLogContent(s...)\n\t//l.mysqlChan <- l.buffer.String()\n\tl.buffer.WriteString(\"\\n\")\n\tl.fd.Write(l.buffer.Bytes())\n\tl.buffer.Reset()\n}", "func infoLog(v ...interface{}) {\n\t// if source info is enabled, prepend the log data with source information\n\tif enableSourceInfo {\n\t\tv = append([]interface{}{getSourceInfo(), s}, v...)\n\t}\n\n\tlog.Print(v...)\n}", "func SetOutput(w io.Writer) {\n\tgolog.SetOutput(w)\n}", "func Info(v ...interface{}) {\n\tstdLogger.Print(v...)\n}", "func Info(args ...interface{}) {\n\tlogWithFilename().Info(args...)\n}", "func (c *StatsClient) logger() *log.Logger {\n\treturn log.New(c.LogOutput, \"\", log.LstdFlags)\n}", "func initLogger() {\n\tlogdir := viper.GetString(\"log.log_dir\")\n\tstdout := viper.GetBool(\"log_stdout\")\n\n\tvar writer io.Writer\n\n\tif logdir != \"\" {\n\t\tfolderPath, err := filepath.Abs(logdir)\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on parsing log path: %s\", logdir))\n\n\t\tabspath, err := filepath.Abs(path.Join(logdir, \"run.log\"))\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on parsing log file path: %s\", logdir))\n\n\t\terr = os.MkdirAll(folderPath, os.ModePerm)\n\t\tpanicIfError(err, fmt.Sprintf(\"Error on creating log dir: %s\", folderPath))\n\n\t\tif stdout {\n\t\t\tfmt.Println(\"Will be logged to stdout and \", abspath)\n\t\t\tfileWriter := mylog.RotateLog(abspath)\n\t\t\twriter = io.MultiWriter(os.Stdout, fileWriter)\n\t\t} else {\n\t\t\tfmt.Println(\"Will be logged to \", abspath)\n\t\t\twriter = mylog.RotateLog(abspath)\n\t\t}\n\t} else {\n\t\t// stdout only\n\t\tfmt.Println(\"Will be logged to stdout\")\n\t\twriter = os.Stdout\n\t}\n\tlogrus.SetOutput(writer)\n\n\t// Only log the warning severity or above.\n\tswitch viper.GetString(\"log.level\") {\n\tcase \"panic\":\n\t\tlogrus.SetLevel(logrus.PanicLevel)\n\tcase \"fatal\":\n\t\tlogrus.SetLevel(logrus.FatalLevel)\n\tcase \"error\":\n\t\tlogrus.SetLevel(logrus.ErrorLevel)\n\tcase \"warn\":\n\t\tlogrus.SetLevel(logrus.WarnLevel)\n\tcase \"info\":\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\tcase \"debug\":\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\tcase \"trace\":\n\t\tlogrus.SetLevel(logrus.TraceLevel)\n\tdefault:\n\t\tfmt.Println(\"Unknown level\", viper.GetString(\"log.level\"), \"Set to INFO\")\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t}\n\n\tFormatter := new(logrus.TextFormatter)\n\tFormatter.ForceColors = false\n\tFormatter.DisableColors = true\n\tFormatter.TimestampFormat = \"06-01-02 15:04:05.000000\"\n\tFormatter.FullTimestamp = true\n\tlogrus.SetFormatter(Formatter)\n\n\t// redirect standard log to logrus\n\t//log.SetOutput(logrus.StandardLogger().Writer())\n\t//log.Println(\"Standard logger. Am I here?\")\n\tlineNum := viper.GetBool(\"log_line_number\")\n\tif lineNum {\n\t\t//filenameHook := filename.NewHook()\n\t\t//filenameHook.Field = \"line\"\n\t\t//logrus.AddHook(filenameHook)\n\t\tlogrus.SetReportCaller(true)\n\t}\n\tbyLevel := viper.GetBool(\"multifile_by_level\")\n\tif byLevel && logdir != \"\" {\n\t\tpanicLog, _ := filepath.Abs(path.Join(logdir, \"panic.log\"))\n\t\tfatalLog, _ := filepath.Abs(path.Join(logdir, \"fatal.log\"))\n\t\twarnLog, _ := filepath.Abs(path.Join(logdir, \"warn.log\"))\n\t\terrorLog, _ := filepath.Abs(path.Join(logdir, \"error.log\"))\n\t\tinfoLog, _ := filepath.Abs(path.Join(logdir, \"info.log\"))\n\t\tdebugLog, _ := filepath.Abs(path.Join(logdir, \"debug.log\"))\n\t\ttraceLog, _ := filepath.Abs(path.Join(logdir, \"trace.log\"))\n\t\twriterMap := lfshook.WriterMap{\n\t\t\tlogrus.PanicLevel: mylog.RotateLog(panicLog),\n\t\t\tlogrus.FatalLevel: mylog.RotateLog(fatalLog),\n\t\t\tlogrus.WarnLevel: mylog.RotateLog(warnLog),\n\t\t\tlogrus.ErrorLevel: mylog.RotateLog(errorLog),\n\t\t\tlogrus.InfoLevel: mylog.RotateLog(infoLog),\n\t\t\tlogrus.DebugLevel: mylog.RotateLog(debugLog),\n\t\t\tlogrus.TraceLevel: mylog.RotateLog(traceLog),\n\t\t}\n\t\tlogrus.AddHook(lfshook.NewHook(\n\t\t\twriterMap,\n\t\t\tFormatter,\n\t\t))\n\t}\n\tlogger := logrus.StandardLogger()\n\tlogrus.Debug(\"Logger initialized.\")\n\tbyModule := viper.GetBool(\"multifile_by_module\")\n\tif !byModule {\n\t\tlogdir = \"\"\n\t}\n\n\tdownloader.InitLoggers(logger, logdir)\n\tfetcher.InitLoggers(logger, logdir)\n\tp2p.InitLoggers(logger, logdir)\n\tog.InitLoggers(logger, logdir)\n\tsyncer.InitLoggers(logger, logdir)\n\tannsensus.InitLoggers(logger, logdir)\n\n}", "func (lx *LXRHash) Log(msg string) {\n\tif lx.verbose {\n\t\tfmt.Println(msg)\n\t}\n}", "func (l *GrpcLog) Info(args ...interface{}) {\n\t// l.SugaredLogger.Info(args...)\n}", "func logStatsCSV(name string, times []time.Duration) {\n\tnr := len(times)\n\tif nr == 0 {\n\t\treturn\n\t}\n\tsort.Slice(times, func(a, b int) bool {\n\t\treturn int64(times[a]) < int64(times[b])\n\t})\n\tvar sum time.Duration\n\tfor _, d := range times {\n\t\tsum += d\n\t}\n\tvar mean = (sum / time.Duration(nr)).Nanoseconds() / 1000\n\tvar sqrdiff float64\n\tfor _, d := range times {\n\t\tvar tmp = float64(d.Nanoseconds()/1000.0 - mean)\n\t\tsqrdiff += tmp * tmp\n\t}\n\tvar stddev = math.Sqrt(sqrdiff / float64(nr))\n\tfmt.Printf(\"%s,%v,%v,%v,%v,%.2f,%s\\n\",\n\t\tname, // test name\n\t\tmean, // mean\n\t\ttimes[nr/2].Nanoseconds()/1000, // median\n\t\ttimes[0].Nanoseconds()/1000, // minimum\n\t\ttimes[nr-1].Nanoseconds()/1000, // maximum\n\t\tstddev, // standard deviation\n\t\t\"\") // collection label\n}", "func (l *Logger) Info(log ...interface{}) {\n\tl.instance.Info(log...)\n}", "func init() {\n\tlog.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)\n\tlog.SetOutput(os.Stdout)\n}" ]
[ "0.680837", "0.6039698", "0.6038768", "0.5924901", "0.5796917", "0.5652235", "0.56242526", "0.5620106", "0.56045973", "0.5572503", "0.5500622", "0.5486929", "0.53948975", "0.53909", "0.5349086", "0.5295915", "0.52923536", "0.52890617", "0.52746356", "0.5259584", "0.5251158", "0.5246677", "0.5238658", "0.5229027", "0.5219764", "0.5210088", "0.52038103", "0.5180865", "0.5169201", "0.5168874", "0.51676965", "0.51622266", "0.51560986", "0.51097935", "0.5109231", "0.507924", "0.5075131", "0.50573343", "0.503549", "0.50236714", "0.5023341", "0.50161207", "0.5011854", "0.5007865", "0.49963266", "0.49922493", "0.49815056", "0.49795762", "0.49710712", "0.497012", "0.49691465", "0.49648973", "0.49605486", "0.4957247", "0.4956847", "0.49502975", "0.49501392", "0.49415463", "0.49410385", "0.49407905", "0.49345478", "0.4922475", "0.49209896", "0.49142036", "0.49053496", "0.49033996", "0.48984206", "0.48937857", "0.4891192", "0.48908088", "0.48907614", "0.4887483", "0.48771298", "0.48750773", "0.48713043", "0.4870122", "0.4865564", "0.48573002", "0.4854313", "0.48519066", "0.4845419", "0.48443168", "0.48422384", "0.48393208", "0.48330808", "0.48291454", "0.48235843", "0.48205113", "0.4819038", "0.48143357", "0.48091504", "0.48074386", "0.48039302", "0.48013258", "0.48009908", "0.47987768", "0.47888932", "0.47850257", "0.4782906", "0.47824526" ]
0.51933074
27
Reset clears the counter to reset it to original 'no data' state.
func (c *Counter) Reset() { var empty Counter *c = empty }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Counter) Reset() { c.n = 0 }", "func (c *Counter) Reset() {\n\tc.Lock()\n\tc.Unlock()\n\tc.lastFail = time.Time{}\n\tc.lastSuccess = time.Time{}\n\tc.failure = 0\n\tc.success = 0\n}", "func (c *Counter) Reset() {\n\tc.global.Store(0)\n\tc.window.Store(0)\n}", "func (c *Counter) Reset() {\n\tc.bits.Reset()\n}", "func (c *Counter) Reset() {\n\tc.NextLineConcats = 0\n\tc.CurlyBrackets = 0\n\tc.SquareBrackets = 0\n\tc.Parentheses = 0\n}", "func (c *counter) reset() {\n\tc.messages, c.samples = 0, 0\n}", "func (c *counter) reset() {\n\tc.messages, c.samples = 0, 0\n}", "func (c *Counter) Reset() {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.rate = 0.0\n\tc.ticksPrevious = 0\n\tc.ticksCurrent = 0\n\tc.v = 0\n\tc.p = 0\n}", "func (c *standardResettingCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func (NilCounter) Clear() {}", "func (NilCounter) Clear() {}", "func (s *SafeCount) Reset() {\n\ts.mu.Lock()\n\t{\n\t\ts.i = 0\n\t}\n\ts.mu.Unlock()\n}", "func (c *CTR) Reset() {\n\tc.blocks = 0\n\tc.ks = nil\n}", "func (s *dataSet) Reset() {\n\ts.dataPtr = len(s.buf)\n\ts.dataWritten = 0\n\ts.idxPtr = 0\n\ts.idxWritten = 0\n}", "func (c *StandardCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func (c *StandardCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func ResetCount() {\n\tcount = 0\n}", "func (h *Histogram) Reset() {\n\th.Counter.Reset()\n\t// Leave Offset and Divider alone\n\tfor i := 0; i < len(h.Hdata); i++ {\n\t\th.Hdata[i] = 0\n\t}\n}", "func (s *Statistics) reset() {\n\ts.cycles++\n\ts.totalMessagesCleared += s.messagesCleared\n\n\ts.memoryCleared = 0\n\ts.messagesCleared = 0\n}", "func (v *OperationIdentifier) Reset() {\n\tv.Index = 0\n\tv.NetworkIndex.Value = 0\n\tv.NetworkIndex.Set = false\n}", "func (c *SwitchTicker) Reset() {\n\tatomic.StoreInt64(&c.failCount, 0)\n}", "func (i *identity) Reset() {\n\ti.data = make([]byte, 0)\n}", "func (plan *DeploymentPlan) ResetCounter() {\n\tplan.commandCounter = 0\n}", "func (c *Calculator) Reset() {\n\tlog.Printf(\"Reset.\\n\")\n\tvalue = 0\n\tc.returnResult()\n}", "func (c *ChannelData) Reset() {\n\tc.Raw = c.Raw[:0]\n\tc.Length = 0\n\tc.Data = c.Data[:0]\n}", "func (s *State) Reset() {\n\ts.hash = 0\n\ts.clen = 0\n\ts.tail = nil\n}", "func (m *Msg) Reset() {\n\tm.Id = 0\n\tm.Flags = 0\n\tm.data = m.data[:0]\n}", "func (rd *ratedisp) reset() {\n\trd.start = time.Now()\n\trd.cnt = 0\n\trd.size = 0\n}", "func (da *DataFrame) Reset() {\n\tda.chunk = 0\n\tda.nobs = 0\n\tda.done = false\n}", "func (e *Zero) Reset() {}", "func (h *HashReader) Reset() {\n\th.count = 0\n\th.hasher.Reset()\n}", "func (ds *DataSet) ResetData() {\n\tds.data = nil\n}", "func (errors *Errors) Reset() {\n\terrors.counter.Reset()\n}", "func (s *Store) Reset() {\n\ts.access.Lock()\n\tdefer s.access.Unlock()\n\n\tfor key, _ := range s.data {\n\t\tdelete(s.data, key)\n\t\ts.sendDataChanged()\n\t\ts.doKeyChanged(key)\n\t}\n\n\ts.data = make(map[string]interface{})\n}", "func Reset() {\n\treset()\n}", "func (s Counters) Reset() Counters {\n\tfor i := range s {\n\t\ts[i] = Counter{}\n\t}\n\treturn s[:0]\n}", "func Reset() {\n\tstats.Reset()\n}", "func (i *Integer) Reset() {\n\ti.Value = 0\n\ti.Initialized = false\n\tIntegerPool.Put(i)\n}", "func (t *Tracker) Reset() {\n\t// acquire mutex\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t// reset timestamp\n\tt.last = time.Now()\n}", "func (v *SyncStatus) Reset() {\n\tv.CurrentIndex.Value = 0\n\tv.CurrentIndex.Set = false\n\tv.Stage.Value = \"\"\n\tv.Stage.Set = false\n\tv.Synced.Value = false\n\tv.Synced.Set = false\n\tv.TargetIndex.Value = 0\n\tv.TargetIndex.Set = false\n}", "func (c *calculon) Reset(ctx context.Context, arg calculator.Empty) (calculator.Result, error) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.current = 0\n\treturn calculator.Result{c.current }, nil\n}", "func (s *Stack) Reset() {\n\ts.data = nil\n}", "func (cb *CircuitBreaker) Reset() {\n\tcb.counter.Reset()\n\tcb.state.Reset()\n\tcb.Unblock()\n}", "func (s Counters) Zero() {\n\tfor i := range s {\n\t\tc := &s[i]\n\t\tc.Count = 0\n\t}\n}", "func (c ShmCounter) Clear() {\n\tatomic.StoreInt64((*int64)(unsafe.Pointer(c)), 0)\n}", "func (s *Stats) Reset() {\n\ts.Client.Init()\n\ts.Error.Init()\n\ts.Subscription.Init()\n}", "func (hc *cmdCollector) Reset() {\n}", "func Reset() int {\n\tstatus := C.Reset()\n\treturn int(status)\n}", "func (c *Counter) Clear() {\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\n\tc.count = make(map[interface{}]int)\n}", "func (d *RabinKarp64) Reset() {\n\td.tables = nil\n\td.value = 0\n\td.window = d.window[:0]\n\td.oldest = 0\n\td.updateTables()\n}", "func (e *Timing) Reset() {\n\te.Min = 0\n\te.Max = 0\n\te.Value = 0\n\te.Values = make(float64Slice, 0)\n\te.Count = 0\n}", "func (sc *Scavenger) Reset() {\n\tsc.mu.Lock()\n\tsc.entries = nil\n\tsc.mu.Unlock()\n}", "func (v *Coin) Reset() {\n\tv.Amount.Reset()\n\tv.CoinIdentifier.Reset()\n}", "func (r *RegionStatistics) Reset() {\n\tregionMissPeerRegionCounter.Set(0)\n\tregionExtraPeerRegionCounter.Set(0)\n\tregionDownPeerRegionCounter.Set(0)\n\tregionPendingPeerRegionCounter.Set(0)\n\tregionOfflinePeerRegionCounter.Set(0)\n\tregionLearnerPeerRegionCounter.Set(0)\n\tregionEmptyRegionCounter.Set(0)\n\tregionOversizedRegionCounter.Set(0)\n\tregionUndersizedRegionCounter.Set(0)\n\tregionWitnessLeaderRegionCounter.Set(0)\n}", "func (r *BasicResampler) Reset() {\n\tr.sampleAggregates = r.sampleAggregates[:0]\n}", "func (v *OperationStatus) Reset() {\n\tv.Status = \"\"\n\tv.Successful = false\n}", "func (p containerJSONItemRemover) Reset() {\n\tp.removedDataIndex = make(map[int]bool)\n}", "func (cr *ClientResponse) Reset() {\n\tcr.offset = 0\n\tcr.nbatches = 0\n\tcr.err = nil\n\tcr.mokBuf = nil\n\tcr.ok = false\n\tcr.nmok = 0\n}", "func (s *MockStore) Reset() {\n\ts.Data = map[string]map[string]string{}\n}", "func (cv *ConVar) Reset() {\n\tcv.value.Store(cv.valDefault)\n}", "func (d *pmac) Reset() {\n\td.digest.Clear()\n\td.offset.Clear()\n\td.buf.Clear()\n\td.pos = 0\n\td.ctr = 0\n\td.finished = false\n}", "func (dc *DatadogCollector) Reset() {}", "func (w *Writer) Reset() {\n\tw.n = 0\n\tw.err = nil\n}", "func (m *pollerUsageEstimator) Reset() {\n\tm.atomicBits.Store(0)\n}", "func (cb *CircuitBreaker) Reset() {\n\tcb.setState(CircuitBreakerStateEnabled)\n\tcb.ConsecutiveFailures = 0\n\tcb.NextCheckTime = nil\n}", "func (b *batch) Reset() {\n\tb.batch.Clear()\n\tb.size = 0\n}", "func (cs *ConnStats) Reset() {\n\tcs.lock.Lock()\n\tcs.RPCCalls = 0\n\tcs.RPCTime = 0\n\tcs.BytesWritten = 0\n\tcs.BytesRead = 0\n\tcs.WriteCalls = 0\n\tcs.WriteErrors = 0\n\tcs.ReadCalls = 0\n\tcs.ReadErrors = 0\n\tcs.DialCalls = 0\n\tcs.DialErrors = 0\n\tcs.AcceptCalls = 0\n\tcs.AcceptErrors = 0\n\tcs.lock.Unlock()\n}", "func (n *Number) Reset() {\n\tn.Value = 0.0\n\tn.Initialized = false\n\tNumberPool.Put(n)\n}", "func (p *ProgressBar) Reset() {\n\tp.lock.Lock()\n\tdefer p.lock.Unlock()\n\n\tp.state = getBlankState()\n}", "func (lm *LevelManager) Reset() {\n\tlm.currentLevelNumber = 0\n}", "func (cc *computer) reset() {\n\tcc.accumulator = 0\n\tcc.instrPointer = 0\n\tcc.history = make([]int, len(cc.instructions))\n}", "func (s *Snowball) Reset() {\n\ts.Preferred = nil\n\ts.Last = nil\n\n\ts.Counts = make(map[[blake2b.Size256]byte]uint16)\n\ts.Count = 0\n\n\ts.Done = false\n}", "func (c resettableComponent) ClearSentData() {\n\tc.IComponent.ClearSentData()\n\tfor _, counter := range c.counters {\n\t\tcounter.Clear()\n\t}\n}", "func (v *Amount) Reset() {\n\tv.Currency.Reset()\n\tv.Metadata = v.Metadata[:0]\n\tv.Value = \"\"\n}", "func (s *Greeter) ResetCounters() {\n\ts.mutex.Lock()\n\ts.callCounts[Unary] = 0\n\ts.callCounts[ServerStream] = 0\n\ts.callCounts[ClientStream] = 0\n\ts.callCounts[Bidi] = 0\n\ts.mutex.Unlock()\n\n\tif s.Stats != nil {\n\t\ts.Stats.mutex.Lock()\n\t\ts.Stats.connCount = 0\n\t\ts.Stats.mutex.Unlock()\n\t}\n}", "func (s *MemorySession) Reset() error {\n\t// reset counter and stores\n\ts.Counter.Reset()\n\ts.Incoming.Reset()\n\ts.Outgoing.Reset()\n\n\treturn nil\n}", "func (l *FixedLimiter) Reset() {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.value = 0\n}", "func (c *PNGCopyCounters) Reset() {\n\tc.ToCopy = 400\n\tc.Layers = 0\n\tc.CopiedBytes = 0\n\tc.StoredBytes = 0\n\tside := int(math.Sqrt(float64(c.ToCopy)))\n\tc.Image = image.NewGray(image.Rect(0, 0, side, side))\n\tc.Image.Pix = make([]byte, c.ToCopy)\n\tc.Buffer = &bytes.Buffer{}\n\tc.Buffer.Reset()\n}", "func (m *MockImpl) Reset() {\n\tm.recording = make([]Transaction, 0)\n\tm.simulateGetError = nil\n\tm.simulateAddError = nil\n}", "func (m *MockImpl) Reset() {\n\tm.recording = make([]Transaction, 0)\n\tm.simulateGetError = nil\n\tm.simulateAddError = nil\n\tm.simulateUpdateError = nil\n}", "func (m *Message) Reset() {\n\tresetHeader(m.Header)\n\tm.Payload = m.Payload[:0]\n\tm.data = m.data[:0]\n}", "func (b *Buffer) Reset() {\n b.size = 0\n b.offset = 0\n}", "func (d *Decoder) Reset() {\n\td.buffer = []byte{}\n\td.complete = false\n\td.total = 0\n\td.frames = []frameInfo{}\n\td.cache = map[string]struct{}{}\n\n\td.progress = 0\n\td.speed = 0\n\td.start = time.Time{}\n\td.lastChunk = time.Time{}\n\td.readInterval = 0\n}", "func (s *Snapshot) Reset() {\n\t*s = Snapshot{\n\t\tCounters: events.Counters(s.Counters).Reset(),\n\t}\n}", "func (message *Message) Reset() {\n\tif message == nil {\n\t\treturn\n\t}\n\n\tmessage.mutex.Lock()\n\tdefer message.mutex.Unlock()\n\n\tmessage.ack = make(chan struct{}, 0)\n\tmessage.nack = make(chan struct{}, 0)\n\tmessage.response = UnkownResolvedStatus\n\n\treturn\n}", "func (b *Buffer) Reset() {\n\tb.start = 0\n\tb.used = 0\n}", "func (b *batch) Reset() {\n\tb.writes = b.writes[:0]\n\tb.size = 0\n}", "func (d *state) Reset() {\n\t// Zero the permutation's state.\n\tfor i := range d.a {\n\t\td.a[i] = 0\n\t}\n\td.state = spongeAbsorbing\n\td.buf = d.storage[:0]\n}", "func (d *digest) Reset() { d.crc = 0 }", "func (c *Curl) Reset() {\n\tfor i := range c.state {\n\t\tc.state[i] = 0\n\t}\n\tc.direction = SpongeAbsorbing\n}", "func (s *sum64_128) Reset() {\n\ts.h1, s.h2, s.k1, s.k2, s.length, s.offset = 0, 0, 0, 0, 0, 0\n}", "func (rr *ResourceRecord) Reset() {\n\trr.Name = rr.Name[:0]\n\trr.Type = QueryTypeZERO\n\trr.Class = QueryClassZERO\n\trr.TTL = 0\n\trr.rdlen = 0\n\trr.rdata = rr.rdata[:0]\n\trr.Text = nil\n\trr.SOA = nil\n\trr.WKS = nil\n\trr.HInfo = nil\n\trr.MInfo = nil\n\trr.MX = nil\n\trr.OPT = nil\n\trr.off = 0\n\trr.offTTL = 0\n}", "func (v *CoinChange) Reset() {\n\tv.CoinAction = \"\"\n\tv.CoinIdentifier.Reset()\n}", "func (v *Operation) Reset() {\n\tv.Account.Value.Reset()\n\tv.Account.Set = false\n\tv.Amount.Value.Reset()\n\tv.Amount.Set = false\n\tv.CoinChange.Value.Reset()\n\tv.CoinChange.Set = false\n\tv.Metadata = v.Metadata[:0]\n\tv.OperationIdentifier.Reset()\n\tv.RelatedOperations = v.RelatedOperations[:0]\n\tv.Status.Value = \"\"\n\tv.Status.Set = false\n\tv.Type = \"\"\n}", "func (b *Buffer) Reset() {\n\tb.mux.Lock()\n\tdefer b.mux.Unlock()\n\n\tb.data = make([]byte, len(b.data))\n\tb.dataSize = 0\n\tb.head, b.tail = 0, 0\n}", "func (ref *digest) Reset() {\n\tref.ptr = 0\n\tref.cnt = 0\n\tcopy(ref.h[:], kInit[:])\n}", "func (c *PrometheusCollector) Reset() {\n\tc.RWMutex.Lock()\n\tdefer c.RWMutex.Unlock()\n}", "func (t *Tx) Reset() {\n\tt.Status = TxNone\n\tif !t.IsEmpty() {\n\t\tt.Ops = nil\n\t}\n}", "func (reader *Reader) Reset() (e error) {\n\te = reader.Flush()\n\tif e != nil {\n\t\treturn\n\t}\n\te = reader.dataset.(tabula.DatasetInterface).Reset()\n\treturn\n}", "func (c *Cipher) Reset() {\n\tfor i := range c.state {\n\t\tc.state[i] = 0\n\t}\n\tfor i := range c.buf {\n\t\tc.buf[i] = 0\n\t}\n}" ]
[ "0.78308314", "0.7520165", "0.73536634", "0.7295654", "0.72185487", "0.71448356", "0.71448356", "0.7116816", "0.7066918", "0.6882138", "0.6882138", "0.68437505", "0.67747796", "0.67619026", "0.6729472", "0.6729472", "0.6675341", "0.6660722", "0.6555883", "0.65421313", "0.6540637", "0.65345186", "0.652937", "0.65201527", "0.6478182", "0.646074", "0.64590174", "0.64369273", "0.6417297", "0.64171416", "0.64062995", "0.6392015", "0.6382061", "0.638066", "0.6374079", "0.6372967", "0.63291425", "0.6312846", "0.6312247", "0.63120496", "0.630588", "0.6305407", "0.6302716", "0.62920046", "0.6290365", "0.6284711", "0.62785506", "0.62768734", "0.62764144", "0.6273356", "0.62686276", "0.625882", "0.62433803", "0.6234852", "0.62257344", "0.6222377", "0.62149", "0.6213632", "0.6190092", "0.61900485", "0.61780804", "0.6164847", "0.6164609", "0.6163585", "0.61611813", "0.61585253", "0.6137581", "0.61340183", "0.61189944", "0.61157495", "0.61142826", "0.6112026", "0.6105733", "0.6104858", "0.61044824", "0.6103988", "0.61007965", "0.6100225", "0.6091622", "0.6068134", "0.6063038", "0.60492826", "0.6046303", "0.6045372", "0.6044674", "0.60443884", "0.6043072", "0.604045", "0.60364807", "0.60312325", "0.60292596", "0.60263944", "0.60250044", "0.6020273", "0.60150224", "0.6014294", "0.6014009", "0.6007259", "0.6001884", "0.59951127" ]
0.77540463
1
Transfer merges the data from src into this Counter and clears src.
func (c *Counter) Transfer(src *Counter) { if src.Count == 0 { return // nothing to do } if c.Count == 0 { *c = *src // copy everything at once src.Reset() return } c.Count += src.Count if src.Min < c.Min { c.Min = src.Min } if src.Max > c.Max { c.Max = src.Max } c.Sum += src.Sum c.sumOfSquares += src.sumOfSquares src.Reset() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Histogram) Transfer(src *Histogram) {\n\tif src.Count == 0 {\n\t\treturn\n\t}\n\tif h.Count == 0 {\n\t\th.CopyFrom(src)\n\t\tsrc.Reset()\n\t\treturn\n\t}\n\th.copyHDataFrom(src)\n\th.Counter.Transfer(&src.Counter)\n\tsrc.Reset()\n}", "func (c *PNGCopyCounters) Clear() {\n\tc.StoredBytes = 0\n\tif c.CopiedBytes >= c.ToCopy && c.Created {\n\t\tc.Image = nil\n\t\tc.Buffer = nil\n\t}\n}", "func (self *nativePduBuffer) Clear() {\n\tself.start = 0\n\tself.count = 0\n}", "func (c *PNGCopyCounters) Reset() {\n\tc.ToCopy = 400\n\tc.Layers = 0\n\tc.CopiedBytes = 0\n\tc.StoredBytes = 0\n\tside := int(math.Sqrt(float64(c.ToCopy)))\n\tc.Image = image.NewGray(image.Rect(0, 0, side, side))\n\tc.Image.Pix = make([]byte, c.ToCopy)\n\tc.Buffer = &bytes.Buffer{}\n\tc.Buffer.Reset()\n}", "func (NilCounter) Clear() {}", "func (NilCounter) Clear() {}", "func (c *counter) reset() {\n\tc.messages, c.samples = 0, 0\n}", "func (c *counter) reset() {\n\tc.messages, c.samples = 0, 0\n}", "func (c *standardResettingCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func (c *Chunk) Clear() {\n\tc.data = nil\n}", "func (v *Data) UClear() {\n\t*v = (*v)[:0]\n}", "func (s *UniformSample) Clear() {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\ts.count = 0\n\ts.values = make([]int64, 0, s.reservoirSize)\n}", "func (h *Histogram) copyHDataFrom(src *Histogram) {\n\tif h.Divider == src.Divider && h.Offset == src.Offset {\n\t\tfor i := 0; i < len(h.Hdata); i++ {\n\t\t\th.Hdata[i] += src.Hdata[i]\n\t\t}\n\t\treturn\n\t}\n\n\thData := src.Export()\n\tfor _, data := range hData.Data {\n\t\th.record((data.Start+data.End)/2, int(data.Count))\n\t}\n}", "func (v *Data) Clear() {\n\tv.Truncate(0)\n}", "func (c *MockSource) Del(ctx *Context, next Next) {\n\t// source cache, like mysql/oss/rdb, etc\n\t// do not delete the data in source cache\n}", "func (c resettableComponent) ClearSentData() {\n\tc.IComponent.ClearSentData()\n\tfor _, counter := range c.counters {\n\t\tcounter.Clear()\n\t}\n}", "func (c ShmCounter) Clear() {\n\tatomic.StoreInt64((*int64)(unsafe.Pointer(c)), 0)\n}", "func (d *Driver) Clear() {\n\tfor i := 0; i < len(d.buff); i++ {\n\t\td.buff[i] = 0\n\t}\n}", "func (h *Histogram) CopyFrom(src *Histogram) {\n\th.Counter = src.Counter\n\th.copyHDataFrom(src)\n}", "func (c *Counter) Clear(prefix string) {\n\tif !c.stopped {\n\t\tc.controlChannel <- controlRecord{\"clear\", prefix}\n\t}\n}", "func (h *NormalHopper) Refill() {\n\tfor _, v := range h.Source {\n\t\tvar copiedCard Card\n\t\tcopiedCard = v // this copies???\n\t\th.Cards = append(h.Cards, copiedCard)\n\t}\n\trand.Shuffle(len(h.Cards), func(i, j int) {\n\t\th.Cards[i], h.Cards[j] = h.Cards[j], h.Cards[i]\n\t})\n}", "func (d Data) Del(key uint32) {\n\td.mutex.Lock()\n\tcount := d.counts[key]\n\tcount -= 1\n\tif count < 1 {\n\t\tdelete(d.data, key)\n\t\tdelete(d.counts, key)\n\t} else {\n\t\td.counts[key] = count\n\t}\n\td.mutex.Unlock()\n}", "func (b *Buffer) Clear() {\n\tb.currentSize = 0\n\tb.contents = map[entity.Key]inventoryapi.PostDeltaBody{}\n}", "func (this *channelStruct) Clear() {\n\tthis.samples = make([]float64, 0)\n}", "func (c *StandardCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func (c *StandardCounter) Clear() {\n\tatomic.StoreInt64(&c.count, 0)\n}", "func (queue *Queue) Clear() {\n\tqueue.data = queue.data[:0]\n}", "func (b *Buf) Reset() { b.b = b.b[:0] }", "func (s *Streams) Clear() {\n\ts.Buffer.Clear()\n}", "func (pb *PacketBuffer) Clear() {\n\tpb.numPackets = 0\n\tpb.offsets[0] = 0\n}", "func (s *IntSlicer) Clear() {\n\ts.slice = []int{}\n}", "func (r *Transformer) flushSource(source string, deleteSource bool) error {\n\tbatch := r.batchMap[source]\n\t// Skip flushing a combined log if the batch is empty\n\tif batch == nil {\n\t\treturn nil\n\t}\n\n\tif len(batch.entries) == 0 {\n\t\tr.removeBatch(source)\n\t\treturn nil\n\t}\n\n\t// Choose which entry we want to keep the rest of the fields from\n\tvar base *entry.Entry\n\tentries := batch.entries\n\n\tif r.overwriteWithOldest {\n\t\tbase = entries[0]\n\t} else {\n\t\tbase = entries[len(entries)-1]\n\t}\n\n\t// Set the recombined field on the entry\n\terr := base.Set(r.combineField, batch.recombined.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Write(context.Background(), base)\n\tif deleteSource {\n\t\tr.removeBatch(source)\n\t} else {\n\t\tbatch.entries = batch.entries[:0]\n\t\tbatch.recombined.Reset()\n\t}\n\n\treturn nil\n}", "func (b *Buffer) Clear() {\n\tb.series = make(map[string]*influxdb.Series)\n\tb.size = 0\n}", "func (c *Counter) Reset() {\n\tvar empty Counter\n\t*c = empty\n}", "func (c *Counter) Clear() {\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\n\tc.count = make(map[interface{}]int)\n}", "func (rb *RingBuffer[T]) Clear() {\n\trb.mu.Lock()\n\tdefer rb.mu.Unlock()\n\trb.pos = 0\n\trb.buf = nil\n}", "func (s *segment) merge(oth *segment) {\n\ts.pkt.Data().Merge(oth.pkt.Data())\n\ts.dataMemSize = s.pkt.MemSize()\n\toth.dataMemSize = oth.pkt.MemSize()\n}", "func (s *Statistics) reset() {\n\ts.cycles++\n\ts.totalMessagesCleared += s.messagesCleared\n\n\ts.memoryCleared = 0\n\ts.messagesCleared = 0\n}", "func (ds *Dataset) Clear() {\n\tds.min = math.MaxFloat64\n\tds.max = math.SmallestNonzeroFloat64\n\tds.product = 1\n\tds.total = 0\n\tds.recipsum = 0\n\tds.values = ds.values[:0]\n}", "func (d PacketData) Merge(oth PacketData) {\n\toth.pk.buf.TrimFront(int64(oth.pk.dataOffset()))\n\td.pk.buf.Merge(&oth.pk.buf)\n}", "func (h *FoilHopper) Refill() {\n\tfor _, v := range h.Source {\n\t\tvar copiedCard Card\n\t\tcopiedCard = v // this copies???\n\t\th.Cards = append(h.Cards, copiedCard)\n\t}\n\trand.Shuffle(len(h.Cards), func(i, j int) {\n\t\th.Cards[i], h.Cards[j] = h.Cards[j], h.Cards[i]\n\t})\n}", "func (b *batch) Reset() {\n\tb.writes = b.writes[:0]\n\tb.size = 0\n}", "func (r *PackageAggRow) ClearCount() { r.Data.Count = nil }", "func (h *BasicLandHopper) Refill() {\n\tfor _, v := range h.Source {\n\t\tvar copiedCard Card\n\t\tcopiedCard = v // this copies???\n\t\th.Cards = append(h.Cards, copiedCard)\n\t}\n\t// no need to shuffle\n}", "func (bio *BinaryIO) Copy(dst int64, src int64, count int) error {\n\tbuf := makeBuf(count)\n\tfor count > 0 {\n\t\tbuf = truncBuf(buf, count)\n\t\tbio.ReadAt(src, buf)\n\t\tbio.WriteAt(dst, buf)\n\t\tcount -= len(buf)\n\t\tsrc += int64(len(buf))\n\t\tdst += int64(len(buf))\n\t}\n\treturn nil\n}", "func (c *ChannelData) Reset() {\n\tc.Raw = c.Raw[:0]\n\tc.Length = 0\n\tc.Data = c.Data[:0]\n}", "func (c *Counter) flush() {\n\tatomic.StoreUint64(&c.value, 0)\n}", "func (d *Dropping) Reset() {\n\t// We need to create a new slice because the existing one\n\t// may have already been put onto o channel or referenced\n\t// in another way.\n\td.batch = make(Batch, d.maxSize)\n\td.next = 0\n}", "func (c *Counter) Reset() { c.n = 0 }", "func (b *batch) Reset() {\n\tb.batch.Clear()\n\tb.size = 0\n}", "func (b *Buffer) ClearFrom(o int) {\n\tfor l := len(b.Tiles); o < l; o++ {\n\t\tb.Tiles[o] = nil\n\t}\n}", "func (r *Reader) Reset(srcR io.Reader, buf []byte) {\n\tr.srcR = srcR\n\tr.ResetBuf(buf)\n}", "func dupe(src []byte) []byte {\n\td := make([]byte, len(src))\n\tcopy(d, src)\n\treturn d\n}", "func (h *MapInt16ToInt8) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (r *Ring) Clear() {\n\tr.size, r.in, r.out = 0, 0, 0\n}", "func (m *IntervalMutation) ClearDataSource() {\n\tm.cleareddata_source = true\n}", "func (batch *Batch) Clear() {\n\tbatch.mutex.Lock()\n\tdefer batch.mutex.Unlock()\n\tbatch.messages = batch.messages[0:0]\n}", "func (h *MapInt16ToInt) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (rra *RoundRobinArchive) clear() {\n\tif len(rra.dps) > 0 {\n\t\trra.dps = make(map[int64]float64)\n\t}\n}", "func (c *cache) clear() {\n\tc.cursor = 0\n\tc.chunks = make(map[FileID]location)\n\tc.sums = c.sums[:0]\n}", "func (c *Concurrent) Clear() {\n\tfor {\n\t\tselect {\n\t\tcase <-c.values:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *Secp256k1N) Clear() {\n\tx.limbs[0] = 0\n\tx.limbs[1] = 0\n\tx.limbs[2] = 0\n\tx.limbs[3] = 0\n\tx.limbs[4] = 0\n}", "func (b *Buffer) Reset() {\n\tb.buf = b.buf[:0]\n}", "func (c *AdapterMemory) Clear(ctx context.Context) error {\n\treturn c.data.Clear()\n}", "func (c Counters) Merge(other Counters) Counters {\n\tresult := c.Copy()\n\tfor k, v := range other {\n\t\tresult[k] = result[k] + v\n\t}\n\treturn result\n}", "func (s *dataSet) Reset() {\n\ts.dataPtr = len(s.buf)\n\ts.dataWritten = 0\n\ts.idxPtr = 0\n\ts.idxWritten = 0\n}", "func (h *MapInt16ToInt32) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (l *List) Clear() {\n\tl.Source = nil\n}", "func (s *sum64_128) Reset() {\n\ts.h1, s.h2, s.k1, s.k2, s.length, s.offset = 0, 0, 0, 0, 0, 0\n}", "func (h *MapInt16ToInt64) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (dst *Worker) Merge(src Worker) {\n\tif dst == nil || dst.Name != src.Name {\n\t\treturn\n\t}\n\n\tif src.Enabled != nil {\n\t\tdst.Enabled = src.Enabled\n\t}\n\tif src.Command != \"\" {\n\t\tdst.Command = src.Command\n\t}\n\tif len(src.Commands) > 0 {\n\t\tdst.Commands = strings.Unique(append(dst.Commands, src.Commands...))\n\t}\n\tif src.Replicas != 0 {\n\t\tdst.Replicas = src.Replicas\n\t}\n\tif src.LivenessProbe != \"\" {\n\t\tdst.LivenessProbe = src.LivenessProbe\n\t}\n\tif src.Size != \"\" {\n\t\tdst.Size = src.Size\n\t}\n\n\tif src.Resources != nil && dst.Resources == nil {\n\t\tdst.Resources = new(Resources)\n\t}\n\tdst.Resources.Merge(src.Resources)\n}", "func (d *Decoder) reset() {\n\tif unread := len(d.buf) - d.r1; unread == 0 {\n\t\t// No bytes in the buffer, so we can start from the beginning without\n\t\t// needing to copy anything (and get better cache behaviour too).\n\t\td.buf = d.buf[:0]\n\t\td.r1 = 0\n\t} else if !d.complete && unread <= maxSlide {\n\t\t// Slide the unread portion of the buffer to the\n\t\t// start so that when we read more data,\n\t\t// there's less chance that we'll need to grow the buffer.\n\t\tcopy(d.buf, d.buf[d.r1:])\n\t\td.r1 = 0\n\t\td.buf = d.buf[:unread]\n\t}\n\td.r0 = d.r1\n\td.escBuf = d.escBuf[:0]\n}", "func (cs *UnsafeCounterIndex) Flush(s Counters) Counters {\n\ts = append(s, cs.counters...)\n\tcs.counters.Zero()\n\treturn s\n}", "func (r *BasicResampler) Reset() {\n\tr.sampleAggregates = r.sampleAggregates[:0]\n}", "func (z *Int) Clear() *Int {\n\tz[3], z[2], z[1], z[0] = 0, 0, 0, 0\n\treturn z\n}", "func (c *Counter) Reset() {\n\tc.bits.Reset()\n}", "func (s *SharedMemorySegment) Clear() {\n\tfor i := 0; i < len(s.data); i++ {\n\t\ts.data[i] = 0\n\t}\n}", "func (c *CTR) Reset() {\n\tc.blocks = 0\n\tc.ks = nil\n}", "func (b *BaseImpl) Copy(src Base, srcOff, size, dstOff, extend int) {\n\n\t// src, ok := osrc.(*BaseImpl)\n\t// if !ok {\n\t// \tlog.Log(LOG_WARN, log.Printf(\"BaseImpl.Copy() src is only BaseImpl\"))\n\n\t// \treturn\n\t// }\n\n\tif len(b.bytes) > dstOff {\n\t\tdiff := Diff{Offset: dstOff, bytes: b.bytes[dstOff:]}\n\t\tb.Diffs = append(b.Diffs, diff)\n\t\t//b.bytes = b.bytes[:dstOff]\n\t}\n\n\tfor i, diff := range b.Diffs {\n\t\tif diff.Offset >= dstOff {\n\t\t\tdiff.Offset += extend\n\t\t}\n\t\tb.Diffs[i] = diff\n\t}\n\n\tif len(src.R(0)) > srcOff {\n\t\tnSize := len(src.R(0)[srcOff:])\n\t\tif nSize > size {\n\t\t\tnSize = size\n\t\t}\n\n\t\tdiff := Diff{Offset: dstOff, bytes: src.R(0)[srcOff : srcOff+nSize]}\n\t\tb.Diffs = append(b.Diffs, diff)\n\t}\n\tfor _, diff := range src.GetDiffs() {\n\t\tif diff.Offset >= srcOff {\n\t\t\tnDiff := diff\n\t\t\tnDiff.Offset -= srcOff\n\t\t\tnDiff.Offset += dstOff\n\t\t\tb.Diffs = append(b.Diffs, nDiff)\n\t\t}\n\t}\n\treturn\n}", "func (s *Stream) Reset() {\n\ts.stream.reset()\n\ts.b = s.b[:0]\n}", "func (w *buffer) reset() {\n\tfor i := range (*w)[:cap(*w)] {\n\t\t(*w)[i] = 0\n\t}\n\t*w = (*w)[:0]\n}", "func (g *GaugeInt64) Clear() {\n\tatomic.StoreInt64(&g.val, 0)\n}", "func (r *PendingPodsRecorder) Clear() {\n\tr.recorder.Set(float64(0))\n}", "func (ingest *Ingestion) Clear(start int64, end int64) error {\n\tclear := ingest.DB.DeleteRange\n\n\terr := clear(start, end, \"history_effects\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operation_participants\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_operations\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transaction_participants\", \"history_transaction_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_transactions\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = clear(start, end, \"history_ledgers\", \"id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = clear(start, end, \"history_trades\", \"history_operation_id\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *RunningStats) Clear() {\n\tr.n = 0\n\tr.m1 = 0.0\n\tr.m2 = 0.0\n\tr.m3 = 0.0\n\tr.m4 = 0.0\n}", "func (c *SyncCollector) Clear() {\n\tfor k := range c.c {\n\t\tc.rw.Lock()\n\t\tdelete(c.c, k)\n\t\tc.rw.Unlock()\n\t}\n}", "func (dc *DatadogCollector) Reset() {}", "func (ss *SequenceStats) Clear() {\n\tss.Min.Clear()\n\tss.Max.Clear()\n\tss.Variance.Reset()\n}", "func (cs *CounterIndex) Flush(s []Counter) []Counter {\n\tcs.mu.RLock()\n\tsrc := cs.index.counters\n\tfor i := range src {\n\t\tc := &src[i]\n\t\tn := atomic.SwapInt64(&c.Count, 0)\n\t\tif n != 0 {\n\t\t\ts = append(s, Counter{n, c.Values})\n\t\t}\n\t}\n\tcs.mu.RUnlock()\n\treturn s\n}", "func (tb *TransactionBuffer) Clear() {\n\ttb.mux.Lock()\n\ttb.Buffer = make([]TxPublish, 0)\n\ttb.mux.Unlock()\n}", "func (c *Conn) Clear() {\n\tc.statsMut.Lock()\n\tdefer c.statsMut.Unlock()\n\n\tc.commands = []*Cmd{}\n\tc.queue = []queueElement{}\n\tc.replies = []replyElement{}\n\tc.stats = make(map[cmdHash]int)\n}", "func (v *Int32Vec) Clear() {\n\tv.Truncate(0)\n}", "func (h *MapInt16ToInt16) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (w *Writer) Reset() {\n\tw.buf = w.buf[:0]\n}", "func (c *PNGCopyCounters) Collect() []byte {\n\tif c.Created {\n\t\tb, _ := json.Marshal(ByteCopyCountersOut{\n\t\t\tCopiedBytes: c.CopiedBytes,\n\t\t\tData: c.Buffer.Bytes(),\n\t\t})\n\t\treturn b\n\t} else {\n\t\tb, _ := json.Marshal(ByteCopyCountersOut{\n\t\t\tCopiedBytes: c.CopiedBytes,\n\t\t\tData: nil,\n\t\t})\n\t\treturn b\n\t}\n\n}", "func (z *Writer) Reset(w io.Writer) {\n\tn := cap(z.c)\n\t_ = z.close()\n\tz.freeBuffers()\n\tz.Header.Reset()\n\tz.dst = w\n\tz.checksum.Reset()\n\tz.idx = 0\n\tz.err = nil\n\t// reset hashtable to ensure deterministic output.\n\tfor i := range z.hashtable {\n\t\tz.hashtable[i] = 0\n\t}\n\tz.WithConcurrency(n)\n}", "func (s *StreamPack) Flush() {\n\ts.Buffer.Clear()\n}", "func TestMerge_Empty(t *testing.T) {\n\tpncounter1 := PNCounter{}\n\tpncounter2 := PNCounter{}\n\tpncounter3 := PNCounter{}\n\n\tpncounterExpected := PNCounter{}\n\tpncounterActual := Merge(pncounter1, pncounter2, pncounter3)\n\n\tcountExpected := 0\n\tcountActual := pncounterActual.GetTotal()\n\n\tassert.Equal(t, pncounterExpected, pncounterActual)\n\tassert.Equal(t, countExpected, countActual)\n\n\tpncounter = pncounter.Clear(testNode)\n}", "func (mg *MoveGen) Clear() {\n\tmg.index = 0\n}", "func (e *dataUsageEntry) merge(other dataUsageEntry) {\n\te.Objects += other.Objects\n\te.Versions += other.Versions\n\te.Size += other.Size\n\tors := other.ReplicationStats\n\tempty := replicationStats{}\n\tif ors != nil && *ors != empty {\n\t\tif e.ReplicationStats == nil {\n\t\t\te.ReplicationStats = &replicationStats{}\n\t\t}\n\t\te.ReplicationStats.PendingSize += other.ReplicationStats.PendingSize\n\t\te.ReplicationStats.FailedSize += other.ReplicationStats.FailedSize\n\t\te.ReplicationStats.ReplicatedSize += other.ReplicationStats.ReplicatedSize\n\t\te.ReplicationStats.ReplicaSize += other.ReplicationStats.ReplicaSize\n\t\te.ReplicationStats.PendingCount += other.ReplicationStats.PendingCount\n\t\te.ReplicationStats.FailedCount += other.ReplicationStats.FailedCount\n\n\t}\n\n\tfor i, v := range other.ObjSizes[:] {\n\t\te.ObjSizes[i] += v\n\t}\n}" ]
[ "0.59546256", "0.5845583", "0.5342968", "0.5308023", "0.53014207", "0.53014207", "0.5278379", "0.5278379", "0.52758855", "0.52296466", "0.5226735", "0.5226296", "0.5215459", "0.5205346", "0.51741487", "0.5115584", "0.5103847", "0.5100748", "0.5090523", "0.50738835", "0.50632274", "0.5062689", "0.50294954", "0.50279564", "0.50134695", "0.50134695", "0.50125813", "0.49859613", "0.49845585", "0.49679592", "0.49488235", "0.49455288", "0.4933328", "0.49239567", "0.48916483", "0.4885387", "0.4870685", "0.48681772", "0.48661384", "0.48630664", "0.48570904", "0.48465854", "0.48397672", "0.4830675", "0.48297283", "0.48268476", "0.48224637", "0.48184592", "0.48139423", "0.48122603", "0.48048744", "0.47965208", "0.47896034", "0.47863722", "0.47861892", "0.47681537", "0.47609347", "0.47595498", "0.475602", "0.47539443", "0.4747079", "0.47349676", "0.47238412", "0.47142515", "0.47089878", "0.4707139", "0.4701546", "0.47002736", "0.4697228", "0.46941382", "0.46713313", "0.46648204", "0.46599424", "0.46525753", "0.46521726", "0.46483645", "0.46444276", "0.46376365", "0.4635913", "0.4633824", "0.4632837", "0.46274716", "0.46261778", "0.46245605", "0.46163484", "0.46100548", "0.46086097", "0.46074685", "0.45958692", "0.45954072", "0.4594974", "0.45874086", "0.45823044", "0.45788234", "0.45772552", "0.45762023", "0.45667407", "0.45574948", "0.4555309", "0.45537636" ]
0.6706543
0
NewHistogram creates a new histogram (sets up the buckets). Divider value can not be zero, otherwise returns zero
func NewHistogram(Offset float64, Divider float64) *Histogram { h := new(Histogram) h.Offset = Offset if Divider == 0 { return nil } h.Divider = Divider h.Hdata = make([]int32, numBuckets) return h }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewHistogram(opts HistogramOptions) *Histogram {\n\tif opts.NumBuckets == 0 {\n\t\topts.NumBuckets = 32\n\t}\n\tif opts.BaseBucketSize == 0.0 {\n\t\topts.BaseBucketSize = 1.0\n\t}\n\th := Histogram{\n\t\topts: opts,\n\t\tbuckets: make([]bucketInternal, opts.NumBuckets),\n\t\tcount: newCounter(),\n\t\tsum: newCounter(),\n\t\tsumOfSquares: newCounter(),\n\t\ttracker: newTracker(),\n\n\t\tlogBaseBucketSize: math.Log(opts.BaseBucketSize),\n\t\toneOverLogOnePlusGrowthFactor: 1 / math.Log(1+opts.GrowthFactor),\n\t}\n\tm := 1.0 + opts.GrowthFactor\n\tdelta := opts.BaseBucketSize\n\th.buckets[0].lowBound = float64(opts.MinValue)\n\th.buckets[0].count = newCounter()\n\tfor i := 1; i < opts.NumBuckets; i++ {\n\t\th.buckets[i].lowBound = float64(opts.MinValue) + delta\n\t\th.buckets[i].count = newCounter()\n\t\tdelta = delta * m\n\t}\n\treturn &h\n}", "func NewHistogram() *Histogram {\n\treturn &Histogram{make([]int, HistogramSize), &sync.Mutex{}}\n}", "func NewHistogram(name, help string, cutoffs []int64) *Histogram {\n\tlabels := make([]string, len(cutoffs)+1)\n\tfor i, v := range cutoffs {\n\t\tlabels[i] = fmt.Sprintf(\"%d\", v)\n\t}\n\tlabels[len(labels)-1] = \"inf\"\n\treturn NewGenericHistogram(name, help, cutoffs, labels, \"Count\", \"Total\")\n}", "func NewHistogram(labels map[string]string) *Histogram {\n\treturn &Histogram{\n\t\tLabels: labels,\n\t\tBuckets: make(map[string]int),\n\t}\n}", "func NewHistogram(nanoseconds []float64, opts *HistogramOptions) *Histogram {\n\tif opts.BinCount <= 0 {\n\t\tpanic(\"binCount must be larger than 0\")\n\t}\n\n\thist := &Histogram{}\n\thist.Width = 40\n\thist.Bins = make([]HistogramBin, opts.BinCount)\n\tif len(nanoseconds) == 0 {\n\t\treturn hist\n\t}\n\n\tnanoseconds = append(nanoseconds[:0:0], nanoseconds...)\n\tsort.Float64s(nanoseconds)\n\n\thist.Minimum = nanoseconds[0]\n\thist.Maximum = nanoseconds[len(nanoseconds)-1]\n\n\thist.Average = float64(0)\n\tfor _, x := range nanoseconds {\n\t\thist.Average += x\n\t}\n\thist.Average /= float64(len(nanoseconds))\n\n\tp := func(p float64) float64 {\n\t\ti := int(math.Round(p * float64(len(nanoseconds))))\n\t\tif i < 0 {\n\t\t\ti = 0\n\t\t}\n\t\tif i >= len(nanoseconds) {\n\t\t\ti = len(nanoseconds) - 1\n\t\t}\n\t\treturn nanoseconds[i]\n\t}\n\n\thist.P50, hist.P90, hist.P99, hist.P999, hist.P9999 = p(0.50), p(0.90), p(0.99), p(0.999), p(0.9999)\n\n\tclampMaximum := hist.Maximum\n\tif opts.ClampPercentile > 0 {\n\t\tclampMaximum = p(opts.ClampPercentile)\n\t}\n\tif opts.ClampMaximum > 0 {\n\t\tclampMaximum = opts.ClampMaximum\n\t}\n\n\tvar minimum, spacing float64\n\n\tif opts.NiceRange {\n\t\tminimum, spacing = calculateNiceSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t} else {\n\t\tminimum, spacing = calculateSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t}\n\n\tfor i := range hist.Bins {\n\t\thist.Bins[i].Start = spacing*float64(i) + minimum\n\t}\n\thist.Bins[0].Start = hist.Minimum\n\n\tfor _, x := range nanoseconds {\n\t\tk := int(float64(x-minimum) / spacing)\n\t\tif k < 0 {\n\t\t\tk = 0\n\t\t}\n\t\tif k >= opts.BinCount {\n\t\t\tk = opts.BinCount - 1\n\t\t\thist.Bins[k].andAbove = true\n\t\t}\n\t\thist.Bins[k].Count++\n\t}\n\n\tmaxBin := 0\n\tfor _, bin := range hist.Bins {\n\t\tif bin.Count > maxBin {\n\t\t\tmaxBin = bin.Count\n\t\t}\n\t}\n\n\tfor k := range hist.Bins {\n\t\tbin := &hist.Bins[k]\n\t\tbin.Width = float64(bin.Count) / float64(maxBin)\n\t}\n\n\treturn hist\n}", "func (c *Aggregator) Histogram() (aggregation.Buckets, error) {\n\treturn aggregation.Buckets{\n\t\tBoundaries: c.boundaries,\n\t\tCounts: c.state.bucketCounts,\n\t}, nil\n}", "func NewHistogram(w io.Writer, key string, interval time.Duration) metrics.Histogram {\n\th := make(chan string)\n\tgo fwd(w, key, interval, h)\n\treturn statsdHistogram(h)\n}", "func NewHistogram(subsystem, name, help string, labels []string, buckets []float64) *prometheus.HistogramVec {\n\treturn promauto.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t\tBuckets: buckets,\n\t\t},\n\t\tlabels,\n\t)\n}", "func newBatchHistogram(desc *Desc, buckets []float64, hasSum bool) *batchHistogram {\n\t// We need to remove -Inf values. runtime/metrics keeps them around.\n\t// But -Inf bucket should not be allowed for prometheus histograms.\n\tif buckets[0] == math.Inf(-1) {\n\t\tbuckets = buckets[1:]\n\t}\n\th := &batchHistogram{\n\t\tdesc: desc,\n\t\tbuckets: buckets,\n\t\t// Because buckets follows runtime/metrics conventions, there's\n\t\t// 1 more value in the buckets list than there are buckets represented,\n\t\t// because in runtime/metrics, the bucket values represent *boundaries*,\n\t\t// and non-Inf boundaries are inclusive lower bounds for that bucket.\n\t\tcounts: make([]uint64, len(buckets)-1),\n\t\thasSum: hasSum,\n\t}\n\th.init(h)\n\treturn h\n}", "func NewGenericHistogram(name, help string, cutoffs []int64, labels []string, countLabel, totalLabel string) *Histogram {\n\tif len(cutoffs) != len(labels)-1 {\n\t\tpanic(\"mismatched cutoff and label lengths\")\n\t}\n\th := &Histogram{\n\t\tname: name,\n\t\thelp: help,\n\t\tcutoffs: cutoffs,\n\t\tlabels: labels,\n\t\tcountLabel: countLabel,\n\t\ttotalLabel: totalLabel,\n\t\tbuckets: make([]atomic.Int64, len(labels)),\n\t}\n\tif name != \"\" {\n\t\tpublish(name, h)\n\t}\n\treturn h\n}", "func (e *Exporter) NewHistogram(name, help string, cutoffs []int64) *stats.Histogram {\n\tif e.name == \"\" || name == \"\" {\n\t\tv := stats.NewHistogram(name, help, cutoffs)\n\t\taddUnnamedExport(name, v)\n\t\treturn v\n\t}\n\thist := stats.NewHistogram(\"\", help, cutoffs)\n\te.addToOtherVars(name, hist)\n\treturn hist\n}", "func (h *Histogram) filterHistogram(newBuckets []Bucket) *Histogram {\n\tcheckBucketsValid(newBuckets)\n\n\ttotal := int64(0)\n\tfor _, b := range newBuckets {\n\t\ttotal += b.NumEq + b.NumRange\n\t}\n\n\tif total == 0 {\n\t\treturn &Histogram{}\n\t}\n\n\tselectivity := float64(total) / float64(h.RowCount)\n\n\t// Estimate the new DistinctCount based on the selectivity of this filter.\n\t// todo(rytaft): this could be more precise if we take into account the\n\t// null count of the original histogram. This could also be more precise for\n\t// the operators =, !=, in, and not in, since we know how these operators\n\t// should affect the distinct count.\n\tdistinctCount := int64(float64(h.DistinctCount) * selectivity)\n\tif distinctCount == 0 {\n\t\t// There must be at least one distinct value since RowCount > 0.\n\t\tdistinctCount++\n\t}\n\n\treturn &Histogram{\n\t\tRowCount: total,\n\t\tDistinctCount: distinctCount,\n\n\t\t// All the returned rows will be non-null for this column.\n\t\tNullCount: 0,\n\t\tBuckets: newBuckets,\n\t}\n}", "func (bench *Stopwatch) Histogram(binCount int) *Histogram {\n\tbench.mustBeCompleted()\n\n\topts := defaultOptions\n\topts.BinCount = binCount\n\n\treturn NewDurationHistogram(bench.Durations(), &opts)\n}", "func NewHistogram(config HistogramConfig) (objectspec.InstrumentorHistogram, error) {\n\tnewHistogram := &histogram{\n\t\tHistogramConfig: config,\n\t}\n\n\tif len(newHistogram.Buckets) == 0 {\n\t\treturn nil, maskAnyf(invalidConfigError, \"buckets must not be empty\")\n\t}\n\tif newHistogram.Help == \"\" {\n\t\treturn nil, maskAnyf(invalidConfigError, \"help must not be empty\")\n\t}\n\tif newHistogram.Name == \"\" {\n\t\treturn nil, maskAnyf(invalidConfigError, \"name must not be empty\")\n\t}\n\n\tnewHistogram.ClientHistogram = prometheusclient.NewHistogram(prometheusclient.HistogramOpts{\n\t\tBuckets: newHistogram.Buckets,\n\t\tHelp: newHistogram.Help,\n\t\tName: newHistogram.Name,\n\t})\n\n\treturn newHistogram, nil\n}", "func NewHistogram(name string, options ...Option) Histogram {\n\treturn newHistogram(name, options...)\n}", "func (p *influxProvider) NewHistogram(name string, buckets int) metrics.Histogram {\n\treturn p.in.NewHistogram(name)\n}", "func NewHistogramBucket() HistogramBucket {\n\torig := (*otlpmetrics.HistogramDataPoint_Bucket)(nil)\n\treturn newHistogramBucket(&orig)\n}", "func newBuckets(c Config, end time.Time) buckets {\n\tn := c.len()\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tout := make(buckets, n+1)\n\n\tfor i := n; i >= 1; i-- {\n\t\tw := c.MinInterval()\n\n\t\t// c is a copy of the config,\n\t\t// so we can decrement values without\n\t\t// a problem.\n\t\tswitch w {\n\t\tcase Hour:\n\t\t\tc.Hourly--\n\t\tcase Day:\n\t\t\tc.Daily--\n\t\tcase Week:\n\t\t\tc.Weekly--\n\t\tcase Month:\n\t\t\tc.Monthly--\n\t\tcase Year:\n\t\t\tc.Yearly--\n\t\tcase -1:\n\t\t\tpanic(\"ran out of buckets\")\n\t\tdefault:\n\t\t\tpanic(\"unknown interval\")\n\t\t}\n\n\t\tout[i] = &bucket{\n\t\t\tWidth: w,\n\t\t\tEnd: end,\n\t\t}\n\t\tend = end.Add(-w)\n\t}\n\n\t// Catchall bucket.\n\tout[0] = &bucket{\n\t\tEnd: end,\n\t\tWidth: 0,\n\t}\n\n\treturn out\n}", "func newRuneHistogram(tracking, init []rune) *runeHistogram {\n\th := &runeHistogram{set: make(map[rune]int)}\n\tfor _, ch := range tracking {\n\t\th.set[ch] = 0\n\t}\n\tif len(init) > 0 {\n\t\tfor _, ch := range init {\n\t\t\tif _, ok := h.set[ch]; ok {\n\t\t\t\th.set[ch]++\n\t\t\t}\n\t\t}\n\t\th.refreshValidity()\n\t}\n\treturn h\n}", "func createHistogram(data []float64, n int) {\n\tp, err := plot.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tp.Add(plotter.NewGrid())\n\thistdata := valuer{data}\n\tp.Add(plotter.NewHist(histdata, n))\n\tp.X.Label.Text = \"time / ps\"\n\tp.Y.Label.Text = \"frequency\"\n\tp.Title.Text = fmt.Sprintf(\"Frequency of lifetime data from lifetime.txt. %v bins.\", n)\n\n\tif err := p.Save(5, 5, fmt.Sprintf(\"out/Histogram with %v bins.png\", n)); err != nil {\n\t\tpanic(err)\n\t}\n}", "func NewHistogramBucketSlice() HistogramBucketSlice {\n\torig := []*otlpmetrics.HistogramDataPoint_Bucket(nil)\n\treturn HistogramBucketSlice{&orig}\n}", "func newBuckets(n int) *buckets {\n\treturn &buckets{counts: make([]uint64, n)}\n}", "func (NoopProvider) Histogram(_ string, _ Buckets, _ ...string) Histogram {\n\treturn noopInstrument{}\n}", "func (s *fseEncoder) Histogram() *[256]uint32 {\n\treturn &s.count\n}", "func (p *Provider) NewHistogram(name string, _ int) metrics.Histogram {\n\treturn p.newHistogram(name)\n}", "func (h *Histogram) Clone() *Histogram {\n\tcopy := NewHistogram(h.Offset, h.Divider)\n\tcopy.CopyFrom(h)\n\treturn copy\n}", "func New(cnt int, desc *metric.Descriptor, opts ...Option) []Aggregator {\n\tvar cfg config\n\n\tif desc.NumberKind() == number.Int64Kind {\n\t\tcfg.explicitBoundaries = defaultInt64ExplicitBoundaries\n\t} else {\n\t\tcfg.explicitBoundaries = defaultFloat64ExplicitBoundaries\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(&cfg)\n\t}\n\n\taggs := make([]Aggregator, cnt)\n\n\t// Boundaries MUST be ordered otherwise the histogram could not\n\t// be properly computed.\n\tsortedBoundaries := make([]float64, len(cfg.explicitBoundaries))\n\n\tcopy(sortedBoundaries, cfg.explicitBoundaries)\n\tsort.Float64s(sortedBoundaries)\n\n\tfor i := range aggs {\n\t\taggs[i] = Aggregator{\n\t\t\tkind: desc.NumberKind(),\n\t\t\tboundaries: sortedBoundaries,\n\t\t}\n\t\taggs[i].state = aggs[i].newState()\n\t}\n\treturn aggs\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}", "func (bench *Stopwatch) HistogramClamp(binCount int, min, max time.Duration) *Histogram {\n\tbench.mustBeCompleted()\n\n\tdurations := make([]time.Duration, 0, len(bench.spans))\n\tfor _, span := range bench.spans {\n\t\tduration := span.Duration()\n\t\tif duration < min {\n\t\t\tdurations = append(durations, min)\n\t\t} else {\n\t\t\tdurations = append(durations, duration)\n\t\t}\n\t}\n\n\topts := defaultOptions\n\topts.BinCount = binCount\n\topts.ClampMaximum = float64(max.Nanoseconds())\n\topts.ClampPercentile = 0\n\n\treturn NewDurationHistogram(durations, &opts)\n}", "func NewSimpleHistogram(subsystem, name, help string, buckets []float64) SimpleHistogram {\n\treturn NewSimpleHistogramWithOpts(subsystem, name, help, buckets, DefaultOptions)\n}", "func (it *emptyIterator) AtHistogram() (int64, *histogram.Histogram) { return 0, nil }", "func (ms HistogramBucket) InitEmpty() {\n\t*ms.orig = &otlpmetrics.HistogramDataPoint_Bucket{}\n}", "func Merge(h1 *Histogram, h2 *Histogram) *Histogram {\n\tdivider := h1.Divider\n\toffset := h1.Offset\n\tif h2.Divider > h1.Divider {\n\t\tdivider = h2.Divider\n\t}\n\tif h2.Offset < h1.Offset {\n\t\toffset = h2.Offset\n\t}\n\tnewH := NewHistogram(offset, divider)\n\tnewH.Transfer(h1)\n\tnewH.Transfer(h2)\n\treturn newH\n}", "func (c *Client) Histogram(name string, value int) error {\n\treturn c.DataDog.Histogram(name, float64(value), nil, 1)\n}", "func (m *Metrics) Histogram(name, help string, buckets []float64) prometheus.Histogram {\n\thistogram := prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tNamespace: m.config.Namespace,\n\t\tName: name,\n\t\tHelp: help,\n\t\tBuckets: buckets,\n\t})\n\n\tprometheus.MustRegister(histogram)\n\n\treturn histogram\n}", "func (c *Client) Histogram(stat string, value int, rate float64) error {\n\treturn c.send(stat, rate, \"%d|ms\", value)\n}", "func (datadog *Datadog) Histogram(name string, startTime time.Time, tags []string) error {\n\telapsedTime := time.Since(startTime).Seconds() * 1000\n\terr := datadog.client.Histogram(name, elapsedTime, tags, float64(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ParseHistogram(scale string, histo *dto.Histogram) (buckets HistogramBuckets, err error) {\n\tif histo == nil {\n\t\treturn nil, errors.New(\"nil Histogram\")\n\t}\n\n\ttotal := *histo.SampleCount\n\tn := len(histo.Bucket)\n\n\tbuckets = make(HistogramBuckets, n+1)\n\tbuckets[n] = HistogramBucket{\n\t\tScale: scale,\n\t\tUpperBound: math.MaxFloat64,\n\t\tCount: total,\n\t}\n\tfor idx, bv := range histo.Bucket {\n\t\tbuckets[idx] = HistogramBucket{\n\t\t\tScale: scale,\n\t\t\tUpperBound: *bv.UpperBound,\n\t\t\tCount: *bv.CumulativeCount,\n\t\t}\n\t}\n\tfor idx := n; idx > 0; idx-- { // start from last, end at second to last\n\t\t// convert cumulative count to per-bucket count\n\t\tbuckets[idx].Count = buckets[idx].Count - buckets[idx-1].Count\n\t\t// use previous bucket upper bound as lower bound\n\t\tbuckets[idx].LowerBound = buckets[idx-1].UpperBound\n\t}\n\n\tsort.Sort(HistogramBuckets(buckets))\n\treturn buckets, nil\n}", "func (p *Provider) Histogram(name string, value float64, tags map[string]string) error {\n\treturn p.client.Histogram(name, value, p.formatTags(tags), p.rate)\n}", "func init() {\n\tval2Bucket = make([]int, maxArrayValue)\n\tmaxArrayValueIndex = -1\n\tfor i, value := range histogramBucketValues {\n\t\tif value == maxArrayValue {\n\t\t\tmaxArrayValueIndex = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif maxArrayValueIndex == -1 {\n\t\tlog.Fatalf(\"Bug boundary maxArrayValue=%d not found in bucket list %v\", maxArrayValue, histogramBucketValues)\n\t}\n\tidx := 0\n\tfor i := int32(0); i < maxArrayValue; i++ {\n\t\tif i >= histogramBucketValues[idx] {\n\t\t\tidx++\n\t\t}\n\t\tval2Bucket[i] = idx\n\t}\n\t// coding bug detection (aka impossible if it works once) until 1000\n\tif idx != maxArrayValueIndex {\n\t\tlog.Fatalf(\"Bug in creating histogram index idx %d vs index %d up to %d\", idx, int(maxArrayValue), maxArrayValue)\n\t}\n}", "func (c *LoggerClient) Histogram(name string, value float64) {\n\tc.print(\"Histogram\", name, value, value)\n}", "func NewBucket(tokens uint64) *Bucket {\n\treturn &Bucket{Added: float64(tokens)}\n}", "func (_m *Reporter) Histogram(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 (c *StatsClient) Histogram(name string, value float64) {\n\tif err := c.client.Histogram(name, value, c.tags, Rate); err != nil {\n\t\tc.logger().Printf(\"datadog.StatsClient.Histogram error: %s\", err)\n\t}\n}", "func (h *Histogram) Export() *HistogramData {\n\tvar res HistogramData\n\tres.Count = h.Counter.Count\n\tres.Min = h.Counter.Min\n\tres.Max = h.Counter.Max\n\tres.Sum = h.Counter.Sum\n\tres.Avg = h.Counter.Avg()\n\tres.StdDev = h.Counter.StdDev()\n\tmultiplier := h.Divider\n\toffset := h.Offset\n\t// calculate the last bucket index\n\tlastIdx := -1\n\tfor i := numBuckets - 1; i >= 0; i-- {\n\t\tif h.Hdata[i] > 0 {\n\t\t\tlastIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastIdx == -1 {\n\t\treturn &res\n\t}\n\n\t// previous bucket value:\n\tprev := histogramBucketValues[0]\n\tvar total int64\n\tctrTotal := float64(h.Count)\n\t// export the data of each bucket of the histogram\n\tfor i := 0; i <= lastIdx; i++ {\n\t\tif h.Hdata[i] == 0 {\n\t\t\t// empty bucket: skip it but update prev which is needed for next iter\n\t\t\tif i < numValues {\n\t\t\t\tprev = histogramBucketValues[i]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tvar b Bucket\n\t\ttotal += int64(h.Hdata[i])\n\t\tif len(res.Data) == 0 {\n\t\t\t// First entry, start is min\n\t\t\tb.Start = h.Min\n\t\t} else {\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t}\n\t\tb.Percent = 100. * float64(total) / ctrTotal\n\t\tif i < numValues {\n\t\t\tcur := histogramBucketValues[i]\n\t\t\tb.End = multiplier*float64(cur) + offset\n\t\t\tprev = cur\n\t\t} else {\n\t\t\t// Last Entry\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t\tb.End = h.Max\n\t\t}\n\t\tb.Count = int64(h.Hdata[i])\n\t\tres.Data = append(res.Data, b)\n\t}\n\tres.Data[len(res.Data)-1].End = h.Max\n\treturn &res\n}", "func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: sample.H.Count,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func NewSplitter(f func([]byte, uint) error) *Splitter {\n\trs := buzhash32.New()\n\tvar zeroes [windowSize]byte\n\trs.Write(zeroes[:]) // initialize the rolling checksum window\n\n\treturn &Splitter{f: f, rs: rs}\n}", "func (r *JobsService) Histogram(gethistogramrequest *GetHistogramRequest) *JobsHistogramCall {\n\tc := &JobsHistogramCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.gethistogramrequest = gethistogramrequest\n\treturn c\n}", "func NewMultiHistogram(name string, histograms ...Histogram) Histogram {\n\treturn &multiHistogram{\n\t\tname: name,\n\t\ta: histograms,\n\t}\n}", "func (d TestSink) Histogram(c *telemetry.Context, stat string, value float64) {\n\td[stat] = TestMetric{\"Histogram\", value, c.Tags()}\n}", "func (ac *Accumulator) AddHistogram(measurement string, fields map[string]interface{},\n\ttags map[string]string, t ...time.Time) {\n\t// as of right now metric always returns a nil error\n\tm, _ := metric.New(measurement, tags, fields, getTime(t), telegraf.Histogram)\n\tac.AddMetric(m)\n}", "func newHashRange(start common.Hash, num uint64) *hashRange {\n\tleft := new(big.Int).Sub(hashSpace, start.Big())\n\tstep := new(big.Int).Div(\n\t\tnew(big.Int).Add(left, new(big.Int).SetUint64(num-1)),\n\t\tnew(big.Int).SetUint64(num),\n\t)\n\tstep256 := new(uint256.Int)\n\tstep256.SetFromBig(step)\n\n\treturn &hashRange{\n\t\tcurrent: new(uint256.Int).SetBytes32(start[:]),\n\t\tstep: step256,\n\t}\n}", "func (r *Recorder) Histogram(ctx context.Context, tconn *chrome.TestConn) ([]*Histogram, error) {\n\tnames := r.names()\n\n\ts, err := GetHistograms(ctx, tconn, names)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get snapshot\")\n\t}\n\n\treturn DiffHistograms(r.snapshot, s)\n}", "func getHistogram(src [][3]int, size float64, pixels *[HistSize][3]float64, hist *[HistSize]float64) {\n\tvar ind, r, g, b, i int\n\tvar inr, ing, inb int\n\n\tfor i = range src {\n\t\tr = src[i][0]\n\t\tg = src[i][1]\n\t\tb = src[i][2]\n\n\t\tinr = r >> Shift\n\t\ting = g >> Shift\n\t\tinb = b >> Shift\n\n\t\tind = (inr << (2 * HistBits)) + (ing << HistBits) + inb\n\t\tpixels[ind][0], pixels[ind][1], pixels[ind][2] = float64(r), float64(g), float64(b)\n\t\thist[ind]++\n\t}\n\n\t// normalize weight by the number of pixels in the image\n\tfor i = 0; i < HistSize; i++ {\n\t\thist[i] /= size\n\t}\n}", "func UpdateHistogram(h *Histogram, feedback *QueryFeedback) *Histogram {\n\tbuckets, isNewBuckets, totalCount := splitBuckets(h, feedback)\n\tbuckets = mergeBuckets(buckets, isNewBuckets, float64(totalCount))\n\thist := buildNewHistogram(h, buckets)\n\t// Update the NDV of primary key column.\n\tif feedback.Tp == PkType {\n\t\thist.NDV = int64(hist.TotalRowCount())\n\t}\n\treturn hist\n}", "func (m *Metrics) Histogram(key string) *metrics.Histogram {\n\tm.Lock()\n\tdefer m.Unlock()\n\thist, ok := m.histograms[key]\n\tif !ok {\n\t\thist = metrics.NewHistogram(key, 0, 1e8, 5)\n\t\tm.histograms[key] = hist\n\t}\n\treturn hist\n}", "func mockStatsHistogram(id int64, values []types.Datum, repeat int64, tp *types.FieldType) *statistics.Histogram {\n\tndv := len(values)\n\thistogram := statistics.NewHistogram(id, int64(ndv), 0, 0, tp, ndv, 0)\n\tfor i := 0; i < ndv; i++ {\n\t\thistogram.AppendBucket(&values[i], &values[i], repeat*int64(i+1), repeat)\n\t}\n\treturn histogram\n}", "func Histogram(name string, requestTime float64, tags []string, rate float64) {\n\tif ddog == nil {\n\t\tlog.Error(\"datadog client is not initialized\")\n\t\treturn\n\t}\n\n\terr := ddog.Client.Histogram(name, requestTime, tags, rate)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"name\": name,\n\t\t}).Error(\"Failed to send histogram data to datadog\")\n\t}\n}", "func New() *HashTable {\n\tt := &HashTable{}\n\tfor i := range t.array {\n\t\tt.array[i] = &bucket{}\n\t}\n\treturn t\n}", "func (c *Prometheus) getHistogram(name string, labels ...map[string]string) *prometheus.HistogramVec {\n\tvar keys []string\n\tvar values []string\n\n\tfor key, value := range labels[0] {\n\t\tkeys = append(keys, key)\n\t\tvalues = append(values, value)\n\t}\n\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tif _, ok := c.histograms[name]; !ok {\n\t\tc.histograms[name] = prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\t\tName: name + \"_seconds\",\n\t\t\tHelp: \" \",\n\t\t}, keys)\n\t\tprometheus.Register(c.histograms[name])\n\t}\n\treturn c.histograms[name]\n}", "func (cm *customMetrics) AddHistogram(\n\tnamespace, subsystem, name, help, internalKey string,\n\tconstLabels prometheus.Labels, buckets []float64) {\n\n\tcm.histograms[internalKey] = promauto.NewHistogram(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t\tHelp: help,\n\t\tConstLabels: constLabels,\n\t\tBuckets: buckets,\n\t})\n}", "func NewTable(desiredBucketCount int) *hashtable {\n\th := &hashtable{\n\t\tbucketcount: desiredBucketCount,\n\t\tbuckets: make([]*CacheItem, desiredBucketCount),\n\t}\n\treturn h\n}", "func histHelper(expFormat string, labels ...interface{}) *metrics.Histogram {\n\treturn metrics.GetOrCreateHistogram(fmt.Sprintf(expFormat, labels...))\n}", "func (h *Histogram) Diff(old *Histogram) (*Histogram, error) {\n\tif h.Name != old.Name {\n\t\treturn nil, errors.Errorf(\"unmatched histogram, %s vs %s\", h.Name, old.Name)\n\t}\n\tif len(old.Buckets) > len(h.Buckets) {\n\t\treturn nil, errors.Errorf(\"old histogram has %d bucket(s), new only has %d\", len(old.Buckets), len(h.Buckets))\n\t}\n\n\tdiff := &Histogram{Name: h.Name, Sum: h.Sum - old.Sum}\n\toi := 0\n\tfor _, hb := range h.Buckets {\n\t\t// If we've already looked at all of the old buckets, copy the new bucket over.\n\t\tif oi >= len(old.Buckets) {\n\t\t\tdiff.Buckets = append(diff.Buckets, hb)\n\t\t\tcontinue\n\t\t}\n\n\t\tob := old.Buckets[oi]\n\n\t\tswitch {\n\t\tcase ob.Min < hb.Min:\n\t\t\t// The old histogram shouldn't contain any buckets that aren't in the new one.\n\t\t\treturn nil, errors.Errorf(\"bucket [%d,%d) is present in old histogram but not new one\", ob.Min, ob.Max)\n\t\tcase ob.Min > hb.Min:\n\t\t\t// If this bucket isn't present in the old histogram, just copy it over.\n\t\t\tif ob.Min < hb.Max {\n\t\t\t\treturn nil, errors.Errorf(\"old bucket [%d,%d) overlaps new bucket [%d,%d)\", ob.Min, ob.Max, hb.Min, hb.Max)\n\t\t\t}\n\t\t\tdiff.Buckets = append(diff.Buckets, hb)\n\t\tcase ob.Min == hb.Min:\n\t\t\t// If we're looking at the same bucket in both histograms, save the difference (if any) and move to the next old bucket.\n\t\t\tif ob.Max != hb.Max {\n\t\t\t\treturn nil, errors.Errorf(\"old bucket [%d,%d) doesn't match new bucket [%d,%d)\", ob.Min, ob.Max, hb.Min, hb.Max)\n\t\t\t}\n\t\t\tif hb.Count < ob.Count {\n\t\t\t\treturn nil, errors.Errorf(\"old bucket [%d,%d) has count %d, new only has %d\", ob.Min, ob.Max, ob.Count, hb.Count)\n\t\t\t} else if hb.Count > ob.Count {\n\t\t\t\tdiff.Buckets = append(diff.Buckets, HistogramBucket{hb.Min, hb.Max, hb.Count - ob.Count})\n\t\t\t}\n\t\t\toi++\n\t\t}\n\t}\n\treturn diff, nil\n}", "func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tlower := vals[0].(Vector)[0].F\n\tupper := vals[1].(Vector)[0].F\n\tinVec := vals[2].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramFraction(lower, upper, sample.H),\n\t\t})\n\t}\n\treturn enh.Out\n}", "func NewHistoCounter(sink *Counter) *HistoCounter {\n\treturn &HistoCounter{\n\t\tsink: sink,\n\t\tDatapointBucket: sfxclient.NewRollingBucket(\"datapoint_batch_size\", map[string]string{}),\n\t\tEventBucket: sfxclient.NewRollingBucket(\"event_batch_size\", map[string]string{}),\n\t\tSpanBucket: sfxclient.NewRollingBucket(\"span_batch_size\", map[string]string{}),\n\t}\n}", "func (block *Block) CalculateHistogram(x, y int) {\n\n\tblock.Histogram = make([]int, 256)\n\tblock.Histogram.Generate(block)\n\tblock.Histogram.Clip(block.Picture.ClipLimit)\n\tblock.Histogram.Map(int(block.Picture.ColorMin), int(block.Picture.ColorMax), block.Picture.BlockWidth, block.Picture.BlockHeight)\n\n\t// Notify SubBlocks waiting for this block that we're ready!\n\tfor _, subBlock := range block.Notify {\n\t\tsubBlock.WaitGroup.Done()\n\t}\n\n}", "func CreateDescribeHistogramResponse() (response *DescribeHistogramResponse) {\n\tresponse = &DescribeHistogramResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDescribeAlertLogHistogramRequest() (request *DescribeAlertLogHistogramRequest) {\n\trequest = &DescribeAlertLogHistogramRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Cms\", \"2019-01-01\", \"DescribeAlertLogHistogram\", \"cms\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (m *MetricsManager) AddHistogram(name, help string, labelNames []string, buckets []float64) error {\n\tvar allLabels sort.StringSlice\n\tfor k := range m.commonLabels {\n\t\tallLabels = append(allLabels, k)\n\t}\n\tallLabels = append(allLabels, labelNames...)\n\tallLabels.Sort()\n\n\topts := prometheus.HistogramOpts{\n\t\tName: name,\n\t\tHelp: help,\n\t}\n\tif buckets != nil {\n\t\topts.Buckets = buckets\n\t}\n\n\tmetric := prometheus.NewHistogramVec(opts, allLabels)\n\tif err := prometheus.Register(metric); err != nil {\n\t\treturn err\n\t}\n\n\tpartialMetric, err := metric.CurryWith(m.commonLabels)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.histograms[name] = &Histogram{\n\t\tcreationTime: time.Now(),\n\t\tmetric: partialMetric,\n\t}\n\treturn nil\n}", "func getHistogramSamples(name string,\n\tlabels []*prometheus_models.LabelPair,\n\ttimestampMs int64,\n\th *prometheus_models.Histogram,\n\tentity string,\n) []Sample {\n\tsamples := make([]Sample, len(h.GetBucket())*2+2)\n\tsamples[0] = Sample{\n\t\tname: name + \"_count\",\n\t\tlabels: labels,\n\t\ttimestampMs: timestampMs,\n\t\tvalue: strconv.FormatUint(h.GetSampleCount(), 10),\n\t\tentity: entity,\n\t}\n\tsamples[1] = Sample{\n\t\tname: name + \"_sum\",\n\t\tlabels: labels,\n\t\ttimestampMs: timestampMs,\n\t\tvalue: strconv.FormatFloat(h.GetSampleSum(), 'E', -1, 64),\n\t\tentity: entity,\n\t}\n\tfor i, b := range h.GetBucket() {\n\t\tsamples[i+2] = Sample{\n\t\t\tname: fmt.Sprintf(\"%s_bucket_%d_le\", name, i),\n\t\t\tlabels: labels,\n\t\t\ttimestampMs: timestampMs,\n\t\t\tvalue: strconv.FormatFloat(b.GetUpperBound(), 'E', -1, 64),\n\t\t\tentity: entity,\n\t\t}\n\t\tsamples[i+3] = Sample{\n\t\t\tname: fmt.Sprintf(\"%s_bucket_%d_count\", name, i),\n\t\t\tlabels: labels,\n\t\t\ttimestampMs: timestampMs,\n\t\t\tvalue: strconv.FormatUint(b.GetCumulativeCount(), 10),\n\t\t\tentity: entity,\n\t\t}\n\t}\n\treturn samples\n}", "func GetOrRegisterHistogram(namespace, field string, tags map[string]string) metrics.Histogram {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tname := internal.BuildFQName(internalNamespace, namespace)\n\tkey := key(name, tags)\n\tmm := metrics.GetOrRegisterMultiMetric(key, tags, registry)\n\tif metric, ok := mm.Metrics()[field]; ok {\n\t\tswitch v := metric.(type) {\n\t\tcase metrics.Histogram:\n\t\t\treturn v\n\t\tdefault:\n\t\t\tpanic(\"Attempted to register Histogram over other metric\")\n\t\t}\n\t}\n\ts := metrics.NewUniformSample(10000)\n\tc := mm.GetOrAdd(field, func() metrics.Histogram { return metrics.NewHistogram(s) }).(metrics.Histogram)\n\treturn c\n}", "func NewDurationHistogram(durations []time.Duration, opts *HistogramOptions) *Histogram {\n\tnanos := make([]float64, len(durations))\n\tfor i, d := range durations {\n\t\tnanos[i] = float64(d.Nanoseconds())\n\t}\n\treturn NewHistogram(nanos, opts)\n}", "func (ms HistogramBucketExemplar) InitEmpty() {\n\t*ms.orig = &otlpmetrics.HistogramDataPoint_Bucket_Exemplar{}\n}", "func BuildColumn(ctx context.Context, numBuckets, id int64, ndv int64, count int64, samples []types.Datum) (*Histogram, error) {\n\tif count == 0 {\n\t\treturn &Histogram{ID: id}, nil\n\t}\n\tsc := ctx.GetSessionVars().StmtCtx\n\terr := types.SortDatums(sc, samples)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\thg := &Histogram{\n\t\tID: id,\n\t\tNDV: ndv,\n\t\tBuckets: make([]Bucket, 1, numBuckets),\n\t}\n\tvaluesPerBucket := float64(count)/float64(numBuckets) + 1\n\n\t// As we use samples to build the histogram, the bucket number and repeat should multiply a factor.\n\tsampleFactor := float64(count) / float64(len(samples))\n\tndvFactor := float64(count) / float64(ndv)\n\tif ndvFactor > sampleFactor {\n\t\tndvFactor = sampleFactor\n\t}\n\tbucketIdx := 0\n\tvar lastCount int64\n\tfor i := int64(0); i < int64(len(samples)); i++ {\n\t\tcmp, err := hg.Buckets[bucketIdx].Value.CompareDatum(sc, samples[i])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\ttotalCount := float64(i+1) * sampleFactor\n\t\tif cmp == 0 {\n\t\t\t// The new item has the same value as current bucket value, to ensure that\n\t\t\t// a same value only stored in a single bucket, we do not increase bucketIdx even if it exceeds\n\t\t\t// valuesPerBucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\tif float64(hg.Buckets[bucketIdx].Repeats) == ndvFactor {\n\t\t\t\thg.Buckets[bucketIdx].Repeats = int64(2 * sampleFactor)\n\t\t\t} else {\n\t\t\t\thg.Buckets[bucketIdx].Repeats += int64(sampleFactor)\n\t\t\t}\n\t\t} else if totalCount-float64(lastCount) <= valuesPerBucket {\n\t\t\t// The bucket still have room to store a new item, update the bucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\thg.Buckets[bucketIdx].Value = samples[i]\n\t\t\thg.Buckets[bucketIdx].Repeats = int64(ndvFactor)\n\t\t} else {\n\t\t\tlastCount = hg.Buckets[bucketIdx].Count\n\t\t\t// The bucket is full, store the item in the next bucket.\n\t\t\tbucketIdx++\n\t\t\thg.Buckets = append(hg.Buckets, Bucket{\n\t\t\t\tCount: int64(totalCount),\n\t\t\t\tValue: samples[i],\n\t\t\t\tRepeats: int64(ndvFactor),\n\t\t\t})\n\t\t}\n\t}\n\treturn hg, nil\n}", "func New(buckets int) *ModHasher {\n\treturn &ModHasher{uint64(buckets)}\n}", "func CreateDescribeHistogramRequest() (request *DescribeHistogramRequest) {\n\trequest = &DescribeHistogramRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aegis\", \"2016-11-11\", \"DescribeHistogram\", \"vipaegis\", \"openAPI\")\n\treturn\n}", "func (m *Metrics) HistogramVec(name, help string, buckets []float64, labels ...string) *prometheus.HistogramVec {\n\thistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: m.config.Namespace,\n\t\tName: name,\n\t\tHelp: help,\n\t\tBuckets: buckets,\n\t}, labels)\n\n\tprometheus.MustRegister(histogram)\n\n\treturn histogram\n}", "func getHistogram(ctx context.Context, name string, labels map[string]string) Histogram {\n\tif !On(ctx) {\n\t\treturn &nopHistogram{}\n\t}\n\tif opts, ok := Histograms[name]; !ok {\n\t\tmsg := fmt.Sprintf(\"attempted to get undeclared histogram %s\", name)\n\t\tpanic(msg)\n\t} else {\n\t\tif !mustCompleteLabels(opts.Labels, labels) {\n\t\t\terr := fmt.Sprintf(\"attempted to set histogram %s with invalid labels, expected %v but got %v\",\n\t\t\t\tname, opts.Labels, labels)\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn metricsClient(ctx).GetHistogram(name, labels)\n}", "func (e errChunkIterator) AtHistogram() (int64, *histogram.Histogram) { panic(\"not implemented\") }", "func (h *Histogram) Reset() {\n\th.Counter.Reset()\n\t// Leave Offset and Divider alone\n\tfor i := 0; i < len(h.Hdata); i++ {\n\t\th.Hdata[i] = 0\n\t}\n}", "func NewBucket(desc metrics.Descriptor, dur time.Duration) (*Bucket, error) {\n\tvar (\n\t\tm metrics.Metric\n\t\terr error\n\t)\n\tif m, err = metrics.FromDescriptor(desc); err != nil {\n\t\treturn nil, err\n\t}\n\tshard := NewShard(m, dur)\n\treturn &Bucket{\n\t\tdescriptor: desc,\n\t\tshards: []*Shard{shard},\n\t\tshardDuration: dur,\n\t}, nil\n}", "func (h *Histograms) With(labels model.LabelSet) prometheus.Histogram {\n\treturn h.metricVec.With(labels).(prometheus.Histogram)\n}", "func New() *Hash {\n\treturn &Hash{\n\t\tbuckets: make([][]entry, numBuckets),\n\t}\n}", "func makeBuckets(m *dto.Metric) map[string]interface{} {\n\tfields := make(map[string]interface{})\n\tfor _, b := range m.GetHistogram().Bucket {\n\t\tfields[fmt.Sprint(b.GetUpperBound())] = float64(b.GetCumulativeCount())\n\t}\n\treturn fields\n}", "func MergeHistograms(a HistogramBuckets, b HistogramBuckets) (HistogramBuckets, error) {\n\tcounts := make(map[HistogramBucket]uint64)\n\tfor _, cur := range a {\n\t\tkey := HistogramBucket{\n\t\t\tScale: cur.Scale,\n\t\t\tLowerBound: cur.LowerBound,\n\t\t\tUpperBound: cur.UpperBound,\n\t\t}\n\t\tcounts[key] = cur.Count\n\t}\n\tfor _, cur := range b {\n\t\tkey := HistogramBucket{\n\t\t\tScale: cur.Scale,\n\t\t\tLowerBound: cur.LowerBound,\n\t\t\tUpperBound: cur.UpperBound,\n\t\t}\n\t\tprevCount, ok := counts[key]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"[%f, %f] not found in previous counts\", cur.LowerBound, cur.UpperBound)\n\t\t}\n\t\tcounts[key] = prevCount + cur.Count\n\t}\n\ths := make(HistogramBuckets, 0, len(counts))\n\tfor k, v := range counts {\n\t\ths = append(hs, HistogramBucket{\n\t\t\tScale: k.Scale,\n\t\t\tLowerBound: k.LowerBound,\n\t\t\tUpperBound: k.UpperBound,\n\t\t\tCount: v,\n\t\t})\n\t}\n\tsort.Sort(HistogramBuckets(hs))\n\treturn hs, nil\n}", "func CreateDescribeAlertLogHistogramResponse() (response *DescribeAlertLogHistogramResponse) {\n\tresponse = &DescribeAlertLogHistogramResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func NewBar(total int) *Bar {\n\treturn &Bar{\n\t\tTotal: total,\n\t\tWidth: Width,\n\t\tLeftEnd: LeftEnd,\n\t\tRightEnd: RightEnd,\n\t\tHead: Head,\n\t\tFill: Fill,\n\t\tEmpty: Empty,\n\n\t\tmtx: &sync.RWMutex{},\n\t}\n}", "func (ms HistogramDataPoint) InitEmpty() {\n\t*ms.orig = &otlpmetrics.HistogramDataPoint{}\n}", "func (h *Histogram) Add(value int64) {\n\tfor i := range h.labels {\n\t\tif i == len(h.labels)-1 || value <= h.cutoffs[i] {\n\t\t\th.buckets[i].Add(1)\n\t\t\th.total.Add(value)\n\t\t\tbreak\n\t\t}\n\t}\n\tif h.hook != nil {\n\t\th.hook(value)\n\t}\n\tif defaultStatsdHook.histogramHook != nil && h.name != \"\" {\n\t\tdefaultStatsdHook.histogramHook(h.name, value)\n\t}\n}", "func (h *Histogram) Add(value int64) error {\n\tbucket, err := h.findBucket(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.buckets[bucket].count.Incr(1)\n\th.count.Incr(1)\n\th.sum.Incr(value)\n\th.sumOfSquares.Incr(value * value)\n\th.tracker.Push(value)\n\treturn nil\n}", "func ComputeHistogram(block []byte, freqs []int, isOrder0, withTotal bool) {\n\tif isOrder0 == true {\n\t\tif withTotal == true {\n\t\t\tfreqs[256] = len(block)\n\t\t}\n\n\t\tf0 := [256]int{}\n\t\tf1 := [256]int{}\n\t\tf2 := [256]int{}\n\t\tf3 := [256]int{}\n\t\tend16 := len(block) & -16\n\n\t\tfor i := 0; i < end16; {\n\t\t\td := block[i:i+16]\n\t\t\tf0[d[0]]++\n\t\t\tf1[d[1]]++\n\t\t\tf2[d[2]]++\n\t\t\tf3[d[3]]++\n\t\t\tf0[d[4]]++\n\t\t\tf1[d[5]]++\n\t\t\tf2[d[6]]++\n\t\t\tf3[d[7]]++\n\t\t\tf0[d[8]]++\n\t\t\tf1[d[9]]++\n\t\t\tf2[d[10]]++\n\t\t\tf3[d[11]]++\n\t\t\tf0[d[12]]++\n\t\t\tf1[d[13]]++\n\t\t\tf2[d[14]]++\n\t\t\tf3[d[15]]++\n\t\t\ti += 16\n\t\t}\n\n\t\tfor i := end16; i < len(block); i++ {\n\t\t\tfreqs[block[i]]++\n\t\t}\n\n\t\tfor i := 0; i < 256; i++ {\n\t\t\tfreqs[i] += (f0[i] + f1[i] + f2[i] + f3[i])\n\t\t}\n\t} else { // Order 1\n\t\tlength := len(block)\n\t\tquarter := length >> 2\n\t\tn0 := 0 * quarter\n\t\tn1 := 1 * quarter\n\t\tn2 := 2 * quarter\n\t\tn3 := 3 * quarter\n\n\t\tif withTotal == true {\n\t\t\tif length < 32 {\n\t\t\t\tprv := uint(0)\n\n\t\t\t\tfor i := 0; i < length; i++ {\n\t\t\t\t\tfreqs[prv+uint(block[i])]++\n\t\t\t\t\tfreqs[prv+256]++\n\t\t\t\t\tprv = 257 * uint(block[i])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprv0 := uint(0)\n\t\t\t\tprv1 := 257 * uint(block[n1-1])\n\t\t\t\tprv2 := 257 * uint(block[n2-1])\n\t\t\t\tprv3 := 257 * uint(block[n3-1])\n\n\t\t\t\tfor n0 < quarter {\n\t\t\t\t\tcur0 := uint(block[n0])\n\t\t\t\t\tcur1 := uint(block[n1])\n\t\t\t\t\tcur2 := uint(block[n2])\n\t\t\t\t\tcur3 := uint(block[n3])\n\t\t\t\t\tfreqs[prv0+cur0]++\n\t\t\t\t\tfreqs[prv0+256]++\n\t\t\t\t\tfreqs[prv1+cur1]++\n\t\t\t\t\tfreqs[prv1+256]++\n\t\t\t\t\tfreqs[prv2+cur2]++\n\t\t\t\t\tfreqs[prv2+256]++\n\t\t\t\t\tfreqs[prv3+cur3]++\n\t\t\t\t\tfreqs[prv3+256]++\n\t\t\t\t\tprv0 = 257 * cur0\n\t\t\t\t\tprv1 = 257 * cur1\n\t\t\t\t\tprv2 = 257 * cur2\n\t\t\t\t\tprv3 = 257 * cur3\n\t\t\t\t\tn0++\n\t\t\t\t\tn1++\n\t\t\t\t\tn2++\n\t\t\t\t\tn3++\n\t\t\t\t}\n\n\t\t\t\tfor ; n3 < length; n3++ {\n\t\t\t\t\tfreqs[prv3+uint(block[n3])]++\n\t\t\t\t\tfreqs[prv3+256]++\n\t\t\t\t\tprv3 = 257 * uint(block[n3])\n\t\t\t\t}\n\t\t\t}\n\t\t} else { // order 1, no total\n\t\t\tif length < 32 {\n\t\t\t\tprv := uint(0)\n\n\t\t\t\tfor i := 0; i < length; i++ {\n\t\t\t\t\tfreqs[prv+uint(block[i])]++\n\t\t\t\t\tprv = 256 * uint(block[i])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprv0 := uint(0)\n\t\t\t\tprv1 := 256 * uint(block[n1-1])\n\t\t\t\tprv2 := 256 * uint(block[n2-1])\n\t\t\t\tprv3 := 256 * uint(block[n3-1])\n\n\t\t\t\tfor n0 < quarter {\n\t\t\t\t\tcur0 := uint(block[n0])\n\t\t\t\t\tcur1 := uint(block[n1])\n\t\t\t\t\tcur2 := uint(block[n2])\n\t\t\t\t\tcur3 := uint(block[n3])\n\t\t\t\t\tfreqs[prv0+cur0]++\n\t\t\t\t\tfreqs[prv1+cur1]++\n\t\t\t\t\tfreqs[prv2+cur2]++\n\t\t\t\t\tfreqs[prv3+cur3]++\n\t\t\t\t\tprv0 = cur0 << 8\n\t\t\t\t\tprv1 = cur1 << 8\n\t\t\t\t\tprv2 = cur2 << 8\n\t\t\t\t\tprv3 = cur3 << 8\n\t\t\t\t\tn0++\n\t\t\t\t\tn1++\n\t\t\t\t\tn2++\n\t\t\t\t\tn3++\n\t\t\t\t}\n\n\t\t\t\tfor ; n3 < length; n3++ {\n\t\t\t\t\tfreqs[prv3+uint(block[n3])]++\n\t\t\t\t\tprv3 = uint(block[n3]) << 8\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (it *pushdownSeriesIterator) AtHistogram() (int64, *histogram.Histogram) {\n\tpanic(\"not implemented\")\n}", "func GetHistogram(ctx context.Context, tconn *chrome.TestConn, name string) (*Histogram, error) {\n\th := Histogram{Name: name}\n\tif err := tconn.Call(ctx, &h, `tast.promisify(chrome.metricsPrivate.getHistogram)`, name); err != nil {\n\t\tif strings.Contains(err.Error(), fmt.Sprintf(\"Histogram %s not found\", name)) {\n\t\t\treturn &Histogram{Name: name}, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tif err := h.validate(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"bad histogram %v\", h)\n\t}\n\treturn &h, nil\n}", "func newBucketGroup(mBuckets int64) bucketGroup {\n\treturn make(bucketGroup, mBuckets)\n}", "func NewLinearHist(min, max float64, nbins int) *LinearHist {\n\tdelta := float64(nbins) / (max - min)\n\treturn &LinearHist{min, max, delta, 0, 0, make([]uint, nbins)}\n}", "func ConvertSampleToHistogram(sample *model.Sample, h *Histogram) {\n\tlabels := make(map[string]string)\n\tfor k, v := range sample.Metric {\n\t\tif k != model.BucketLabel {\n\t\t\tlabels[string(k)] = string(v)\n\t\t}\n\t}\n\n\th.Labels = labels\n\th.Buckets[string(sample.Metric[model.BucketLabel])] += int(sample.Value)\n}", "func NewDeltaHistogram[N int64 | float64](cfg aggregation.ExplicitBucketHistogram) Aggregator[N] {\n\treturn &deltaHistogram[N]{\n\t\thistValues: newHistValues[N](cfg.Boundaries),\n\t\tnoMinMax: cfg.NoMinMax,\n\t\tstart: now(),\n\t}\n}", "func Buckets(count int) func(any) error {\n\treturn func(f any) error {\n\t\td := f.(*dto.Histogram)\n\t\tif len(d.Bucket) != count {\n\t\t\treturn fmt.Errorf(\"want %v buckets, got %v\", count, len(d.Bucket))\n\t\t}\n\t\treturn nil\n\t}\n}", "func New(rgb color.RGBA) *HSBA {\n\tvar r, g, b float64\n\tvar rgb_min, rgb_max, delta float64\n\n\tr = float64(rgb.R) / 255.0\n\tg = float64(rgb.G) / 255.0\n\tb = float64(rgb.B) / 255.0\n\n\trgb_max = math.Max(r, math.Max(g, b))\n\trgb_min = math.Min(r, math.Min(g, b))\n\n\th := &HSBA{0, 0.0, rgb_max, float64(rgb.A) / 255.0}\n\n\tdelta = rgb_max - rgb_min\n\n\tif rgb_max == 0 {\n\t\th.S = 0\n\t} else {\n\t\th.S = delta / rgb_max\n\t}\n\n\tif delta == 0 {\n\t\th.H = 0\n\t\th.S = 0\n\t} else if rgb_max == r {\n\t\tif g >= b {\n\t\t\th.H = int(60 * (g - b) / delta)\n\t\t} else {\n\t\t\th.H = int(60*(g-b)/delta + 360)\n\t\t}\n\t} else if rgb_max == g {\n\t\th.H = int(60*(b-r)/delta + 120)\n\t} else {\n\t\th.H = int(60*(r-g)/delta + 240)\n\t}\n\n\treturn h\n}" ]
[ "0.73743796", "0.7168792", "0.7159077", "0.6934756", "0.6632371", "0.65602773", "0.6504207", "0.6394936", "0.63825554", "0.63377315", "0.6321556", "0.6309373", "0.62639225", "0.6134104", "0.61226654", "0.6092483", "0.60104716", "0.5948328", "0.5894486", "0.5871288", "0.586908", "0.5847022", "0.58295554", "0.56844276", "0.5679534", "0.56742376", "0.5666894", "0.56507796", "0.5628003", "0.55662537", "0.5560393", "0.5550075", "0.5548444", "0.55350244", "0.55171156", "0.55169696", "0.55163896", "0.5505417", "0.54838496", "0.5464635", "0.5455417", "0.54545486", "0.5437295", "0.54131234", "0.5410642", "0.53812766", "0.53203565", "0.5320074", "0.5301113", "0.52937776", "0.5284943", "0.525974", "0.524513", "0.5242555", "0.52386594", "0.52336735", "0.5228692", "0.5186169", "0.5176193", "0.5147798", "0.51455873", "0.5135816", "0.5131744", "0.51027685", "0.51000917", "0.5079856", "0.5073943", "0.5066524", "0.5066096", "0.5060036", "0.5031205", "0.49885076", "0.49869925", "0.4966229", "0.4957219", "0.4956202", "0.49520603", "0.49513927", "0.49504474", "0.49360475", "0.4918212", "0.4896037", "0.48907226", "0.48845592", "0.4873318", "0.48620662", "0.4861062", "0.48588642", "0.48557568", "0.48530537", "0.48497266", "0.48415744", "0.4839443", "0.48349082", "0.48031133", "0.47986826", "0.4795407", "0.47895688", "0.47879496", "0.47856885" ]
0.7941442
0
Val2Bucket values are kept in two different structure val2Bucket allows you reach between 0 and 1000 in constant time
func init() { val2Bucket = make([]int, maxArrayValue) maxArrayValueIndex = -1 for i, value := range histogramBucketValues { if value == maxArrayValue { maxArrayValueIndex = i break } } if maxArrayValueIndex == -1 { log.Fatalf("Bug boundary maxArrayValue=%d not found in bucket list %v", maxArrayValue, histogramBucketValues) } idx := 0 for i := int32(0); i < maxArrayValue; i++ { if i >= histogramBucketValues[idx] { idx++ } val2Bucket[i] = idx } // coding bug detection (aka impossible if it works once) until 1000 if idx != maxArrayValueIndex { log.Fatalf("Bug in creating histogram index idx %d vs index %d up to %d", idx, int(maxArrayValue), maxArrayValue) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bl *lfList) bucketValue(b int) int {\n return int(atomic.LoadInt32(&bl.b[b]))\n}", "func TestBucket(t *testing.T) {\n\ttestData := []struct {\n\t\tinput int64\n\t\texpected int64\n\t}{\n\t\t{0, 0},\n\t\t{1, 1},\n\t\t{2, 2},\n\t\t{3, 3},\n\t\t{4, 4},\n\t\t{5, 5},\n\t\t{6, 6},\n\t\t{7, 7},\n\t\t{8, 8},\n\t\t{9, 9},\n\t\t{10, 10},\n\t\t{11, 10},\n\t\t{20, 10},\n\t\t{99, 10},\n\t\t{100, 100},\n\t\t{101, 100},\n\t\t{200, 100},\n\t\t{999, 100},\n\t\t{1000, 1000},\n\t\t{math.MaxInt64, 1000000000000000000},\n\t\t{-1, -1},\n\t\t{-2, -2},\n\t\t{-3, -3},\n\t\t{-4, -4},\n\t\t{-5, -5},\n\t\t{-6, -6},\n\t\t{-7, -7},\n\t\t{-8, -8},\n\t\t{-9, -9},\n\t\t{-10, -10},\n\t\t{-11, -10},\n\t\t{-20, -10},\n\t\t{-100, -100},\n\t\t{-200, -100},\n\t\t{math.MinInt64, -1000000000000000000},\n\t}\n\n\tfor _, tc := range testData {\n\t\tif actual, expected := telemetry.Bucket10(tc.input), tc.expected; actual != expected {\n\t\t\tt.Errorf(\"%d: expected %d, got %d\", tc.input, expected, actual)\n\t\t}\n\t}\n}", "func TestBucket(t *testing.T) {\n\tconst n = 100\n\n\tlocal := p2p.GenerateRandomNodeData()\n\tlocalId := local.DhtId()\n\n\tb := table.NewBucket()\n\tnodes := p2p.GenerateRandomNodesData(n)\n\tfor i := 0; i < n; i++ {\n\t\tb.PushFront(nodes[i])\n\t}\n\n\ti := rand.Intn(len(nodes))\n\tif !b.Has(nodes[i]) {\n\t\tt.Errorf(\"Failed to find peer: %v\", nodes[i])\n\t}\n\n\tspl := b.Split(0, localId)\n\tllist := b.List()\n\n\tfor e := llist.Front(); e != nil; e = e.Next() {\n\t\tid := e.Value.(node.RemoteNodeData).DhtId()\n\t\tcpl := id.CommonPrefixLen(localId)\n\t\tif cpl > 0 {\n\t\t\tt.Fatalf(\"Split failed. found id with cpl > 0 in 0 bucket\")\n\t\t}\n\t}\n\n\trlist := spl.List()\n\n\tfor e := rlist.Front(); e != nil; e = e.Next() {\n\t\tid := e.Value.(node.RemoteNodeData).DhtId()\n\t\tcpl := id.CommonPrefixLen(localId)\n\t\tif cpl == 0 {\n\t\t\tt.Fatalf(\"Split failed. found id with cpl == 0 in non 0 bucket\")\n\t\t}\n\t}\n}", "func valueLimiter(index indexedCluster, cluster []cell) (changes []cell) {\n\tupperBound := len(index)\n\tfor i := 2; i <= upperBound; i++ {\n\t\tchanges = append(changes, valueLimiterChild(i, []int{}, index, cluster)...)\n\t}\n\treturn changes\n}", "func (c *TwoQueueCache[K, V]) Values() []V {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tv1 := c.frequent.Values()\n\tv2 := c.recent.Values()\n\treturn append(v1, v2...)\n}", "func dobucket(bn int) {\n\n\tdefer func() { <-sem }()\n\n\tdtypes := config.ReadDtypes(bn, sourcedir)\n\n\twritedtypes(dtypes, bn)\n\n\tix := getix(bn)\n\n\tfor vn, dt := range dtypes {\n\n\t\tif dt == \"uvarint\" {\n\t\t\tdouvarint(bn, vn, ix)\n\t\t} else if dt == \"varint\" {\n\t\t\tpanic(\"varint not implemented\\n\")\n\t\t} else {\n\t\t\tw := config.DTsize[dt]\n\t\t\tdofixedwidth(bn, vn, w, ix)\n\t\t}\n\t}\n}", "func Test_BucketCreation(t *testing.T) {\n\t// Create a bucket with capacity 3, that adds tokens every 4 seconds\n\tconst RATE = 4 * time.Second\n\tconst CAPACITY = 3\n\tconst ERROR = 500 * time.Millisecond\n\tconst EXPECTED_DURATION = RATE * CAPACITY\n\n\tb := tokenbucket.NewBucket(RATE, CAPACITY)\n\n\t// Ensure that the bucket is empty\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\n\t// Spending three times on an empty bucket should take 12 seconds\n\t// (Take the average across three, due to imprecision/scheduling)\n\tbefore := time.Now()\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\tafter := time.Now()\n\n\tlower := EXPECTED_DURATION - ERROR\n\tupper := EXPECTED_DURATION + ERROR\n\tif diff := after.Sub(before); diff < lower || diff > upper {\n\t\tt.Errorf(\"Waited %s seconds, though really should have waited between %s and %s\", diff.String(), lower.String(), upper.String())\n\t}\n}", "func Test_BucketBuffering(t *testing.T) {\n\t// Create a bucket with capacity 3, that adds tokens every 4 seconds\n\tconst RATE = 4 * time.Second\n\tconst CAPACITY = 3\n\tconst ERROR = 500 * time.Millisecond\n\tb := tokenbucket.NewBucket(RATE, CAPACITY)\n\n\t// Allow the bucket enough time to fill to capacity\n\ttime.Sleep(CAPACITY * RATE)\n\n\t// Check that we can empty the bucket without wasting any time\n\tbefore := time.Now()\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\t<-b.SpendToken(1)\n\tafter := time.Now()\n\n\tif diff := after.Sub(before); diff > RATE {\n\t\tt.Errorf(\"Waited %d seconds, though this should have been nearly instantaneous\", diff)\n\t}\n}", "func newBuckets(c Config, end time.Time) buckets {\n\tn := c.len()\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tout := make(buckets, n+1)\n\n\tfor i := n; i >= 1; i-- {\n\t\tw := c.MinInterval()\n\n\t\t// c is a copy of the config,\n\t\t// so we can decrement values without\n\t\t// a problem.\n\t\tswitch w {\n\t\tcase Hour:\n\t\t\tc.Hourly--\n\t\tcase Day:\n\t\t\tc.Daily--\n\t\tcase Week:\n\t\t\tc.Weekly--\n\t\tcase Month:\n\t\t\tc.Monthly--\n\t\tcase Year:\n\t\t\tc.Yearly--\n\t\tcase -1:\n\t\t\tpanic(\"ran out of buckets\")\n\t\tdefault:\n\t\t\tpanic(\"unknown interval\")\n\t\t}\n\n\t\tout[i] = &bucket{\n\t\t\tWidth: w,\n\t\t\tEnd: end,\n\t\t}\n\t\tend = end.Add(-w)\n\t}\n\n\t// Catchall bucket.\n\tout[0] = &bucket{\n\t\tEnd: end,\n\t\tWidth: 0,\n\t}\n\n\treturn out\n}", "func (this *MyHashMap) Put(key int, value int) {\n\t// 此处选择取模的数为1024-1=1023 的原因是因为素数\n\t// 此文章有做解析 https://cloud.tencent.com/developer/ask/79043\n\tindex := key & (this.b - 1)\n\tfor e := range this.bucket[index] {\n\t\tif this.bucket[index][e].key == key {\n\t\t\tthis.bucket[index][e].value = value\n\t\t\treturn\n\t\t}\n\t}\n\tthis.bucket[index] = append(this.bucket[index], kv{key: key, value: value})\n\treturn\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func buildBucketFeedback(h *Histogram, feedback *QueryFeedback) (map[int]*BucketFeedback, int) {\n\tbktID2FB := make(map[int]*BucketFeedback)\n\tif len(feedback.Feedback) == 0 {\n\t\treturn bktID2FB, 0\n\t}\n\ttotal := 0\n\tsc := &stmtctx.StatementContext{TimeZone: time.UTC}\n\tmin, max := GetMinValue(h.Tp), GetMaxValue(h.Tp)\n\tfor _, fb := range feedback.Feedback {\n\t\tskip, err := fb.adjustFeedbackBoundaries(sc, &min, &max)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"adjust feedback boundaries failed\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif skip {\n\t\t\tcontinue\n\t\t}\n\t\tidx := h.Bounds.UpperBound(0, fb.Lower)\n\t\tbktIdx := 0\n\t\t// The last bucket also stores the feedback that falls outside the upper bound.\n\t\tif idx >= h.Bounds.NumRows()-1 {\n\t\t\tbktIdx = h.Len() - 1\n\t\t} else if h.Len() == 1 {\n\t\t\tbktIdx = 0\n\t\t} else {\n\t\t\tif idx == 0 {\n\t\t\t\tbktIdx = 0\n\t\t\t} else {\n\t\t\t\tbktIdx = (idx - 1) / 2\n\t\t\t}\n\t\t\t// Make sure that this feedback lies within the bucket.\n\t\t\tif chunk.Compare(h.Bounds.GetRow(2*(bktIdx+1)), 0, fb.Upper) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ttotal++\n\t\tbkt := bktID2FB[bktIdx]\n\t\tif bkt == nil {\n\t\t\tbkt = &BucketFeedback{lower: h.GetLower(bktIdx), upper: h.GetUpper(bktIdx)}\n\t\t\tbktID2FB[bktIdx] = bkt\n\t\t}\n\t\tbkt.feedback = append(bkt.feedback, fb)\n\t\t// Update the bound if necessary.\n\t\tres, err := bkt.lower.CompareDatum(nil, fb.Lower)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"compare datum failed\", zap.Any(\"value1\", bkt.lower), zap.Any(\"value2\", fb.Lower), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif res > 0 {\n\t\t\tbkt.lower = fb.Lower\n\t\t}\n\t\tres, err = bkt.upper.CompareDatum(nil, fb.Upper)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"compare datum failed\", zap.Any(\"value1\", bkt.upper), zap.Any(\"value2\", fb.Upper), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif res < 0 {\n\t\t\tbkt.upper = fb.Upper\n\t\t}\n\t}\n\treturn bktID2FB, total\n}", "func (tb *TimeBucket) NumValueBits() int { return tb.numValueBits }", "func BenchmarkDoMultiwayMerge_4GiB_values(b *testing.B) {\n\tconst N = 4 * 1024 * 1024 * 1024 / sortio.SizeOfValue // 8GiB data = 1G values\n\tconst InputCount = 8\n\tconst ValuesPerInput = N / InputCount\n\t//defer profile.Start(profile.MemProfile).Stop()\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tb.StopTimer()\n\t\tlog.Println(\"Preparing data...\")\n\n\t\tinput := make([]sortio.Uint64Reader, InputCount)\n\t\tfor i := range input {\n\t\t\tinputPart := make([]uint64, ValuesPerInput)\n\t\t\tfor j := range inputPart {\n\t\t\t\tinputPart[j] = rand.Uint64()\n\t\t\t}\n\t\t\tsort.Slice(inputPart, func(i, j int) bool { return inputPart[i] < inputPart[j] })\n\t\t\tinput[i] = sortio.NewSliceUint64Reader(inputPart)\n\t\t}\n\n\t\toutput := sortio.NewNullUint64Writer()\n\n\t\tlog.Println(\"Preparation finished.\")\n\t\tb.StartTimer()\n\n\t\tDoMultiwayMerge(input, output)\n\t}\n}", "func makeBuckets(current, prev summaryMap, l *logrus.Entry) []*agentpb.MetricsBucket {\n\tres := make([]*agentpb.MetricsBucket, 0, len(current))\n\n\tfor digest, currentESS := range current {\n\t\tprevESS := prev[digest]\n\t\tif prevESS == nil {\n\t\t\tprevESS = &eventsStatementsSummaryByDigest{}\n\t\t}\n\n\t\tswitch {\n\t\tcase currentESS.CountStar == prevESS.CountStar:\n\t\t\t// Another way how this is possible is if events_statements_summary_by_digest was truncated,\n\t\t\t// and then the same number of queries were made.\n\t\t\t// Currently, we can't differentiate between those situations.\n\t\t\t// TODO We probably could by using first_seen/last_seen columns.\n\t\t\tl.Tracef(\"Skipped due to the same number of queries: %s.\", currentESS)\n\t\t\tcontinue\n\t\tcase currentESS.CountStar < prevESS.CountStar:\n\t\t\tl.Debugf(\"Truncate detected. Treating as a new query: %s.\", currentESS)\n\t\t\tprevESS = &eventsStatementsSummaryByDigest{}\n\t\tcase prevESS.CountStar == 0:\n\t\t\tl.Debugf(\"New query: %s.\", currentESS)\n\t\tdefault:\n\t\t\tl.Debugf(\"Normal query: %s.\", currentESS)\n\t\t}\n\n\t\tcount := inc(currentESS.CountStar, prevESS.CountStar)\n\t\tfingerprint, isTruncated := truncate.Query(*currentESS.DigestText)\n\t\tmb := &agentpb.MetricsBucket{\n\t\t\tCommon: &agentpb.MetricsBucket_Common{\n\t\t\t\tSchema: pointer.GetString(currentESS.SchemaName), // TODO can it be NULL?\n\t\t\t\tQueryid: *currentESS.Digest,\n\t\t\t\tFingerprint: fingerprint,\n\t\t\t\tIsTruncated: isTruncated,\n\t\t\t\tNumQueries: count,\n\t\t\t\tNumQueriesWithErrors: inc(currentESS.SumErrors, prevESS.SumErrors),\n\t\t\t\tNumQueriesWithWarnings: inc(currentESS.SumWarnings, prevESS.SumWarnings),\n\t\t\t\tAgentType: inventorypb.AgentType_QAN_MYSQL_PERFSCHEMA_AGENT,\n\t\t\t},\n\t\t\tMysql: &agentpb.MetricsBucket_MySQL{},\n\t\t}\n\n\t\tfor _, p := range []struct {\n\t\t\tvalue float32 // result value: currentESS.SumXXX-prevESS.SumXXX\n\t\t\tsum *float32 // MetricsBucket.XXXSum field to write value\n\t\t\tcnt *float32 // MetricsBucket.XXXCnt field to write count\n\t\t}{\n\t\t\t// in order of events_statements_summary_by_digest columns\n\n\t\t\t// convert picoseconds to seconds\n\t\t\t{inc(currentESS.SumTimerWait, prevESS.SumTimerWait) / 1000000000000, &mb.Common.MQueryTimeSum, &mb.Common.MQueryTimeCnt},\n\t\t\t{inc(currentESS.SumLockTime, prevESS.SumLockTime) / 1000000000000, &mb.Mysql.MLockTimeSum, &mb.Mysql.MLockTimeCnt},\n\n\t\t\t{inc(currentESS.SumRowsAffected, prevESS.SumRowsAffected), &mb.Mysql.MRowsAffectedSum, &mb.Mysql.MRowsAffectedCnt},\n\t\t\t{inc(currentESS.SumRowsSent, prevESS.SumRowsSent), &mb.Mysql.MRowsSentSum, &mb.Mysql.MRowsSentCnt},\n\t\t\t{inc(currentESS.SumRowsExamined, prevESS.SumRowsExamined), &mb.Mysql.MRowsExaminedSum, &mb.Mysql.MRowsExaminedCnt},\n\n\t\t\t{inc(currentESS.SumCreatedTmpDiskTables, prevESS.SumCreatedTmpDiskTables), &mb.Mysql.MTmpDiskTablesSum, &mb.Mysql.MTmpDiskTablesCnt},\n\t\t\t{inc(currentESS.SumCreatedTmpTables, prevESS.SumCreatedTmpTables), &mb.Mysql.MTmpTablesSum, &mb.Mysql.MTmpTablesCnt},\n\t\t\t{inc(currentESS.SumSelectFullJoin, prevESS.SumSelectFullJoin), &mb.Mysql.MFullJoinSum, &mb.Mysql.MFullJoinCnt},\n\t\t\t{inc(currentESS.SumSelectFullRangeJoin, prevESS.SumSelectFullRangeJoin), &mb.Mysql.MSelectFullRangeJoinSum, &mb.Mysql.MSelectFullRangeJoinCnt},\n\t\t\t{inc(currentESS.SumSelectRange, prevESS.SumSelectRange), &mb.Mysql.MSelectRangeSum, &mb.Mysql.MSelectRangeCnt},\n\t\t\t{inc(currentESS.SumSelectRangeCheck, prevESS.SumSelectRangeCheck), &mb.Mysql.MSelectRangeCheckSum, &mb.Mysql.MSelectRangeCheckCnt},\n\t\t\t{inc(currentESS.SumSelectScan, prevESS.SumSelectScan), &mb.Mysql.MFullScanSum, &mb.Mysql.MFullScanCnt},\n\n\t\t\t{inc(currentESS.SumSortMergePasses, prevESS.SumSortMergePasses), &mb.Mysql.MMergePassesSum, &mb.Mysql.MMergePassesCnt},\n\t\t\t{inc(currentESS.SumSortRange, prevESS.SumSortRange), &mb.Mysql.MSortRangeSum, &mb.Mysql.MSortRangeCnt},\n\t\t\t{inc(currentESS.SumSortRows, prevESS.SumSortRows), &mb.Mysql.MSortRowsSum, &mb.Mysql.MSortRowsCnt},\n\t\t\t{inc(currentESS.SumSortScan, prevESS.SumSortScan), &mb.Mysql.MSortScanSum, &mb.Mysql.MSortScanCnt},\n\n\t\t\t{inc(currentESS.SumNoIndexUsed, prevESS.SumNoIndexUsed), &mb.Mysql.MNoIndexUsedSum, &mb.Mysql.MNoIndexUsedCnt},\n\t\t\t{inc(currentESS.SumNoGoodIndexUsed, prevESS.SumNoGoodIndexUsed), &mb.Mysql.MNoGoodIndexUsedSum, &mb.Mysql.MNoGoodIndexUsedCnt},\n\t\t} {\n\t\t\tif p.value != 0 {\n\t\t\t\t*p.sum = p.value\n\t\t\t\t*p.cnt = count\n\t\t\t}\n\t\t}\n\n\t\tres = append(res, mb)\n\t}\n\n\treturn res\n}", "func (b *BucketFeedback) splitBucket(newNumBkts int, totalCount float64, originBucketCount float64) []bucket {\n\t// Split the bucket.\n\tbounds := b.getBoundaries(newNumBkts + 1)\n\tbkts := make([]bucket, 0, len(bounds)-1)\n\tsc := &stmtctx.StatementContext{TimeZone: time.UTC}\n\tfor i := 1; i < len(bounds); i++ {\n\t\tnewBkt := bucket{&bounds[i-1], bounds[i].Copy(), 0, 0}\n\t\t// get bucket count\n\t\t_, ratio := getOverlapFraction(Feedback{b.lower, b.upper, int64(originBucketCount), 0}, newBkt)\n\t\tcountInNewBkt := originBucketCount * ratio\n\t\tcountInNewBkt = b.refineBucketCount(sc, newBkt, countInNewBkt)\n\t\t// do not split if the count of result bucket is too small.\n\t\tif countInNewBkt < minBucketFraction*totalCount {\n\t\t\tbounds[i] = bounds[i-1]\n\t\t\tcontinue\n\t\t}\n\t\tnewBkt.Count = int64(countInNewBkt)\n\t\tbkts = append(bkts, newBkt)\n\t\t// To guarantee that each bucket's range will not overlap.\n\t\tsetNextValue(&bounds[i])\n\t}\n\treturn bkts\n}", "func (b *MetricsBPFMap) GetValue() float64 {\n\tebpfMap, err := ebpf.NewMapFromID(b.MapID)\n\tif err != nil {\n\t\t// We have observed in smaller configuration VM's, if we restart KF's\n\t\t// Stale mapID's are reported, in such cases re-checking map id\n\t\tlog.Warn().Err(err).Msgf(\"GetValue : NewMapFromID failed ID %d, re-looking up of map id\", b.MapID)\n\t\ttmpBPF, err := b.BPFProg.GetBPFMap(b.Name)\n\t\tif err != nil {\n\t\t\tlog.Warn().Err(err).Msgf(\"GetValue: Update new map ID %d\", tmpBPF.MapID)\n\t\t\treturn 0\n\t\t}\n\t\tlog.Info().Msgf(\"GetValue: Update new map ID %d\", tmpBPF.MapID)\n\t\tb.MapID = tmpBPF.MapID\n\t\tebpfMap, err = ebpf.NewMapFromID(b.MapID)\n\t\tif err != nil {\n\t\t\tlog.Warn().Err(err).Msgf(\"GetValue : retry of NewMapFromID failed ID %d\", b.MapID)\n\t\t\treturn 0\n\t\t}\n\t}\n\tdefer ebpfMap.Close()\n\n\tvar value int64\n\tif err = ebpfMap.Lookup(unsafe.Pointer(&b.key), unsafe.Pointer(&value)); err != nil {\n\t\tlog.Warn().Err(err).Msgf(\"GetValue Lookup failed : Name %s ID %d\", b.Name, b.MapID)\n\t\treturn 0\n\t}\n\n\tvar retVal float64\n\tswitch b.aggregator {\n\tcase \"scalar\":\n\t\tretVal = float64(value)\n\tcase \"max-rate\":\n\t\tb.Values = b.Values.Next()\n\t\tb.Values.Value = math.Abs(float64(float64(value) - b.lastValue))\n\t\tb.lastValue = float64(value)\n\t\tretVal = b.MaxValue()\n\tcase \"avg\":\n\t\tb.Values.Value = value\n\t\tb.Values = b.Values.Next()\n\t\tretVal = b.AvgValue()\n\tdefault:\n\t\tlog.Warn().Msgf(\"unsupported aggregator %s and value %d\", b.aggregator, value)\n\t}\n\n\treturn retVal\n}", "func lookUpIdx(scaledValue int) int {\n\tscaledValue32 := int32(scaledValue)\n\tif scaledValue32 < maxArrayValue { //constant\n\t\treturn val2Bucket[scaledValue]\n\t}\n\tfor i := maxArrayValueIndex; i < numValues; i++ {\n\t\tif histogramBucketValues[i] > scaledValue32 {\n\t\t\treturn i\n\t\t}\n\t}\n\tlog.Fatalf(\"never reached/bug\")\n\treturn 0\n}", "func (bt *BufferedThing) batchProcess() {\n\tfor {\n\n\t\t// sleep for an interval\n\t\ttime.Sleep(time.Duration(5) * time.Second)\n\n\t\t// declare some slices outside of our DB query, so that we can use\n\t\t// these values in subsequent queries.\n\t\tvar keys []Key\n\t\tvar values []Value\n\n\t\t// Read up to MaxBatch keys and values from boltdb\n\t\terr := bt.DB.View(func(tx *bolt.Tx) error {\n\t\t\tbkt := tx.Bucket([]byte(bktName))\n\t\t\tcur := bkt.Cursor()\n\n\t\t\tcount := 0\n\n\t\t\t// Scan from the first-sorted key in our bucket\n\t\t\tfor k, v := cur.First(); k != nil; k, v = cur.Next() {\n\t\t\t\tif k == nil {\n\t\t\t\t\tfmt.Println(\"initial key was nil\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\t// add to our slices\n\t\t\t\tkeys = append(keys, Key(k))\n\t\t\t\tvalues = append(values, Value(v))\n\n\t\t\t\tcount++\n\t\t\t\tif count >= bt.MaxBatch {\n\t\t\t\t\tfmt.Println(\"max reached\")\n\t\t\t\t\t// we've already got N keys/values in our slices, so we\n\t\t\t\t\t// simply return from our query here.\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t// We return here if we had less than MaxBatch keys in our bucket.\n\t\t\t// E.g., we scanned all of them.\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\", err.Error())\n\t\t\tpanic(\"couldn't read from bolt? we die now\")\n\t\t}\n\n\t\t// Make sure the world makes sense. We probably don't need to do this.\n\t\tif len(keys) != len(values) {\n\t\t\tpanic(\"expected 1:1 key to value\")\n\t\t}\n\n\t\t// Make sure we have at least 1 k-v pair. We definitely NEED to do this.\n\t\tif len(keys) < 1 {\n\t\t\tfmt.Println(\"no keys/values; skipping processing\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Now we do our fake processing. Here we'd send to some API or database.\n\t\tprocess(values)\n\n\t\t// We processed our stuff! Remove the just-processed keys/values from\n\t\t// boltdb. We can rely on the UUIDs in the keys slice to delete only\n\t\t// the successfully processed keys.\n\t\terr = bt.DB.Update(func(tx *bolt.Tx) error {\n\t\t\tbkt := tx.Bucket([]byte(bktName))\n\t\t\tfor _, k := range keys {\n\t\t\t\tif err := bkt.Delete([]byte(k)); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"delete failed: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\", err)\n\t\t\tpanic(\"could not delete processed keys\")\n\t\t}\n\n\t\t// Monitor how many messages are left in our queue. If we're keeping\n\t\t// pace with incoming messages, we will keep this number hovering around\n\t\t// zero.\n\t\terr = bt.DB.View(func(tx *bolt.Tx) error {\n\t\t\tbkt := tx.Bucket([]byte(bktName))\n\t\t\tstats := bkt.Stats()\n\t\t\tfmt.Printf(\"keys in boltdb processing queue: %v\\n\", stats.KeyN)\n\t\t\treturn nil\n\t\t})\n\t}\n}", "func BenchmarkStoreBig_numItems1B_keySize20_valSize0_batchSize100000(b *testing.B) {\n\tbenchmarkStore(b, benchStoreSpec{\n\t\tnumItems: 1000000000, keySize: 20, valSize: 0, batchSize: 100000,\n\t})\n}", "func (ht *HashTable) growBucket(bucket int) {\n\tht.EnsureSize(BUCKET_SIZE)\n\tlastBucketAddr := ht.lastBucket(bucket) * BUCKET_SIZE\n\tbinary.PutVarint(ht.Buf[lastBucketAddr:lastBucketAddr+10], int64(ht.numBuckets))\n\tht.Used += BUCKET_SIZE\n\tht.numBuckets++\n}", "func benchmarkVals() [2][]byte {\n\treturn [2][]byte{\n\t\thexToBytes(\"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364143\"),\n\t\thexToBytes(\"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364144\"),\n\t}\n}", "func (conn *ConnWithParameters) bucketPoints(rawPt Point) {\n\n\t// Truncate each item in batch\n\t// Split float by decimal\n\tlatSlice := strings.SplitAfter(rawPt.Lat, \".\")\n\tlngSlice := strings.SplitAfter(rawPt.Lng, \".\")\n\n\t// Truncate second half of slices\n\tlatSlice[1] = conn.truncate(latSlice[1])\n\tlngSlice[1] = conn.truncate(lngSlice[1])\n\n\t//check for truncating edge case\n\tif strings.Contains(latSlice[0], \"-0.\") {\n\t\tlatSlice = conn.checkZero(latSlice)\n\t}\n\tif strings.Contains(lngSlice[0], \"-0.\") {\n\t\tlngSlice = conn.checkZero(lngSlice)\n\t}\n\n\t// Combine the split strings together\n\tlat := strings.Join(latSlice, \"\")\n\tlng := strings.Join(lngSlice, \"\")\n\n\t//create bucket hash\n\tbucket := lat + \":\" + lng\n\n\t//create point\n\tpt := Latlng{\n\t\tCoords: Point{\n\t\t\tLat: lat,\n\t\t\tLng: lng,\n\t\t},\n\t\tCount: 1,\n\t}\n\n\t// Bucketing\n\t// check if bucket exists\n\t// if it does exists, increase the count\n\t_, contains := conn.batchMap[bucket]\n\tif contains {\n\t\tvalue := conn.batchMap[bucket] //get the value of the bucket\n\n\t\tvalue.Count++ //increase the count\n\n\t\tconn.batchMap[bucket] = value //add the new count to the point\n\n\t} else { //otherwise, add the point with the count\n\t\tconn.batchMap[bucket] = pt\n\t}\n}", "func NewTimeBucket(opcode uint64, numOpcodeBits, numValueBits int) TimeBucket {\n\treturn TimeBucket{\n\t\topcode: opcode,\n\t\tnumOpcodeBits: numOpcodeBits,\n\t\tnumValueBits: numValueBits,\n\t\tmin: -(1 << uint(numValueBits-1)),\n\t\tmax: (1 << uint(numValueBits-1)) - 1,\n\t}\n}", "func (tes *TimeEncodingScheme) Buckets() []TimeBucket { return tes.buckets }", "func (b Bucket) splitBucket(splitPoint, lowerBound int64) (Bucket, Bucket) {\n\tupperBound := (int64)(*b.UpperBound.(*tree.DInt))\n\n\t// The bucket size calculation has a -1 because NumRange does not\n\t// include values equal to UpperBound.\n\tbucketSize := upperBound - lowerBound - 1\n\tif bucketSize <= 0 {\n\t\tpanic(\"empty bucket should have been skipped\")\n\t}\n\n\tif splitPoint >= upperBound || splitPoint <= lowerBound {\n\t\tpanic(fmt.Sprintf(\"splitPoint (%d) must be between UpperBound (%d) and lowerBound (%d)\",\n\t\t\tsplitPoint, upperBound, lowerBound))\n\t}\n\n\t// Make the lower bucket.\n\tlowerMatchSize := splitPoint - lowerBound - 1\n\tlowerNumRange := (int64)(float64(b.NumRange) * float64(lowerMatchSize) / float64(bucketSize))\n\tlowerNumEq := (int64)(float64(b.NumRange) / float64(bucketSize))\n\tbucLower := Bucket{NumEq: lowerNumEq, NumRange: lowerNumRange, UpperBound: makeDatum(splitPoint)}\n\n\t// Make the upper bucket.\n\tupperMatchSize := upperBound - splitPoint - 1\n\tbucUpper := b\n\tbucUpper.NumRange = (int64)(float64(b.NumRange) * float64(upperMatchSize) / float64(bucketSize))\n\n\treturn bucLower, bucUpper\n}", "func getBucketScore(bkts []bucket, totalCount float64, id int) bucketScore {\n\tpreCount, count := float64(bkts[id-1].Count), float64(bkts[id].Count)\n\t// do not merge if the result bucket is too large\n\tif (preCount + count) > maxBucketFraction*totalCount {\n\t\treturn bucketScore{id, math.MaxFloat64}\n\t}\n\t// Merge them if the result bucket is already too small.\n\tif (preCount + count) < minBucketFraction*totalCount {\n\t\treturn bucketScore{id, 0}\n\t}\n\tlow, mid, high := bkts[id-1].Lower, bkts[id-1].Upper, bkts[id].Upper\n\t// If we choose to merge, err is the absolute estimate error for the previous bucket.\n\terr := calcFraction4Datums(low, high, mid)*(preCount+count) - preCount\n\treturn bucketScore{id, math.Abs(err / (preCount + count))}\n}", "func TestReadRegistryStatsNoDecay(t *testing.T) {\n\tdecay := 1.0\n\tpercentile := 0.5\n\tinterval := time.Millisecond\n\n\t// Add 0ms measurement. This results in the following bucket.\n\t// pos: [x]\n\t// est: [1]\n\t// count: [1]\n\t// The 50th percentile should be 1.\n\tbs := newReadRegistryStats(0, interval, decay, percentile)\n\terr := bs.AddDatum(0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif bs.Estimate() != time.Millisecond {\n\t\tt.Fatal(\"wrong measurement\", bs.Estimate())\n\t}\n\tif len(bs.staticBuckets) != 1 {\n\t\tt.Fatal(\"wrong number of buckets\", len(bs.staticBuckets))\n\t}\n\tif bs.currentPosition != 0 {\n\t\tt.Fatal(\"wrong position\", bs.currentPosition)\n\t}\n\n\t// Add interval measurement. This results in the following buckets.\n\t// pos: [ x]\n\t// est: [1, 2]\n\t// count: [0, 1]\n\t// The 50th percentile should be 2.\n\tbs = newReadRegistryStats(interval, interval, decay, percentile)\n\terr = bs.AddDatum(interval)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif bs.Estimate() != 2*time.Millisecond {\n\t\tt.Fatal(\"wrong measurement\", bs.Estimate())\n\t}\n\tif len(bs.staticBuckets) != 2 {\n\t\tt.Fatal(\"wrong number of buckets\", len(bs.staticBuckets))\n\t}\n\tif bs.currentPosition != 1 {\n\t\tt.Fatal(\"wrong position\", bs.currentPosition)\n\t}\n\n\t// Add larger than interval measurement.\n\t// pos: [ x]\n\t// est: [1, 2, 3]\n\t// count: [0, 0, 1]\n\t// The 50th percentile should be 3.\n\tbs = newReadRegistryStats(2*interval, interval, decay, percentile)\n\terr = bs.AddDatum(2 * interval)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif bs.Estimate() != 3*interval {\n\t\tt.Fatal(\"wrong measurement\", bs.Estimate())\n\t}\n\tif len(bs.staticBuckets) != 3 {\n\t\tt.Fatal(\"wrong number of buckets\", len(bs.staticBuckets))\n\t}\n\tif bs.currentPosition != 2 {\n\t\tt.Fatal(\"wrong position\", bs.currentPosition)\n\t}\n\n\t// Add measurements 0..99 exactly once.\n\t// pos: [ x]\n\t// est: [1, 2, ..., 100]\n\t// count: [1, 1, ..., 1]\n\t// The 50th percentile should be 50ms.\n\tbs = newReadRegistryStats(99*time.Millisecond, interval, decay, percentile)\n\tfor i := 0; i <= 99; i++ {\n\t\terr = bs.AddDatum(time.Duration(i) * time.Millisecond)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tif bs.Estimate() != 50*time.Millisecond {\n\t\tt.Fatal(\"wrong measurement\", bs.Estimate())\n\t}\n\tif len(bs.staticBuckets) != 100 {\n\t\tt.Fatal(\"wrong number of buckets\", len(bs.staticBuckets))\n\t}\n\tif bs.currentPosition != 49 {\n\t\tt.Fatal(\"wrong position\", bs.currentPosition)\n\t}\n\n\t// Add 10 measurements for 0, 9 for 1, 8 for 2 and so on.\n\t// pos: [ x ]\n\t// est: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\t// count: [9, 8, 7, 6, 5, 4, 3, 2, 1]\n\t// The total is 45 and 50% of that is 22.5. So the smallest number where 50%\n\t// of values are smaller than us is at index 3 where the smaller items sum\n\t// up to 35. Index 2 means we are in the 3-4ms bucket. So the result is 4ms.\n\tbs = newReadRegistryStats(9*time.Millisecond, interval, decay, percentile)\n\tfor i := 0; i < 10; i++ {\n\t\tfor j := 0; j < 10-i; j++ {\n\t\t\terr = bs.AddDatum(time.Duration(i) * time.Millisecond)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\tif bs.Estimate() != 4*time.Millisecond {\n\t\tt.Fatal(\"wrong measurement\", bs.Estimate())\n\t}\n\tif len(bs.staticBuckets) != 10 {\n\t\tt.Fatal(\"wrong number of buckets\", len(bs.staticBuckets))\n\t}\n\tif bs.currentPosition != 3 {\n\t\tt.Fatal(\"wrong position\", bs.currentPosition)\n\t}\n}", "func NewBucket(tokens uint64) *Bucket {\n\treturn &Bucket{Added: float64(tokens)}\n}", "func (h *hashTable) insert(val []byte) {\n\tif h.search(val) {\n\t\treturn\n\t}\n\tif len(h.bucketSlice) == 0 {\n\t\th.bucketSlice = append(h.bucketSlice, newBucket())\n\t}\n\tprobeIdx := hashFunc(val) % uint32(bucketCnt)\n\tisInserted := false\nLoop:\n\tfor _, bucket := range h.bucketSlice {\n\t\t// if the bucket is already full, skip it\n\t\tif bucket.wrapped {\n\t\t\tcontinue\n\t\t}\n\t\t// if the index is not taken yet, map it\n\t\tif bucket.data[probeIdx] == nil {\n\t\t\tbucket.data[probeIdx] = val\n\t\t\tisInserted = true\n\t\t\tbreak\n\t\t}\n\t\t// linear probe\n\t\tfor idx, elem := range bucket.data {\n\t\t\tif uint32(idx) == probeIdx {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif elem == nil {\n\t\t\t\tbucket.data[idx] = val\n\t\t\t\tisInserted = true\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t\tbucket.wrapped = true\n\t}\n\tif !isInserted {\n\t\tnb := newBucket()\n\t\tnb.data[probeIdx] = val\n\t\th.bucketSlice = append(h.bucketSlice, nb)\n\t}\n}", "func NewCachingBucket(b objstore.Bucket, cfg *cache.CachingBucketConfig, logger log.Logger, reg prometheus.Registerer) (*CachingBucket, error) {\n\tif b == nil {\n\t\treturn nil, errors.New(\"bucket is nil\")\n\t}\n\n\tcb := &CachingBucket{\n\t\tBucket: b,\n\t\tcfg: cfg,\n\t\tlogger: logger,\n\n\t\toperationConfigs: map[string][]*cache.OperationConfig{},\n\n\t\trequestedGetRangeBytes: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"thanos_store_bucket_cache_getrange_requested_bytes_total\",\n\t\t\tHelp: \"Total number of bytes requested via GetRange.\",\n\t\t}, []string{\"config\"}),\n\t\tfetchedGetRangeBytes: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"thanos_store_bucket_cache_getrange_fetched_bytes_total\",\n\t\t\tHelp: \"Total number of bytes fetched because of GetRange operation. Data from bucket is then stored to cache.\",\n\t\t}, []string{\"origin\", \"config\"}),\n\t\trefetchedGetRangeBytes: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"thanos_store_bucket_cache_getrange_refetched_bytes_total\",\n\t\t\tHelp: \"Total number of bytes re-fetched from storage because of GetRange operation, despite being in cache already.\",\n\t\t}, []string{\"origin\", \"config\"}),\n\n\t\toperationRequests: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"thanos_store_bucket_cache_operation_requests_total\",\n\t\t\tHelp: \"Number of requested operations matching given config.\",\n\t\t}, []string{\"operation\", \"config\"}),\n\t\toperationHits: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{\n\t\t\tName: \"thanos_store_bucket_cache_operation_hits_total\",\n\t\t\tHelp: \"Number of operations served from cache for given config.\",\n\t\t}, []string{\"operation\", \"config\"}),\n\t}\n\n\tfor op, names := range cfg.AllConfigNames() {\n\t\tfor _, n := range names {\n\t\t\tcb.operationRequests.WithLabelValues(op, n)\n\t\t\tcb.operationHits.WithLabelValues(op, n)\n\n\t\t\tif op == objstore.OpGetRange {\n\t\t\t\tcb.requestedGetRangeBytes.WithLabelValues(n)\n\t\t\t\tcb.fetchedGetRangeBytes.WithLabelValues(originCache, n)\n\t\t\t\tcb.fetchedGetRangeBytes.WithLabelValues(originBucket, n)\n\t\t\t\tcb.refetchedGetRangeBytes.WithLabelValues(originCache, n)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cb, nil\n}", "func main() {\n\t// get a bucket and mc.Client connection\n\tbucket, err := getTestConnection(\"default\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// start upr feed\n\tfeed, err := bucket.StartUprFeed(\"index\" /*name*/, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i := 0; i < vbcount; i++ {\n\t\terr := feed.UprRequestStream(\n\t\t\tuint16(i) /*vbno*/, uint16(0) /*opaque*/, 0 /*flag*/, 0, /*vbuuid*/\n\t\t\t0 /*seqStart*/, 0xFFFFFFFFFFFFFFFF /*seqEnd*/, 0 /*snaps*/, 0)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err.Error())\n\t\t}\n\t}\n\n\tvbseqNo := receiveMutations(feed, 20000)\n\n\tvbList := make([]uint16, 0)\n\tfor i := 0; i < vbcount; i++ {\n\t\tvbList = append(vbList, uint16(i))\n\t}\n\tfailoverlogMap, err := bucket.GetFailoverLogs(vbList)\n\tif err != nil {\n\t\tlog.Printf(\" error in failover log request %s\", err.Error())\n\n\t}\n\n\t// get a bucket and mc.Client connection\n\tbucket1, err := getTestConnection(\"default\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// add mutations to the bucket\n\tvar mutationCount = 5000\n\taddKVset(bucket1, mutationCount)\n\n\tlog.Println(\"Restarting ....\")\n\tfeed, err = bucket.StartUprFeed(\"index\" /*name*/, 0)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor i := 0; i < vbcount; i++ {\n\t\tlog.Printf(\"Vbucket %d High sequence number %d, Snapshot end sequence %d\", i, vbseqNo[i][0], vbseqNo[i][1])\n\t\tfailoverLog := failoverlogMap[uint16(i)]\n\t\terr := feed.UprRequestStream(\n\t\t\tuint16(i) /*vbno*/, uint16(0) /*opaque*/, 0, /*flag*/\n\t\t\tfailoverLog[0][0], /*vbuuid*/\n\t\t\tvbseqNo[i][0] /*seqStart*/, 0xFFFFFFFFFFFFFFFF, /*seqEnd*/\n\t\t\t0 /*snaps*/, vbseqNo[i][1])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err.Error())\n\t\t}\n\t}\n\n\tvar e, f *memcached.UprEvent\n\tvar mutations int\nloop:\n\tfor {\n\t\tselect {\n\t\tcase f = <-feed.C:\n\t\tcase <-time.After(time.Second):\n\t\t\tbreak loop\n\t\t}\n\n\t\tif f.Opcode == gomemcached.UPR_MUTATION {\n\t\t\tvbseqNo[f.VBucket][0] = f.Seqno\n\t\t\te = f\n\t\t\tmutations += 1\n\t\t}\n\t}\n\n\tlog.Printf(\" got %d mutations\", mutations)\n\n\texptSeq := vbseqNo[e.VBucket][0] + 1\n\n\tif e.Seqno != exptSeq {\n\t\tfmt.Printf(\"Expected seqno %v, received %v\", exptSeq+1, e.Seqno)\n\t\t//panic(err)\n\t}\n\tfeed.Close()\n}", "func genValue(i int, ev *replication.BinlogEvent) []byte {\n\traw := ev.RawData\n\trowValueIndex := ev.Event.(*replication.RowsEvent).RowValueIndex\n\treturn raw[rowValueIndex[i]:rowValueIndex[i+1]] // 共享内存\n}", "func Benchmark_New_Vector_Tile_Proto_Geojson_2(b *testing.B) {\n\n\tbytevals, _ = ioutil.ReadFile(\"test_data/701_1637_12.pbf\")\n\ttileid = m.TileID{701, 1637, 12}\n\n\tb.ReportAllocs()\n\n\t// run the Fib function b.N times\n\tfor n := 0; n < b.N; n++ {\n\t\tmbutil.Convert_Vt_Bytes(bytevals, tileid)\n\t}\n}", "func bucketIndex(index int) int {\n\treturn (MaxRoutingTableSize - 1) - index\n}", "func testAggregation(t *testing.T, testCases []testCase, vals [][]float64) {\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalues, bounds := test.GenerateValuesAndBounds(vals, nil)\n\t\t\tboundStart := bounds.Start\n\t\t\tblock3 := test.NewUnconsolidatedBlockFromDatapoints(bounds, values)\n\t\t\tc, sink := executor.NewControllerWithSink(parser.NodeID(1))\n\n\t\t\tvar (\n\t\t\t\targs []interface{}\n\t\t\t\tbaseOp transform.Params\n\t\t\t\terr error\n\t\t\t)\n\n\t\t\tif tt.opType == QuantileType {\n\t\t\t\targs = []interface{}{0.2, 5 * time.Minute}\n\t\t\t\tbaseOp, err = NewQuantileOp(args, tt.opType)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\targs = []interface{}{5 * time.Minute}\n\t\t\t\tbaseOp, err = NewAggOp(args, tt.opType)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\n\t\t\tnode := baseOp.Node(c, transformtest.Options(t, transform.OptionsParams{\n\t\t\t\tTimeSpec: transform.TimeSpec{\n\t\t\t\t\tStart: boundStart.Add(-2 * bounds.Duration),\n\t\t\t\t\tEnd: bounds.End(),\n\t\t\t\t\tStep: time.Second,\n\t\t\t\t},\n\t\t\t}))\n\t\t\tbNode := node.(*baseNode)\n\t\t\terr = node.Process(models.NoopQueryContext(), parser.NodeID(0), block3)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, sink.Values, 0, \"nothing processed yet\")\n\t\t\tb, exists := bNode.cache.get(boundStart)\n\t\t\tassert.True(t, exists, \"block cached for future\")\n\t\t\t_, err = b.StepIter()\n\t\t\tassert.NoError(t, err)\n\n\t\t\toriginal := values[0][0]\n\t\t\tvalues[0][0] = math.NaN()\n\t\t\tblock1 := test.NewUnconsolidatedBlockFromDatapoints(models.Bounds{\n\t\t\t\tStart: bounds.Start.Add(-2 * bounds.Duration),\n\t\t\t\tDuration: bounds.Duration,\n\t\t\t\tStepSize: bounds.StepSize,\n\t\t\t}, values)\n\n\t\t\tvalues[0][0] = original\n\t\t\terr = node.Process(models.NoopQueryContext(), parser.NodeID(0), block1)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, sink.Values, 2, \"output from first block only\")\n\t\t\ttest.EqualsWithNansWithDelta(t, tt.afterBlockOne[0], sink.Values[0], 0.0001)\n\t\t\ttest.EqualsWithNansWithDelta(t, tt.afterBlockOne[1], sink.Values[1], 0.0001)\n\t\t\t_, exists = bNode.cache.get(boundStart)\n\t\t\tassert.True(t, exists, \"block still cached\")\n\t\t\t_, exists = bNode.cache.get(boundStart.Add(-1 * bounds.Duration))\n\t\t\tassert.False(t, exists, \"block cached\")\n\n\t\t\tblock2 := test.NewUnconsolidatedBlockFromDatapoints(models.Bounds{\n\t\t\t\tStart: bounds.Start.Add(-1 * bounds.Duration),\n\t\t\t\tDuration: bounds.Duration,\n\t\t\t\tStepSize: bounds.StepSize,\n\t\t\t}, values)\n\n\t\t\terr = node.Process(models.NoopQueryContext(), parser.NodeID(0), block2)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, sink.Values, 6, \"output from all 3 blocks\")\n\t\t\ttest.EqualsWithNansWithDelta(t, tt.afterBlockOne[0], sink.Values[0], 0.0001)\n\t\t\ttest.EqualsWithNansWithDelta(t, tt.afterBlockOne[1], sink.Values[1], 0.0001)\n\t\t\texpectedOne := tt.afterAllBlocks[0]\n\t\t\texpectedTwo := tt.afterAllBlocks[1]\n\t\t\ttest.EqualsWithNansWithDelta(t, expectedOne, sink.Values[2], 0.0001)\n\t\t\ttest.EqualsWithNansWithDelta(t, expectedTwo, sink.Values[3], 0.0001)\n\t\t\t_, exists = bNode.cache.get(bounds.Previous(2).Start)\n\t\t\tassert.False(t, exists, \"block removed from cache\")\n\t\t\t_, exists = bNode.cache.get(bounds.Previous(1).Start)\n\t\t\tassert.False(t, exists, \"block not cached\")\n\t\t\t_, exists = bNode.cache.get(bounds.Start)\n\t\t\tassert.False(t, exists, \"block removed from cache\")\n\t\t\tblks, err := bNode.cache.multiGet(bounds.Previous(2), 3, false)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, blks, 0)\n\t\t})\n\t}\n}", "func AsFloat64Between(b Bucket, k string, min, max float64) float64 {\n\treturn asFloat(b, k, 64, min, max)\n}", "func TestBucket(t *testing.T) {\n\tt.Parallel()\n\n\tb := newBucket()\n\n\tpeers := make([]peer.ID, 100)\n\tfor i := 0; i < 100; i++ {\n\t\tpeers[i] = test.RandPeerIDFatal(t)\n\t\tb.pushFront(&PeerInfo{peers[i], PeerStateActive})\n\t}\n\n\tlocal := test.RandPeerIDFatal(t)\n\tlocalID := ConvertPeerID(local)\n\n\tinfos := b.peers()\n\trequire.Len(t, infos, 100)\n\n\ti := rand.Intn(len(peers))\n\tp := b.getPeer(peers[i])\n\trequire.NotNil(t, p)\n\trequire.Equal(t, peers[i], p.Id)\n\trequire.Equal(t, PeerStateActive, p.State)\n\n\t// mark as missing\n\tp.State = PeerStateMissing\n\tp = b.getPeer(peers[i])\n\trequire.NotNil(t, p)\n\trequire.Equal(t, PeerStateMissing, p.State)\n\n\tspl := b.split(0, ConvertPeerID(local))\n\tllist := b.list\n\tfor e := llist.Front(); e != nil; e = e.Next() {\n\t\tp := ConvertPeerID(e.Value.(*PeerInfo).Id)\n\t\tcpl := CommonPrefixLen(p, localID)\n\t\tif cpl > 0 {\n\t\t\tt.Fatalf(\"split failed. found id with cpl > 0 in 0 bucket\")\n\t\t}\n\t}\n\n\trlist := spl.list\n\tfor e := rlist.Front(); e != nil; e = e.Next() {\n\t\tp := ConvertPeerID(e.Value.(*PeerInfo).Id)\n\t\tcpl := CommonPrefixLen(p, localID)\n\t\tif cpl == 0 {\n\t\t\tt.Fatalf(\"split failed. found id with cpl == 0 in non 0 bucket\")\n\t\t}\n\t}\n}", "func (objID *ObjID) Bucket(numBuckets int) int {\n\tvar tempByte byte;\n\n\tfor _, b := range objID.Key {\n\t\ttempByte = tempByte ^ b\n\t}\n\tbucket := int(tempByte) % numBuckets\n\treturn bucket\n}", "func (bit *boundedIterator) RangeValues(interval metric.Interval) []model.SamplePair {\n\tif interval.NewestInclusive < bit.start {\n\t\treturn []model.SamplePair{}\n\t}\n\tif interval.OldestInclusive < bit.start {\n\t\tinterval.OldestInclusive = bit.start\n\t}\n\treturn bit.it.RangeValues(interval)\n}", "func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error {\n\tkind := desc.NumberKind()\n\tasFloat := number.CoerceToFloat64(kind)\n\n\tbucketID := len(c.boundaries)\n\tfor i, boundary := range c.boundaries {\n\t\tif asFloat < boundary {\n\t\t\tbucketID = i\n\t\t\tbreak\n\t\t}\n\t}\n\t// Note: Binary-search was compared using the benchmarks. The following\n\t// code is equivalent to the linear search above:\n\t//\n\t// bucketID := sort.Search(len(c.boundaries), func(i int) bool {\n\t// return asFloat < c.boundaries[i]\n\t// })\n\t//\n\t// The binary search wins for very large boundary sets, but\n\t// the linear search performs better up through arrays between\n\t// 256 and 512 elements, which is a relatively large histogram, so we\n\t// continue to prefer linear search.\n\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.state.count++\n\tc.state.sum.AddNumber(kind, number)\n\tc.state.bucketCounts[bucketID]++\n\n\treturn nil\n}", "func sm2P256FromBig(X *sm2P256FieldElement, a *big.Int) {\n\tx := new(big.Int).Lsh(a, 257)\n\tx.Mod(x, sm2P256.P)\n\tfor i := 0; i < 9; i++ {\n\t\tif bits := x.Bits(); len(bits) > 0 {\n\t\t\tX[i] = uint32(bits[0]) & bottom29Bits\n\t\t} else {\n\t\t\tX[i] = 0\n\t\t}\n\t\tx.Rsh(x, 29)\n\t\ti++\n\t\tif i == 9 {\n\t\t\tbreak\n\t\t}\n\t\tif bits := x.Bits(); len(bits) > 0 {\n\t\t\tX[i] = uint32(bits[0]) & bottom28Bits\n\t\t} else {\n\t\t\tX[i] = 0\n\t\t}\n\t\tx.Rsh(x, 28)\n\t}\n}", "func TestMapRange(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\tyears, err := bx.New([]byte(\"years\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert in `years` bucket\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"1970\"), []byte(\"70\")},\n\t\t{[]byte(\"1975\"), []byte(\"75\")},\n\t\t{[]byte(\"1980\"), []byte(\"80\")},\n\t\t{[]byte(\"1985\"), []byte(\"85\")},\n\t\t{[]byte(\"1990\"), []byte(\"90\")}, // min = 1990\n\t\t{[]byte(\"1995\"), []byte(\"95\")}, // min < 1995 < max\n\t\t{[]byte(\"2000\"), []byte(\"00\")}, // max = 2000\n\t\t{[]byte(\"2005\"), []byte(\"05\")},\n\t\t{[]byte(\"2010\"), []byte(\"10\")},\n\t}\n\n\t// Insert 'em.\n\tif err := years.Insert(items); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Time range to map over.\n\tmin := []byte(\"1990\")\n\tmax := []byte(\"2000\")\n\n\t// Expected items within time range: 1990 <= key <= 2000.\n\texpected := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"1990\"), []byte(\"90\")}, // min = 1990\n\t\t{[]byte(\"1995\"), []byte(\"95\")}, // min < 1995 < max\n\t\t{[]byte(\"2000\"), []byte(\"00\")}, // max = 2000\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := years.MapRange(do, min, max); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tfor i, want := range expected {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func VPBROADCASTMB2Q(k, xyz operand.Op) { ctx.VPBROADCASTMB2Q(k, xyz) }", "func Solve(sizeBucketOne,\n\tsizeBucketTwo,\n\tgoalAmount int,\n\tstartBucket string) (goalBucket string,\n\tnumSteps,\n\totherBucketLevel int,\n\te error) {\n\n\tif sizeBucketOne == 0 || sizeBucketTwo == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid bucket size\")\n\t}\n\n\tif goalAmount == 0 {\n\t\treturn \"\", 0, 0, errors.New(\"invalid goal amount\")\n\t}\n\n\tif startBucket != \"one\" && startBucket != \"two\" {\n\t\treturn \"\", 0, 0, errors.New(\"invalid start bucket name\")\n\t}\n\n\tvar moves int\n\tvar lastPoured bool\n\n\tbucketOne := bucket{\n\t\tname: \"one\",\n\t\tsize: sizeBucketOne,\n\t}\n\n\tbucketTwo := bucket{\n\t\tname: \"two\",\n\t\tsize: sizeBucketTwo,\n\t}\n\n\tif startBucket == \"one\" {\n\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\tif goalAmount == bucketTwo.size {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t\t}\n\t}\n\n\tif startBucket == \"two\" {\n\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\tif goalAmount == bucketOne.size {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t\t}\n\t}\n\n\tfor goalAmount != bucketOne.current && goalAmount != bucketTwo.current {\n\t\tif bucketOne.current != 0 && bucketTwo.current != bucketTwo.size && !lastPoured {\n\t\t\tpourBucket(&bucketOne, &bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\t\tif bucketTwo.current != 0 && bucketOne.current != bucketOne.size && !lastPoured {\n\t\t\tpourBucket(&bucketTwo, &bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == bucketOne.size && bucketTwo.current != 0 {\n\t\t\temptyBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == bucketTwo.size && bucketOne.current != 0 {\n\t\t\temptyBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketOne.current == 0 && bucketTwo.size-bucketTwo.current != 0 {\n\t\t\tfillBucket(&bucketOne, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\tif bucketTwo.current == 0 && bucketOne.size-bucketOne.current != 0 {\n\t\t\tfillBucket(&bucketTwo, &moves, &lastPoured)\n\t\t\tcontinue\n\t\t}\n\n\t\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n\t}\n\n\tif goalAmount == bucketOne.current {\n\t\treturn bucketOne.name, moves, bucketTwo.current, nil\n\t}\n\n\tif goalAmount == bucketTwo.current {\n\t\treturn bucketTwo.name, moves, bucketOne.current, nil\n\t}\n\n\treturn \"\", 0, 0, errors.New(\"no solution\")\n\n}", "func GetPriceBucket(bid openrtb2.Bid, targetingData targetData) string {\n\tcpmStr := \"\"\n\tbucketMax := 0.0\n\tbucketMin := 0.0\n\tincrement := 0.0\n\n\tconfig := targetingData.priceGranularity //assign default price granularity\n\n\tif bidType, err := getMediaTypeForBid(bid); err == nil {\n\t\tif bidType == openrtb_ext.BidTypeBanner && targetingData.mediaTypePriceGranularity.Banner != nil {\n\t\t\tconfig = *targetingData.mediaTypePriceGranularity.Banner\n\t\t} else if bidType == openrtb_ext.BidTypeVideo && targetingData.mediaTypePriceGranularity.Video != nil {\n\t\t\tconfig = *targetingData.mediaTypePriceGranularity.Video\n\t\t} else if bidType == openrtb_ext.BidTypeNative && targetingData.mediaTypePriceGranularity.Native != nil {\n\t\t\tconfig = *targetingData.mediaTypePriceGranularity.Native\n\t\t}\n\t}\n\n\tprecision := *config.Precision\n\n\tcpm := bid.Price\n\tfor i := 0; i < len(config.Ranges); i++ {\n\t\tif config.Ranges[i].Max > bucketMax {\n\t\t\tbucketMax = config.Ranges[i].Max\n\t\t}\n\t\t// find what range cpm is in\n\t\tif cpm >= config.Ranges[i].Min && cpm <= config.Ranges[i].Max {\n\t\t\tincrement = config.Ranges[i].Increment\n\t\t\tbucketMin = config.Ranges[i].Min\n\t\t}\n\t}\n\n\tif cpm > bucketMax {\n\t\t// We are over max, just return that\n\t\tcpmStr = strconv.FormatFloat(bucketMax, 'f', precision, 64)\n\t} else if increment > 0 {\n\t\t// If increment exists, get cpm string value\n\t\tcpmStr = getCpmTarget(cpm, bucketMin, increment, precision)\n\t}\n\n\treturn cpmStr\n}", "func (self *CoreWorkload) buildValues(key string) KVMap {\n\tret := make(KVMap)\n\tvar data Binary\n\tfor _, fieldKey := range self.fieldNames {\n\t\tif self.dataIntegrity {\n\t\t\tdata = self.buildDeterministicValue(key, fieldKey)\n\t\t} else {\n\t\t\t// fill with random data\n\t\t\tdata = RandomBytes(self.fieldLengthGenerator.NextInt())\n\t\t}\n\t\tret[fieldKey] = data\n\t}\n\treturn ret\n}", "func TestKVRebStopStartKVOpsOnUpdateBucketOpOneByOne(t *testing.T) {\n\ttime.Sleep(5 * time.Second)\n\thandler := \"bucket_op_on_update\"\n\n\tflushFunctionAndBucket(handler)\n\ttime.Sleep(5 * time.Second)\n\tcreateAndDeployFunction(handler, handler, &commonSettings{})\n\n\ttime.Sleep(5 * time.Second)\n\n\trl := &rateLimit{\n\t\tlimit: true,\n\t\topsPSec: rlOpsPSec,\n\t\tcount: rlItemCount,\n\t\tstopCh: make(chan struct{}, 1),\n\t\tloop: true,\n\t}\n\n\tgo pumpBucketOps(opsType{count: rlItemCount}, rl)\n\n\twaitForDeployToFinish(handler)\n\tmetaStateDump()\n\n\taddNodeFromRest(\"https://127.0.0.1:19001\", \"kv\")\n\trebalanceFromRest([]string{\"\"})\n\ttime.Sleep(20 * time.Second)\n\trebalanceStop()\n\tmetaStateDump()\n\n\ttime.Sleep(10 * time.Second)\n\n\tmetaStateDump()\n\trebalanceFromRest([]string{\"\"})\n\twaitForRebalanceFinish()\n\tmetaStateDump()\n\n\taddNodeFromRest(\"https://127.0.0.1:19002\", \"kv\")\n\trebalanceFromRest([]string{\"127.0.0.1:19001\"})\n\twaitForRebalanceFinish()\n\tmetaStateDump()\n\n\trebalanceFromRest([]string{\"127.0.0.1:19002\"})\n\twaitForRebalanceFinish()\n\tmetaStateDump()\n\n\trl.stopCh <- struct{}{}\n\n\tflushFunctionAndBucket(handler)\n}", "func TestGetOrAddBurst(t *testing.T) {\n\t// testLock is used for guarding valConstructorCalls for purposes of\n\t// testing.\n\ttestLock := sync.Mutex{}\n\n\tvalConstructorCalls := 0\n\t// goodValConstructor simulates an \"expensive\" call by calculating the\n\t// Collatz Conjecture for a small input. The point is that the value\n\t// generated here will never be able to be optimized away by the compiler\n\t// (because its value cannot be precomputed by the compiler), guaranteeing\n\t// that some CPU cycles will be spent between the time we unlock the\n\t// testLock and the time we retrieve the computed value (all within the same\n\t// thread).\n\tgoodValConstructor := func(input int) func() (interface{}, error) {\n\t\treturn func() (interface{}, error) {\n\t\t\ttestLock.Lock()\n\t\t\tvalConstructorCalls++\n\t\t\ttestLock.Unlock()\n\t\t\tsteps := 0\n\t\t\tn := input\n\t\t\tmax := input\n\t\t\tfor n > 1 {\n\t\t\t\tif n > max {\n\t\t\t\t\tmax = n\n\t\t\t\t}\n\t\t\t\tif n&1 == 0 {\n\t\t\t\t\tn >>= 1\n\t\t\t\t} else {\n\t\t\t\t\tn *= 3\n\t\t\t\t\tn++\n\t\t\t\t}\n\t\t\t\tsteps++\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"(val)input=%d,steps=%d,max=%d\", input, steps, max), nil\n\t\t}\n\t}\n\n\tlruCache, err := NewLRUCache(1000, Callbacks{})\n\tif err != nil {\n\t\tt.Error(\"could not initialize lruCache\")\n\t}\n\n\tvalConstructorCalls = 0\n\tconst maxConcurrentRequests = 500\n\twg := sync.WaitGroup{}\n\n\t// Consider the case where all threads perform the same cache lookup.\n\texpectedVal := \"(val)input=3,steps=7,max=16\"\n\twg.Add(maxConcurrentRequests)\n\tfor i := 0; i < maxConcurrentRequests; i++ {\n\t\tgo func() {\n\t\t\t// Input of 3 for goodValConstructor will take 7 steps and reach a\n\t\t\t// maximum value of 16. We check this below.\n\t\t\tconstructedVal, _, err := lruCache.GetOrAdd(3, goodValConstructor(3))\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"could not fetch or construct value\")\n\t\t\t}\n\t\t\tif constructedVal != expectedVal {\n\t\t\t\tt.Errorf(\"expected constructed value '%v', got '%v'\", expectedVal, constructedVal)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n\t// Expect that we only invoked the goodValConstructor once. Notice how the\n\t// user of lruCache does not need to worry about locking. The cache is smart\n\t// enough to perform duplicate suppression on its own, so that the value is\n\t// constructed and written into the cache only once, no matter how many\n\t// concurrent threads attempt to access it.\n\tif valConstructorCalls != 1 {\n\t\tt.Errorf(\"Expected valConstructorCalls '1', got '%v'\", valConstructorCalls)\n\t}\n\tif lruCache.Len() != 1 {\n\t\tt.Errorf(\"Expected single cached element, got '%v'\", lruCache.Len())\n\t}\n\n\tvalConstructorCalls = 0\n\tlruCache.Purge()\n\n\t// Consider the case where all threads perform one of 5 different cache lookups.\n\twg.Add(maxConcurrentRequests)\n\tfor i := 0; i < maxConcurrentRequests; i++ {\n\t\tj := (i % 5) + 1\n\t\texpectedVal := \"\"\n\t\tgo func() {\n\t\t\tconstructedVal, _, err := lruCache.GetOrAdd(j, goodValConstructor(j))\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"could not fetch or construct value\")\n\t\t\t}\n\t\t\tswitch j {\n\t\t\tcase 1:\n\t\t\t\texpectedVal = \"(val)input=1,steps=0,max=1\"\n\t\t\tcase 2:\n\t\t\t\texpectedVal = \"(val)input=2,steps=1,max=2\"\n\t\t\tcase 3:\n\t\t\t\texpectedVal = \"(val)input=3,steps=7,max=16\"\n\t\t\tcase 4:\n\t\t\t\texpectedVal = \"(val)input=4,steps=2,max=4\"\n\t\t\tdefault:\n\t\t\t\texpectedVal = \"(val)input=5,steps=5,max=16\"\n\t\t\t}\n\t\t\tif constructedVal != expectedVal {\n\t\t\t\tt.Errorf(\"expected constructed value '%v', got '%v'\", expectedVal, constructedVal)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n\t// Only expect 5 valConstructor calls, because there are only 5 unique key lookups.\n\tif valConstructorCalls != 5 {\n\t\tt.Errorf(\"Expected valConstructorCalls '5', got '%v'\", valConstructorCalls)\n\t}\n\tif lruCache.Len() != 5 {\n\t\tt.Errorf(\"Expected 5 cached entries, got '%v'\", lruCache.Len())\n\t}\n}", "func DBBucketAddKeysValues(db *bolt.DB, bucketName string, kvmap map[string]string) error {\n\ttx, err := (*db).Begin(true)\n\tdefer tx.Rollback()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := tx.Bucket([]byte(bucketName))\n\tfor k, v := range kvmap {\n\t\tif err := b.Put([]byte(k), []byte(v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func makeBuckets(m *dto.Metric) map[string]interface{} {\n\tfields := make(map[string]interface{})\n\tfor _, b := range m.GetHistogram().Bucket {\n\t\tfields[fmt.Sprint(b.GetUpperBound())] = float64(b.GetCumulativeCount())\n\t}\n\treturn fields\n}", "func (t *WindowedThroughput) updateMaps() {\n\tcurrentIndex := t.indexGenerator.GetCurrentIndex()\n\tlookbackIndexes := t.indexGenerator.DurationToIndexes(t.LookbackFrequencyDuration)\n\taggregateCounts := t.countList.AggregateCounts(currentIndex, lookbackIndexes)\n\n\t// Apply the same aggregation algorithm as total throughput\n\t// Short circuit if no traffic\n\tt.numKeys = len(aggregateCounts)\n\tif t.numKeys == 0 {\n\t\t// no traffic during the last period.\n\t\tt.lock.Lock()\n\t\tdefer t.lock.Unlock()\n\t\tt.savedSampleRates = make(map[string]int)\n\t\treturn\n\t}\n\t// figure out our target throughput per key over the lookback window.\n\ttotalGoalThroughput := t.GoalThroughputPerSec * t.LookbackFrequencyDuration.Seconds()\n\t// floor the throughput but min should be 1 event per bucket per time period\n\tthroughputPerKey := math.Max(1, float64(totalGoalThroughput)/float64(t.numKeys))\n\t// for each key, calculate sample rate by dividing counted events by the\n\t// desired number of events\n\tnewSavedSampleRates := make(map[string]int)\n\tfor k, v := range aggregateCounts {\n\t\trate := int(math.Max(1, (float64(v) / float64(throughputPerKey))))\n\t\tnewSavedSampleRates[k] = rate\n\t}\n\t// save newly calculated sample rates\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tt.savedSampleRates = newSavedSampleRates\n}", "func BuildColumn(ctx context.Context, numBuckets, id int64, ndv int64, count int64, samples []types.Datum) (*Histogram, error) {\n\tif count == 0 {\n\t\treturn &Histogram{ID: id}, nil\n\t}\n\tsc := ctx.GetSessionVars().StmtCtx\n\terr := types.SortDatums(sc, samples)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\thg := &Histogram{\n\t\tID: id,\n\t\tNDV: ndv,\n\t\tBuckets: make([]Bucket, 1, numBuckets),\n\t}\n\tvaluesPerBucket := float64(count)/float64(numBuckets) + 1\n\n\t// As we use samples to build the histogram, the bucket number and repeat should multiply a factor.\n\tsampleFactor := float64(count) / float64(len(samples))\n\tndvFactor := float64(count) / float64(ndv)\n\tif ndvFactor > sampleFactor {\n\t\tndvFactor = sampleFactor\n\t}\n\tbucketIdx := 0\n\tvar lastCount int64\n\tfor i := int64(0); i < int64(len(samples)); i++ {\n\t\tcmp, err := hg.Buckets[bucketIdx].Value.CompareDatum(sc, samples[i])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\ttotalCount := float64(i+1) * sampleFactor\n\t\tif cmp == 0 {\n\t\t\t// The new item has the same value as current bucket value, to ensure that\n\t\t\t// a same value only stored in a single bucket, we do not increase bucketIdx even if it exceeds\n\t\t\t// valuesPerBucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\tif float64(hg.Buckets[bucketIdx].Repeats) == ndvFactor {\n\t\t\t\thg.Buckets[bucketIdx].Repeats = int64(2 * sampleFactor)\n\t\t\t} else {\n\t\t\t\thg.Buckets[bucketIdx].Repeats += int64(sampleFactor)\n\t\t\t}\n\t\t} else if totalCount-float64(lastCount) <= valuesPerBucket {\n\t\t\t// The bucket still have room to store a new item, update the bucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\thg.Buckets[bucketIdx].Value = samples[i]\n\t\t\thg.Buckets[bucketIdx].Repeats = int64(ndvFactor)\n\t\t} else {\n\t\t\tlastCount = hg.Buckets[bucketIdx].Count\n\t\t\t// The bucket is full, store the item in the next bucket.\n\t\t\tbucketIdx++\n\t\t\thg.Buckets = append(hg.Buckets, Bucket{\n\t\t\t\tCount: int64(totalCount),\n\t\t\t\tValue: samples[i],\n\t\t\t\tRepeats: int64(ndvFactor),\n\t\t\t})\n\t\t}\n\t}\n\treturn hg, nil\n}", "func (m *Metric) getMetricValues(wg *sync.WaitGroup, ctx context.Context) error {\n\tdefer wg.Done()\n\tvar parser fastjson.Parser\n\n\trespBytes, err := sendRequest(ctx, \"GET\", p8sAddr+\"/api/v1/query?query=\"+m.query, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := parser.ParseBytes(respBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar qVal, mtVal *fastjson.Value\n\tvar queue, val []byte\n\tresult := data.GetArray(\"data\", \"result\")\n\tif len(m.values) == 0 {\n\t\tm.values = make([]metricValue, len(result))\n\t}\n\tcnt := 0\n\tfor _, res := range result {\n\t\tqVal = res.Get(\"metric\", \"queue\")\n\t\tif qVal == nil {\n\t\t\tcontinue\n\t\t}\n\t\tmtVal = res.Get(\"value\", \"1\")\n\t\tif mtVal == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tqueue = qVal.GetStringBytes()\n\t\tval = mtVal.GetStringBytes()\n\n\t\tif string(val) == \"0\" {\n\t\t\tcontinue\n\t\t}\n\t\tm.values[cnt] = metricValue{\n\t\t\tvalue: string(val),\n\t\t\tqueue: string(queue),\n\t\t}\n\t\tcnt++\n\t}\n\n\treturn nil\n}", "func lttb(ss []model.SamplePair, t int) []model.SamplePair {\n\tsampled := []model.SamplePair{}\n\tif t >= len(ss) || t == 0 {\n\t\treturn ss\n\t}\n\n\t// Bucket size. Leave room for start and end data points\n\tbsize := float64((len(ss) - 2)) / float64(t-2)\n\ta, nexta := 0, 0\n\n\tsampled = append(sampled, ss[0])\n\n\tfor i := 0; i < t-2; i++ {\n\t\tavgRangeStart := (int)(math.Floor((float64(i+1) * bsize)) + 1)\n\t\tavgRangeEnd := (int)(math.Floor((float64(i+2))*bsize) + 1)\n\n\t\tif avgRangeEnd >= len(ss) {\n\t\t\tavgRangeEnd = len(ss)\n\t\t}\n\n\t\tavgRangeLength := (avgRangeEnd - avgRangeStart)\n\n\t\tavgX, avgY := 0.0, 0.0\n\n\t\tfor {\n\t\t\tif avgRangeStart >= avgRangeEnd {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tavgX += float64(ss[avgRangeStart].Timestamp)\n\t\t\tavgY += float64(ss[avgRangeStart].Value)\n\t\t\tavgRangeStart++\n\t\t}\n\n\t\tavgX /= float64(avgRangeLength)\n\t\tavgY /= float64(avgRangeLength)\n\n\t\trangeOffs := (int)(math.Floor((float64(i)+0)*bsize) + 1)\n\t\trangeTo := (int)(math.Floor((float64(i)+1)*bsize) + 1)\n\n\t\tpointAx := float64(ss[a].Timestamp)\n\t\tpointAy := float64(ss[a].Value)\n\n\t\tmaxArea := -1.0\n\n\t\tvar maxAreaPoint model.SamplePair\n\n\t\tfor {\n\t\t\tif rangeOffs >= rangeTo {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tarea := math.Abs((pointAx-avgX)*(float64(ss[rangeOffs].Value)-pointAy)-(pointAx-float64(ss[rangeOffs].Timestamp))*(avgY-pointAy)) * 0.5\n\n\t\t\tif area > maxArea {\n\t\t\t\tmaxArea = area\n\t\t\t\tmaxAreaPoint = ss[rangeOffs]\n\t\t\t\tnexta = rangeOffs\n\t\t\t}\n\t\t\trangeOffs++\n\t\t}\n\n\t\tsampled = append(sampled, maxAreaPoint)\n\t\ta = nexta\n\t}\n\n\tsampled = append(sampled, ss[len(ss)-1])\n\n\treturn sampled\n}", "func (h *Histogram) Export() *HistogramData {\n\tvar res HistogramData\n\tres.Count = h.Counter.Count\n\tres.Min = h.Counter.Min\n\tres.Max = h.Counter.Max\n\tres.Sum = h.Counter.Sum\n\tres.Avg = h.Counter.Avg()\n\tres.StdDev = h.Counter.StdDev()\n\tmultiplier := h.Divider\n\toffset := h.Offset\n\t// calculate the last bucket index\n\tlastIdx := -1\n\tfor i := numBuckets - 1; i >= 0; i-- {\n\t\tif h.Hdata[i] > 0 {\n\t\t\tlastIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastIdx == -1 {\n\t\treturn &res\n\t}\n\n\t// previous bucket value:\n\tprev := histogramBucketValues[0]\n\tvar total int64\n\tctrTotal := float64(h.Count)\n\t// export the data of each bucket of the histogram\n\tfor i := 0; i <= lastIdx; i++ {\n\t\tif h.Hdata[i] == 0 {\n\t\t\t// empty bucket: skip it but update prev which is needed for next iter\n\t\t\tif i < numValues {\n\t\t\t\tprev = histogramBucketValues[i]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tvar b Bucket\n\t\ttotal += int64(h.Hdata[i])\n\t\tif len(res.Data) == 0 {\n\t\t\t// First entry, start is min\n\t\t\tb.Start = h.Min\n\t\t} else {\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t}\n\t\tb.Percent = 100. * float64(total) / ctrTotal\n\t\tif i < numValues {\n\t\t\tcur := histogramBucketValues[i]\n\t\t\tb.End = multiplier*float64(cur) + offset\n\t\t\tprev = cur\n\t\t} else {\n\t\t\t// Last Entry\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t\tb.End = h.Max\n\t\t}\n\t\tb.Count = int64(h.Hdata[i])\n\t\tres.Data = append(res.Data, b)\n\t}\n\tres.Data[len(res.Data)-1].End = h.Max\n\treturn &res\n}", "func calcValue(bids map[types.BlockID]struct{}) uint32 {\n\tkeys := make([]types.BlockID, 0, len(bids))\n\tfor k := range bids {\n\t\tkeys = append(keys, k)\n\t}\n\n\tkeys = types.SortBlockIDs(keys)\n\n\t// calc\n\th := fnv.New32()\n\tfor i := 0; i < len(keys); i++ {\n\t\t_, err := h.Write(keys[i].Bytes())\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Could not calculate Beacon value. Hash write error=%v\", err)\n\t\t}\n\t}\n\t// update\n\tsum := h.Sum32()\n\treturn sum\n}", "func (ms HistogramBucketExemplar) Value() float64 {\n\treturn (*ms.orig).Value\n}", "func InitBucket() (b map[string]Bucket, err error) {\r\n\tvar (\r\n\t\titem Bucket\r\n\t)\r\n\tb = make(map[string]Bucket)\r\n\t// bucket test\r\n\titem.BucketName = \"test\"\r\n\titem.Property = 2\r\n\titem.KeyId = \"121bce6492eba701\"\r\n\titem.KeySecret = \"1eb80603e85842542f9736eb13b7e1\"\r\n\tb[\"test\"] = item\r\n\r\n\treturn\r\n}", "func ExampleBucket_MapRange() {\n\tbx, _ := buckets.Open(tempfile())\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t// Delete any existing bucket named \"years\".\n\tbx.Delete([]byte(\"years\"))\n\n\t// Create a new bucket named \"years\".\n\tyears, _ := bx.New([]byte(\"years\"))\n\n\t// Setup items to insert in `years` bucket\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"1970\"), []byte(\"70\")},\n\t\t{[]byte(\"1975\"), []byte(\"75\")},\n\t\t{[]byte(\"1980\"), []byte(\"80\")},\n\t\t{[]byte(\"1985\"), []byte(\"85\")},\n\t\t{[]byte(\"1990\"), []byte(\"90\")}, // min = 1990\n\t\t{[]byte(\"1995\"), []byte(\"95\")}, // min < 1995 < max\n\t\t{[]byte(\"2000\"), []byte(\"00\")}, // max = 2000\n\t\t{[]byte(\"2005\"), []byte(\"05\")},\n\t\t{[]byte(\"2010\"), []byte(\"10\")},\n\t}\n\n\t// Insert 'em.\n\tif err := years.Insert(items); err != nil {\n\t\tfmt.Printf(\"could not insert items in `years` bucket: %v\\n\", err)\n\t}\n\n\t// Time range to map over: 1990 <= key <= 2000.\n\tmin := []byte(\"1990\")\n\tmax := []byte(\"2000\")\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := years.MapRange(do, min, max); err != nil {\n\t\tfmt.Printf(\"could not map items within range: %v\\n\", err)\n\t}\n\n\tfor _, item := range results {\n\t\tfmt.Printf(\"%s -> %s\\n\", item.Key, item.Value)\n\t}\n\t// Output:\n\t// 1990 -> 90\n\t// 1995 -> 95\n\t// 2000 -> 00\n}", "func emptyBucket(input []int, value int) (int, int) {\n\tfor i, v := range input {\n\t\tif v == value {\n\t\t\tblocks := input[i]\n\t\t\tinput[i] = 0\n\t\t\treturn i, blocks\n\t\t}\n\t}\n\tlog.Fatalf(\"Cannot find memory bank with value %d\", value)\n\treturn -1, -1\n}", "func CreateB2Storage(accountID string, applicationKey string, bucket string, threads int) (storage *B2Storage, err error) {\n\n var clients []*B2Client\n\n for i := 0; i < threads; i++ {\n client := NewB2Client(accountID, applicationKey)\n\n err = client.AuthorizeAccount()\n if err != nil {\n return nil, err\n }\n\n err = client.FindBucket(bucket)\n if err != nil {\n return nil, err\n }\n\n clients = append(clients, client)\n }\n\n storage = &B2Storage {\n clients: clients,\n }\n return storage, nil\n}", "func (d *dataUsageCache) bucketsUsageInfo(buckets []BucketInfo) map[string]madmin.BucketUsageInfo {\n\tvar dst = make(map[string]madmin.BucketUsageInfo, len(buckets))\n\tfor _, bucket := range buckets {\n\t\te := d.find(bucket.Name)\n\t\tif e == nil {\n\t\t\tcontinue\n\t\t}\n\t\tflat := d.flatten(*e)\n\t\tbui := madmin.BucketUsageInfo{\n\t\t\tSize: uint64(flat.Size),\n\t\t\tObjectsCount: flat.Objects,\n\t\t\tObjectSizesHistogram: flat.ObjSizes.toMap(),\n\t\t}\n\t\tif flat.ReplicationStats != nil {\n\t\t\tbui.ReplicationPendingSize = flat.ReplicationStats.PendingSize\n\t\t\tbui.ReplicatedSize = flat.ReplicationStats.ReplicatedSize\n\t\t\tbui.ReplicationFailedSize = flat.ReplicationStats.FailedSize\n\t\t\tbui.ReplicationPendingCount = flat.ReplicationStats.PendingCount\n\t\t\tbui.ReplicationFailedCount = flat.ReplicationStats.FailedCount\n\t\t\tbui.ReplicaSize = flat.ReplicationStats.ReplicaSize\n\t\t}\n\t\tdst[bucket.Name] = bui\n\t}\n\treturn dst\n}", "func (n *Uint256) SquareVal(n2 *Uint256) *Uint256 {\n\t// Similar to multiplication, the general strategy employed here is:\n\t// 1) Calculate the 512-bit product of the two uint256s using standard\n\t// schoolbook multiplication.\n\t// 2) Reduce the result modulo 2^256.\n\t//\n\t// However, some optimizations are used versus naively calculating all\n\t// intermediate terms:\n\t// 1) Reuse the high 64 bits from the intermediate 128-bit products directly\n\t// since that is equivalent to shifting the result right by 64 bits.\n\t// 2) Ignore all of the products between individual digits that would\n\t// ordinarily be needed for the full 512-bit product when they are\n\t// guaranteed to result in values that fall in the half open interval\n\t// [2^256, 2^512) since they are all ≡ 0 (mod 2^256) given they are\n\t// necessarily multiples of it.\n\t// 3) Use native uint64s for the calculations involving the final digit of\n\t// the result (r3) because all overflow carries to bits >= 256 which, as\n\t// above, are all ≡ 0 (mod 2^256) and thus safe to discard.\n\t// 4) Use the fact the number is being multiplied by itself to take\n\t// advantage of symmetry to double the result of some individual products\n\t// versus calculating them again.\n\tvar r0, r1, r2, r3, c uint64\n\n\t// Terms resulting from the product of the first digit of the second number\n\t// by all digits of the first number except those that will be accounted for\n\t// later via symmetry.\n\tc, r0 = bits.Mul64(n2.n[0], n2.n[0])\n\tc, r1 = mulAdd64(n2.n[0], n2.n[1], c)\n\tc, r2 = mulAdd64(n2.n[0], n2.n[2], c)\n\tr3 = c\n\n\t// Terms resulting from the product of the second digit of the second number\n\t// by all digits of the first number except those that will be accounted for\n\t// later via symmetry and those that are guaranteed to be ≡ 0 (mod 2^256).\n\tc, r1 = mulAdd64(n2.n[1], n2.n[0], r1)\n\tc, r2 = mulAdd64Carry(n2.n[1], n2.n[1], r2, c)\n\tr3 += c\n\n\t// Terms resulting from the product of the third digit of the second number\n\t// by all digits of the first number except those that will be accounted for\n\t// later via symmetry and those that are guaranteed to be ≡ 0 (mod 2^256).\n\tc, r2 = mulAdd64(n2.n[2], n2.n[0], r2)\n\tr3 += c\n\n\t// Terms resulting from the product of the fourth digit of the second number\n\t// by all digits of the first number except those that are guaranteed to be\n\t// ≡ 0 (mod 2^256) and doubling those that were skipped earlier.\n\tr3 += 2 * (n2.n[0]*n2.n[3] + n2.n[1]*n2.n[2])\n\n\tn.n[0], n.n[1], n.n[2], n.n[3] = r0, r1, r2, r3\n\treturn n\n}", "func (d *dataUsageCache) bucketUsageInfo(bucket string) madmin.BucketUsageInfo {\n\te := d.find(bucket)\n\tif e == nil {\n\t\treturn madmin.BucketUsageInfo{}\n\t}\n\tflat := d.flatten(*e)\n\tbui := madmin.BucketUsageInfo{\n\t\tSize: uint64(flat.Size),\n\t\tObjectsCount: flat.Objects,\n\t\tObjectSizesHistogram: flat.ObjSizes.toMap(),\n\t}\n\tif flat.ReplicationStats != nil {\n\t\tbui.ReplicationPendingSize = flat.ReplicationStats.PendingSize\n\t\tbui.ReplicatedSize = flat.ReplicationStats.ReplicatedSize\n\t\tbui.ReplicationFailedSize = flat.ReplicationStats.FailedSize\n\t\tbui.ReplicationPendingCount = flat.ReplicationStats.PendingCount\n\t\tbui.ReplicationFailedCount = flat.ReplicationStats.FailedCount\n\t\tbui.ReplicaSize = flat.ReplicationStats.ReplicaSize\n\t}\n\treturn bui\n}", "func d2h(val uint64) (result *Key) {\n\tresult = new(Key)\n\tfor i := 0; val > 0; i++ {\n\t\tresult[i] = byte(val & 0xFF)\n\t\tval /= 256\n\t}\n\treturn\n}", "func TestMultiRangeScanWithMaxResults(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\ttestCases := []struct {\n\t\tsplitKeys []roachpb.Key\n\t\tkeys []roachpb.Key\n\t}{\n\t\t{[]roachpb.Key{roachpb.Key(\"m\")},\n\t\t\t[]roachpb.Key{roachpb.Key(\"a\"), roachpb.Key(\"z\")}},\n\t\t{[]roachpb.Key{roachpb.Key(\"h\"), roachpb.Key(\"q\")},\n\t\t\t[]roachpb.Key{roachpb.Key(\"b\"), roachpb.Key(\"f\"), roachpb.Key(\"k\"),\n\t\t\t\troachpb.Key(\"r\"), roachpb.Key(\"w\"), roachpb.Key(\"y\")}},\n\t}\n\n\tfor i, tc := range testCases {\n\t\ts, _, _ := serverutils.StartServer(t, base.TestServerArgs{})\n\t\tdefer s.Stopper().Stop()\n\t\tts := s.(*TestServer)\n\t\tretryOpts := base.DefaultRetryOptions()\n\t\tretryOpts.Closer = ts.stopper.ShouldQuiesce()\n\t\tds := kv.NewDistSender(&kv.DistSenderContext{\n\t\t\tClock: s.Clock(),\n\t\t\tRPCContext: s.RPCContext(),\n\t\t\tRPCRetryOptions: &retryOpts,\n\t\t}, ts.Gossip())\n\t\ttds := kv.NewTxnCoordSender(ds, ts.Clock(), ts.Ctx.Linearizable, tracing.NewTracer(),\n\t\t\tts.stopper, kv.NewTxnMetrics(metric.NewRegistry()))\n\n\t\tfor _, sk := range tc.splitKeys {\n\t\t\tif err := ts.node.ctx.DB.AdminSplit(sk); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tfor _, k := range tc.keys {\n\t\t\tput := roachpb.NewPut(k, roachpb.MakeValueFromBytes(k))\n\t\t\tif _, err := client.SendWrapped(tds, nil, put); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t// Try every possible ScanRequest startKey.\n\t\tfor start := 0; start < len(tc.keys); start++ {\n\t\t\t// Try every possible maxResults, from 1 to beyond the size of key array.\n\t\t\tfor maxResults := 1; maxResults <= len(tc.keys)-start+1; maxResults++ {\n\t\t\t\tscan := roachpb.NewScan(tc.keys[start], tc.keys[len(tc.keys)-1].Next())\n\t\t\t\treply, err := client.SendWrappedWith(\n\t\t\t\t\ttds, nil, roachpb.Header{MaxSpanRequestKeys: int64(maxResults)}, scan,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\trows := reply.(*roachpb.ScanResponse).Rows\n\t\t\t\tif start+maxResults <= len(tc.keys) && len(rows) != maxResults {\n\t\t\t\t\tt.Errorf(\"%d: start=%s: expected %d rows, but got %d\", i, tc.keys[start], maxResults, len(rows))\n\t\t\t\t} else if start+maxResults == len(tc.keys)+1 && len(rows) != maxResults-1 {\n\t\t\t\t\tt.Errorf(\"%d: expected %d rows, but got %d\", i, maxResults-1, len(rows))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func TestMultipleBuckets(t *testing.T) {\n\tdone := testutils.FreezeTime()\n\tdefer done()\n\n\tfr, err := NewRatioCounter(3, clock.Second)\n\trequire.NoError(t, err)\n\n\tfr.IncB(1)\n\tclock.Advance(clock.Second)\n\tfr.IncA(1)\n\n\tclock.Advance(clock.Second)\n\tfr.IncA(1)\n\n\tassert.Equal(t, true, fr.IsReady())\n\tassert.Equal(t, float64(2)/float64(3), fr.Ratio())\n}", "func getRedisVal (host string, targetName []string, from string, to string, maxdatapoints int) (ans string) {\r\n\tc, _ := redis.Dial(\"tcp\", host)\r\n\tdefer c.Close()\r\n\r\n\tfor _, v := range targetName {\r\n\t\tif debugEnable {\r\n\t\t\tfmt.Printf(\"zrangebyscore %s %s %s\\n\", grafanaItemMap[v].redisKey, from, to)\r\n\t\t}\r\n\t\tif err := c.Send(\"zrangebyscore\", grafanaItemMap[v].redisKey, from, to); err != nil {\r\n\t\t\tfmt.Fprintf(os.Stderr, \"err: %v\", err)\r\n\t\t}\r\n\t}\r\n\tc.Flush()\r\n\ttargetResult := make([]timeserie, len(targetName))\r\n\tfor i1, v1 := range targetName {\r\n\t\tresult := timeserie{}\r\n\t\tresult.Target = v1\r\n\t\tredisResult, _ := redis.Strings(c.Receive())\r\n\t\tresult.Datapoints, result.Time = convertRedisToGrafana(redisResult, grafanaItemMap[v1].index)\r\n\t\ttargetResult[i1] = result\r\n\t\t//fmt.Printf(\"dp: %v\\n\", result.Datapoints)\r\n\t}\r\n\r\n\tans = getOutputJson(targetResult)\r\n\tif debugEnable {\r\n\t\tfmt.Printf(\"json: %s\\n\", ans)\r\n\t}\r\n\treturn \r\n}", "func NewTimeMap() TimeMap {\n\ttm := make(timemap, bucketConst)\n\tfor i := 0; i < bucketConst; i++ {\n\t\ttm[i] = &bucket{\n\t\t\tobjects: make(map[uintptr]*storeValue),\n\t\t}\n\t}\n\n\tgo tm.goroutine()\n\treturn tm\n}", "func newbloom(n uint64, p float64) (b Bloom) {\n\tm := math.Ceil(-float64(n) * math.Log(p) / math.Ln2 / math.Ln2)\n\tk := math.Ceil(-math.Log(p) / math.Ln2)\n\t// fmt.Printf(\"MiB %v keys %v\\n\", m/8/1024/1024, k)\n\tarrsize := (uint64(m) + 8) / 8\n\tb.bitarray = make([]uint8, arrsize)\n\tb.size = uint64(m)\n\tb.keys = make([][16]byte, int(k))\n\tfor i := 0; i < len(b.keys); i++ {\n\t\tfor j := 0; j < len(b.keys[i]); j++ {\n\t\t\tb.keys[i][j] = byte(rand.Int31n(256))\n\t\t}\n\t}\n\treturn\n}", "func (v *verifiableMetric) update(data *Data, fieldValues string, packer *numberPacker) {\n\tswitch v.wantMetric.Type {\n\tcase TypeCounter:\n\t\tv.lastCounterValue[v.verifier.internMap.Intern(fieldValues)] = packer.pack(data.Number)\n\tcase TypeHistogram:\n\t\tlastDistributionSnapshot := v.lastDistributionSnapshot[v.verifier.internMap.Intern(fieldValues)]\n\t\tlastBucketSamples := lastDistributionSnapshot.numSamples\n\t\tvar count uint64\n\t\tfor i, b := range data.HistogramValue.Buckets {\n\t\t\tlastBucketSamples[i] = packer.packInt(int64(b.Samples))\n\t\t\tcount += b.Samples\n\t\t}\n\t\tlastDistributionSnapshot.sum = packer.pack(&data.HistogramValue.Total)\n\t\tlastDistributionSnapshot.count = packer.packInt(int64(count))\n\t\tlastDistributionSnapshot.min = packer.pack(&data.HistogramValue.Min)\n\t\tlastDistributionSnapshot.max = packer.pack(&data.HistogramValue.Max)\n\t\tlastDistributionSnapshot.ssd = packer.pack(&data.HistogramValue.SumOfSquaredDeviations)\n\t}\n}", "func (c *Counter) getCurrentBucket() *bucket {\n\tnow := time.Now().Unix()\n\tb, ok := c.Buckets[now]\n\tif !ok {\n\t\tb = &bucket{}\n\t\tc.Buckets[now] = b\n\t}\n\treturn b\n}", "func (ht *HashTable) collectEntries(head int) (keys, vals []int) {\n\tkeys = make([]int, 0, PER_BUCKET)\n\tvals = make([]int, 0, PER_BUCKET)\n\tvar entry, bucket int = 0, head\n\tfor {\n\t\tentryAddr := bucket*BUCKET_SIZE + BUCKET_HEADER + entry*ENTRY_SIZE\n\t\tentryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])\n\t\tentryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])\n\t\tif ht.Buf[entryAddr] == 1 {\n\t\t\tkeys = append(keys, int(entryKey))\n\t\t\tvals = append(vals, int(entryVal))\n\t\t} else if entryKey == 0 && entryVal == 0 {\n\t\t\treturn\n\t\t}\n\t\tif entry++; entry == PER_BUCKET {\n\t\t\tentry = 0\n\t\t\tif bucket = ht.nextBucket(bucket); bucket == 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func testStatsAndBucketstats(t *testing.T) {\n\tvar (\n\t\tmyClient1 clientStats\n\t\tmyUniqueClient1 = \"1111111\"\n\n\t\tmyClient2 clientStats\n\t\tmyUniqueClient2 = \"2222222\"\n\t)\n\n\t// Register from bucketstats from pfsagent #1\n\tbucketstats.Register(\"proxyfs.retryrpc\", myUniqueClient1, &myClient1)\n\n\t// Register from bucketstats from pfsagent #2\n\tbucketstats.Register(\"proxyfs.retryrpc\", myUniqueClient2, &myClient2)\n\n\t// Completed list stats\n\tmyClient1.AddCompleted.Add(1)\n\tmyClient1.RmCompleted.Add(1)\n\n\t// RPC counts\n\tmyClient1.RPCcompleted.Add(1)\n\tmyClient1.RPCretried.Add(1)\n\tmyClient1.RPCattempted.Add(1)\n\tmyClient1.RPCinprocess.Add(1)\n\n\t// Track duration of all RPCs in a graph\n\tstart := time.Now()\n\ttime.Sleep(10 * time.Millisecond)\n\tmyClient1.TimeOfRPCUsec.Add(uint64(time.Since(start).Microseconds()))\n\tmyClient1.ReplySize.Add(8192)\n\n\t// Example of pfsagent #2\n\tmyClient2.RPCcompleted.Add(1)\n\tmyClient2.RPCretried.Add(1)\n\tmyClient2.RPCattempted.Add(1)\n\tmyClient2.RPCinprocess.Add(1)\n\n\t// Dump stats\n\t/* DEBUG ONLY -\n\tfmt.Printf(\"pfsagent #1: %s\\n\", bucketstats.SprintStats(bucketstats.StatFormatParsable1, \"proxyfs.retryrpc\", myUniqueClient1))\n\tfmt.Printf(\"pfsagent #2: %s\\n\", bucketstats.SprintStats(bucketstats.StatFormatParsable1, \"proxyfs.retryrpc\", myUniqueClient2))\n\t*/\n\n\t// Unregister clients from bucketstats\n\tbucketstats.UnRegister(\"proxyfs.retryrpc\", myUniqueClient1)\n\tbucketstats.UnRegister(\"proxyfs.retryrpc\", myUniqueClient2)\n}", "func (f *fragment) importValue(columnIDs []uint64, values []int64, bitDepth uint, clear bool) error {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\t// Verify that there are an equal number of column ids and values.\n\tif len(columnIDs) != len(values) {\n\t\treturn fmt.Errorf(\"mismatch of column/value len: %d != %d\", len(columnIDs), len(values))\n\t}\n\n\tif len(columnIDs)*int(bitDepth+1)+f.opN < f.MaxOpN {\n\t\treturn errors.Wrap(f.importValueSmallWrite(columnIDs, values, bitDepth, clear), \"import small write\")\n\t}\n\n\t// Process every value.\n\t// If an error occurs then reopen the storage.\n\tf.storage.OpWriter = nil\n\ttotalChanges := 0\n\tif err := func() (err error) {\n\t\tfor i := range columnIDs {\n\t\t\tcolumnID, value := columnIDs[i], values[i]\n\t\t\tchanged, err := f.importSetValue(columnID, bitDepth, value, clear)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"importSetValue\")\n\t\t\t}\n\t\t\ttotalChanges += changed\n\t\t}\n\t\treturn nil\n\t}(); err != nil {\n\t\t_ = f.closeStorage(true)\n\t\t_ = f.openStorage(true)\n\t\treturn err\n\t}\n\t// We don't actually care, except we want our stats to be accurate.\n\tf.incrementOpN(totalChanges)\n\n\t// Reset the rowCache.\n\tf.rowCache = &simpleCache{make(map[uint64]*Row)}\n\n\t// in theory, this should probably have happened anyway, but if enough\n\t// of the bits matched existing bits, we'll be under our opN estimate, and\n\t// we want to ensure that the snapshot happens.\n\tf.enqueueSnapshot()\n\tf.unprotectedAwaitSnapshot()\n\n\treturn nil\n}", "func (h *hashMap) initializeBucket(index uint32) *bucket {\n\tparentIndex := h.getParentIndex(index)\n\n\tif h.bucketSegments.getBucket(parentIndex) == nil {\n\t\th.initializeBucket(parentIndex)\n\t}\n\n\tdummy := h.bucketSegments.getBucket(parentIndex).getDummy(index)\n\n\tif dummy != nil {\n\t\th.bucketSegments.setBucket(index, dummy)\n\t}\n\n\treturn dummy\n}", "func computeValues(o *Operation) {\n\to.Values[o.Size-1] = o.cumm[o.Size-1]\n\tfor i := o.Size - 2; i >= 0; i-- {\n\t\to.Values[i] = o.Values[i+1] + o.cumm[i]\n\t}\n}", "func (s *Server) Bucket(subKey string) *Bucket {\n\tidx := cityhash.CityHash32([]byte(subKey), uint32(len(subKey))) % s.bucketIdx\n\tif s.Debug {\n\t\ts.log.Infof(\"%s hit channel bucket index: %d use cityhash\", subKey, idx)\n\t}\n\treturn s.buckets[idx]\n}", "func sendAndResetBucket(bucket *[]int64, ws *websocket.Conn, timeNow *int64) {\n\tb, _ := json.Marshal(bucket)\n\tvar jsonStr = []byte(b)\n\tws.Write(jsonStr)\n\n\tfor i := range *bucket {\n\t\t(*bucket)[i] = 0\n\n\t}\n\t*timeNow = atomic.LoadInt64(&analysis.TimeStamp)\n}", "func (s *Series) get(t time.Time) *Bucket {\n\tfloor := s.floor(t)\n\tidx := s.index(t)\n\n\tbucket := s.buckets[idx]\n\tif bucket == nil || bucket.T != floor {\n\t\treturn &Bucket{floor, 0}\n\t}\n\n\treturn bucket\n}", "func (h *Handle) insertColStats2KV(physicalID int64, colInfos []*model.ColumnInfo) (err error) {\n\tstatsVer := uint64(0)\n\tdefer func() {\n\t\tif err == nil && statsVer != 0 {\n\t\t\th.recordHistoricalStatsMeta(physicalID, statsVer, StatsMetaHistorySourceSchemaChange)\n\t\t}\n\t}()\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\tctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)\n\texec := h.mu.ctx.(sqlexec.SQLExecutor)\n\t_, err = exec.ExecuteInternal(ctx, \"begin\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer func() {\n\t\terr = finishTransaction(ctx, exec, err)\n\t}()\n\ttxn, err := h.mu.ctx.Txn(true)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tstartTS := txn.StartTS()\n\t// First of all, we update the version.\n\t_, err = exec.ExecuteInternal(ctx, \"update mysql.stats_meta set version = %? where table_id = %?\", startTS, physicalID)\n\tif err != nil {\n\t\treturn\n\t}\n\tstatsVer = startTS\n\t// If we didn't update anything by last SQL, it means the stats of this table does not exist.\n\tif h.mu.ctx.GetSessionVars().StmtCtx.AffectedRows() > 0 {\n\t\t// By this step we can get the count of this table, then we can sure the count and repeats of bucket.\n\t\tvar rs sqlexec.RecordSet\n\t\trs, err = exec.ExecuteInternal(ctx, \"select count from mysql.stats_meta where table_id = %?\", physicalID)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer terror.Call(rs.Close)\n\t\treq := rs.NewChunk(nil)\n\t\terr = rs.Next(ctx, req)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tcount := req.GetRow(0).GetInt64(0)\n\t\tfor _, colInfo := range colInfos {\n\t\t\tvalue := types.NewDatum(colInfo.GetOriginDefaultValue())\n\t\t\tvalue, err = value.ConvertTo(h.mu.ctx.GetSessionVars().StmtCtx, &colInfo.FieldType)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif value.IsNull() {\n\t\t\t\t// If the adding column has default value null, all the existing rows have null value on the newly added column.\n\t\t\t\tif _, err := exec.ExecuteInternal(ctx, \"insert into mysql.stats_histograms (version, table_id, is_index, hist_id, distinct_count, null_count) values (%?, %?, 0, %?, 0, %?)\", startTS, physicalID, colInfo.ID, count); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// If this stats exists, we insert histogram meta first, the distinct_count will always be one.\n\t\t\t\tif _, err := exec.ExecuteInternal(ctx, \"insert into mysql.stats_histograms (version, table_id, is_index, hist_id, distinct_count, tot_col_size) values (%?, %?, 0, %?, 1, %?)\", startTS, physicalID, colInfo.ID, int64(len(value.GetBytes()))*count); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tvalue, err = value.ConvertTo(h.mu.ctx.GetSessionVars().StmtCtx, types.NewFieldType(mysql.TypeBlob))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// There must be only one bucket for this new column and the value is the default value.\n\t\t\t\tif _, err := exec.ExecuteInternal(ctx, \"insert into mysql.stats_buckets (table_id, is_index, hist_id, bucket_id, repeats, count, lower_bound, upper_bound) values (%?, 0, %?, 0, %?, %?, %?, %?)\", physicalID, colInfo.ID, count, count, value.GetBytes(), value.GetBytes()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m HMSketch) insert(kvs map[string]string, value, count float64) HMSketch {\n\thMux.Lock()\n\tfor key, val := range kvs {\n\t\tlocation := hash(key, val)\n\t\tif _, ok := m.Index[location]; !ok {\n\t\t\tm.Index[location] = m.Max\n\t\t\tm.Max++\n\t\t\tm.Registers = append(m.Registers, hist.New(m.Resolution))\n\t\t}\n\t\tm.Registers[m.Index[location]] = m.Registers[m.Index[location]].Insert(value, count)\n\t}\n\thMux.Unlock()\n\treturn m\n}", "func updateMemValues(srv *server, engine *EngineInstance, getMemInfo common.GetMemInfoFn) error {\n\tengine.RLock()\n\tec := engine.runner.GetConfig()\n\tei := ec.Index\n\n\tif ec.Storage.Tiers.Bdevs().Len() == 0 {\n\t\tsrv.log.Debugf(\"skipping mem check on engine %d, no bdevs\", ei)\n\t\tengine.RUnlock()\n\t\treturn nil\n\t}\n\tengine.RUnlock()\n\n\t// Retrieve up-to-date hugepage info to check that we got the requested number of hugepages.\n\tmi, err := getMemInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Calculate mem_size per I/O engine (in MB) from number of hugepages required per engine.\n\tnrPagesRequired := srv.cfg.NrHugepages / len(srv.cfg.Engines)\n\tpageSizeMiB := mi.HugePageSizeKb / humanize.KiByte // kib to mib\n\tmemSizeReqMiB := nrPagesRequired * pageSizeMiB\n\tmemSizeFreeMiB := mi.HugePagesFree * pageSizeMiB\n\n\t// Fail if free hugepage mem is not enough to sustain average I/O workload (~1GB).\n\tsrv.log.Debugf(\"Per-engine MemSize:%dMB, HugepageSize:%dMB (meminfo: %+v)\", memSizeReqMiB,\n\t\tpageSizeMiB, *mi)\n\tif memSizeFreeMiB < memSizeReqMiB {\n\t\treturn FaultInsufficientFreeHugePageMem(int(ei), memSizeReqMiB, memSizeFreeMiB,\n\t\t\tnrPagesRequired, mi.HugePagesFree)\n\t}\n\n\t// Set engine mem_size and hugepage_size (MiB) values based on hugepage info.\n\tengine.setMemSize(memSizeReqMiB)\n\tengine.setHugePageSz(pageSizeMiB)\n\n\treturn nil\n}", "func (s *Series) Range(start time.Time, end time.Time) []*Bucket {\n\tvar buckets []*Bucket\n\tstartFloor := s.floor(start)\n\tendFloor := s.floor(end)\n\n\tnow := time.Now()\n\tfirstPossibleFloor := s.floor(now.Add(-1 * s.Duration))\n\n\t// sweep through our range of buckets\n\tfor x := startFloor; x.Before(endFloor) || x.Equal(endFloor); x = x.Add(s.Resolution) {\n\t\t// don't return values beyound our Series boundaries or from the future\n\t\tif x.Before(firstPossibleFloor) || x.After(now) {\n\t\t\tcontinue\n\t\t}\n\n\t\tbucket := s.get(x)\n\t\t// should not be the case but good defense\n\t\tif bucket == nil {\n\t\t\tcontinue\n\t\t}\n\t\tbuckets = append(buckets, bucket)\n\t}\n\n\t/* Last record if zero */\n\tb := buckets[len(buckets)-1]\n\tif b.V == 0 {\n\t\tbuckets = buckets[:len(buckets)-1]\n\t}\n\n\treturn buckets\n}", "func (o *ObjectNode) getBucketV2Handler(w http.ResponseWriter, r *http.Request) {\n\tlog.LogInfof(\"getBucketV2Handler: get bucket, requestID(%v) remote(%v)\", RequestIDFromRequest(r), r.RemoteAddr)\n\n\t// check args\n\t_, bucket, _, vl, err := o.parseRequestParams(r)\n\tif err != nil {\n\t\tlog.LogErrorf(\"getBucketV2Handler: parse request parameters fail: requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\treturn\n\t}\n\n\t// get options\n\tprefix := r.URL.Query().Get(ParamPrefix)\n\tmaxKeys := r.URL.Query().Get(ParamMaxKeys)\n\tdelimiter := r.URL.Query().Get(ParamPartDelimiter)\n\tcontToken := r.URL.Query().Get(ParamContToken)\n\tfetchOwner := r.URL.Query().Get(ParamFetchOwner)\n\tstartAfter := r.URL.Query().Get(ParamStartAfter)\n\n\tvar maxKeysInt uint64\n\tif maxKeys != \"\" {\n\t\tmaxKeysInt, err = strconv.ParseUint(maxKeys, 10, 16)\n\t\tif err != nil {\n\t\t\tlog.LogErrorf(\"getBucketV2Handler: parse max keys fail, requestID(%v) err(%v)\",\n\t\t\t\tRequestIDFromRequest(r), err)\n\t\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\t\treturn\n\t\t}\n\t\tif maxKeysInt > MaxKeys {\n\t\t\tmaxKeysInt = MaxKeys\n\t\t}\n\t} else {\n\t\tmaxKeysInt = MaxKeys\n\t}\n\n\tvar fetchOwnerBool bool\n\tif fetchOwner != \"\" {\n\t\tfetchOwnerBool, err = strconv.ParseBool(fetchOwner)\n\t\tif err != nil {\n\t\t\tlog.LogErrorf(\"getBucketV2Handler: requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tfetchOwnerBool = false\n\t}\n\n\trequest := &ListBucketRequestV2{\n\t\tdelimiter: delimiter,\n\t\tmaxKeys: maxKeysInt,\n\t\tprefix: prefix,\n\t\tcontToken: contToken,\n\t\tfetchOwner: fetchOwnerBool,\n\t\tstartAfter: startAfter,\n\t}\n\n\tfsFileInfos, keyCount, nextToken, isTruncated, prefixes, err := vl.ListFilesV2(request)\n\tif err != nil {\n\t\tlog.LogErrorf(\"getBucketV2Handler: request id [%v], Get files list failed cause : %v\", r.URL, err)\n\t\t_ = InternalError.ServeResponse(w, r)\n\t\treturn\n\t}\n\t// get owner\n\tvar bucketOwner *BucketOwner\n\tif fetchOwnerBool {\n\t\taccessKey, _ := vl.OSSSecure()\n\t\tbucketOwner = NewBucketOwner(accessKey)\n\t}\n\n\tvar contents = make([]*Content, 0)\n\tif len(fsFileInfos) > 0 {\n\t\tfor _, fsFileInfo := range fsFileInfos {\n\t\t\tcontent := &Content{\n\t\t\t\tKey: fsFileInfo.Path,\n\t\t\t\tLastModified: formatTimeISO(fsFileInfo.ModifyTime),\n\t\t\t\tETag: fsFileInfo.ETag,\n\t\t\t\tSize: int(fsFileInfo.Size),\n\t\t\t\tStorageClass: StorageClassStandard,\n\t\t\t\tOwner: bucketOwner,\n\t\t\t}\n\t\t\tcontents = append(contents, content)\n\t\t}\n\t}\n\n\tvar commonPrefixes = make([]*CommonPrefix, 0)\n\tfor _, prefix := range prefixes {\n\t\tcommonPrefix := &CommonPrefix{\n\t\t\tPrefix: prefix,\n\t\t}\n\t\tcommonPrefixes = append(commonPrefixes, commonPrefix)\n\t}\n\n\tlistBucketResult := ListBucketResultV2{\n\t\tName: bucket,\n\t\tPrefix: prefix,\n\t\tToken: contToken,\n\t\tNextToken: nextToken,\n\t\tKeyCount: keyCount,\n\t\tMaxKeys: maxKeysInt,\n\t\tDelimiter: delimiter,\n\t\tIsTruncated: isTruncated,\n\t\tContents: contents,\n\t\tCommonPrefixes: commonPrefixes,\n\t}\n\n\tvar bytes []byte\n\tvar marshalError error\n\tif bytes, marshalError = MarshalXMLEntity(listBucketResult); marshalError != nil {\n\t\tlog.LogErrorf(\"getBucketV2Handler: marshal result fail, requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t\t_ = InvalidArgument.ServeResponse(w, r)\n\t\treturn\n\t}\n\n\t// set response header\n\tw.Header().Set(HeaderNameContentType, HeaderValueContentTypeXML)\n\tw.Header().Set(HeaderNameContentLength, strconv.Itoa(len(bytes)))\n\tif _, err = w.Write(bytes); err != nil {\n\t\tlog.LogErrorf(\"getBucketVeHandler: write response body fail, requestID(%v) err(%v)\", RequestIDFromRequest(r), err)\n\t}\n\treturn\n}", "func TestKVRebOnUpdateBucketOpOneByOne(t *testing.T) {\n\ttime.Sleep(5 * time.Second)\n\thandler := \"bucket_op_on_update\"\n\n\tflushFunctionAndBucket(handler)\n\ttime.Sleep(5 * time.Second)\n\tcreateAndDeployFunction(handler, handler, &commonSettings{})\n\n\ttime.Sleep(5 * time.Second)\n\n\trl := &rateLimit{\n\t\tlimit: true,\n\t\topsPSec: rlOpsPSec,\n\t\tcount: rlItemCount,\n\t\tstopCh: make(chan struct{}, 1),\n\t\tloop: true,\n\t}\n\n\tgo pumpBucketOps(opsType{count: rlItemCount}, rl)\n\n\twaitForDeployToFinish(handler)\n\tmetaStateDump()\n\n\taddAllNodesOneByOne(\"kv\")\n\tremoveAllNodesOneByOne()\n\n\trl.stopCh <- struct{}{}\n\n\tflushFunctionAndBucket(handler)\n}", "func (iter *Iterator) tick(i, min int, delta []*vcache) (ok bool, err error) {\n\tnext := make([]*vcache, i)\n\n\t// The biggest outer loop is walking backwards over iter.In[i]\n\tx := len(iter.in[i])\n\tfor x > 0 {\n\t\tj := iter.in[i][x-1]\n\n\t\tif j <= min {\n\t\t\treturn false, iter.restore(next, i)\n\t\t} else if iter.blacklist[j] {\n\t\t\tx--\n\t\t\tcontinue\n\t\t}\n\n\t\tv := iter.variables[j]\n\n\t\tself := v.save()\n\n\t\tif v.value = v.Next(); v.value == NIL {\n\t\t\t// That sucks. Now we need to restore the value\n\t\t\t// that was changed and decrement x.\n\t\t\tv.value = v.Seek(self.ID)\n\t\t\tx--\n\t\t} else {\n\t\t\t// We got a non-nil value for v, so now we\n\t\t\t// propagate between j and i, then crawl forward\n\t\t\t// over the indices in iter.Out[q] that are less than i\n\t\t\t// and seek to their new values.\n\n\t\t\t// Propagate up to but not including i\n\t\t\tif err = iter.push(v, j, i); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Fantastic. Now that we've propagated the value we found for v,\n\t\t\t// we start \"the crawl\" from j to i, seeking to the new satisfying root\n\t\t\t// and recursing on tick when necessary.\n\t\t\tcursor := j\n\t\t\titer.blacklist[j] = true\n\t\t\tfor _, k := range iter.out[j] {\n\t\t\t\tif k >= i {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tw := iter.variables[k]\n\n\t\t\t\tif next[k] == nil {\n\t\t\t\t\tnext[k] = w.save()\n\t\t\t\t}\n\n\t\t\t\td := make([]*vcache, k)\n\n\t\t\t\t// Here we keep seeking and ticking until we have a real value.\n\t\t\t\tfor w.value = w.Seek(w.root); w.value == NIL; w.value = w.Seek(w.root) {\n\t\t\t\t\tif ok, err = iter.tick(k, min, d); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err = iter.restore(d, i); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif w.value == NIL {\n\t\t\t\t\t// We were unable to complete the crawl.\n\t\t\t\t\t// We've already reset our state.\n\t\t\t\t\t// This is how far we got:\n\t\t\t\t\tcursor = k + 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We got a real value for w! Now we propagate the affected values\n\t\t\t\t// through i and stash them into next if they're not there already,\n\t\t\t\t// and then continue with the tick-crawl.\n\t\t\t\terr = iter.push(w, k, i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfor l, saved := range d {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\terr = iter.push(iter.variables[l], l, i)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif next[l] == nil {\n\t\t\t\t\t\t\tnext[l] = saved\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// We need to *unset* the blacklist after recursing.\n\t\t\t// Variables are only blacklisted when they appear as\n\t\t\t// a parent in the call stack - they might be visited\n\t\t\t// twice as siblings in the call tree, etc.\n\t\t\titer.blacklist[j] = false\n\n\t\t\tif cursor == j {\n\t\t\t\t// Hooray!\n\t\t\t\t// Now here we need to push every affected value\n\t\t\t\t// through to the rest of the domain\n\t\t\t\t// delta[j] = self\n\t\t\t\tnext[j] = self\n\t\t\t\tfor l, saved := range next {\n\t\t\t\t\tif saved != nil {\n\t\t\t\t\t\tif delta[l] == nil {\n\t\t\t\t\t\t\tdelta[l] = saved\n\t\t\t\t\t\t}\n\t\t\t\t\t\terr = iter.push(iter.variables[l], i, iter.Len())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\t\t// This means we reset (all) those affected to their previous state\n\t\t\terr = iter.restore(next, i)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (h *Histogram) Buckets() []int64 {\n\tbuckets := make([]int64, len(h.buckets))\n\tfor i := range h.buckets {\n\t\tbuckets[i] = h.buckets[i].Load()\n\t}\n\treturn buckets\n}", "func (ct *ctrlerCtx) diffBucket(apicl apiclient.Services) {\n\topts := api.ListWatchOptions{}\n\n\t// get a list of all objects from API server\n\tobjlist, err := apicl.ObjstoreV1().Bucket().List(context.Background(), &opts)\n\tif err != nil {\n\t\tct.logger.Errorf(\"Error getting a list of objects. Err: %v\", err)\n\t\treturn\n\t}\n\n\tct.logger.Infof(\"diffBucket(): BucketList returned %d objects\", len(objlist))\n\n\t// build an object map\n\tobjmap := make(map[string]*objstore.Bucket)\n\tfor _, obj := range objlist {\n\t\tobjmap[obj.GetKey()] = obj\n\t}\n\n\tlist, err := ct.Bucket().List(context.Background(), &opts)\n\tif err != nil && !strings.Contains(err.Error(), \"not found in local cache\") {\n\t\tct.logger.Infof(\"Failed to get a list of objects. Err: %s\", err)\n\t\treturn\n\t}\n\n\t// if an object is in our local cache and not in API server, trigger delete for it\n\tfor _, obj := range list {\n\t\t_, ok := objmap[obj.GetKey()]\n\t\tif !ok {\n\t\t\tct.logger.Infof(\"diffBucket(): Deleting existing object %#v since its not in apiserver\", obj.GetKey())\n\t\t\tevt := kvstore.WatchEvent{\n\t\t\t\tType: kvstore.Deleted,\n\t\t\t\tKey: obj.GetKey(),\n\t\t\t\tObject: &obj.Bucket,\n\t\t\t}\n\t\t\tct.handleBucketEvent(&evt)\n\t\t}\n\t}\n\n\t// trigger create event for all others\n\tfor _, obj := range objlist {\n\t\tct.logger.Infof(\"diffBucket(): Adding object %#v\", obj.GetKey())\n\t\tevt := kvstore.WatchEvent{\n\t\t\tType: kvstore.Created,\n\t\t\tKey: obj.GetKey(),\n\t\t\tObject: obj,\n\t\t}\n\t\tct.handleBucketEvent(&evt)\n\t}\n}", "func (t *txStats) addKV(k, v []byte) {\n\tif t.numKV == 0 {\n\t\tt.firstTime = time.Now()\n\t}\n\tt.numKV++\n\n\tvBytes := len(v)\n\tkBytes := len(k)\n\tcurBytes := uint64(kBytes + vBytes)\n\tt.lastBytes += curBytes\n\tt.totalBytes += curBytes\n\n\tswitch {\n\tcase vBytes == 0:\n\t\tt.numV0++\n\tcase vBytes < 10:\n\t\tt.numV1++\n\tcase vBytes < 100:\n\t\tt.numV10++\n\tcase vBytes < 1000:\n\t\tt.numV100++\n\tcase vBytes < 10000:\n\t\tt.numV1k++\n\tcase vBytes < 100000:\n\t\tt.numV10k++\n\tcase vBytes < 1000000:\n\t\tt.numV100k++\n\tcase vBytes < 10000000:\n\t\tt.numV1m++\n\tdefault:\n\t\tt.numV10m++\n\t}\n\n\t// Print progress?\n\tif elapsed := time.Since(t.lastTime); elapsed > time.Minute {\n\t\tmb := float64(t.lastBytes) / 1000000\n\t\tsec := elapsed.Seconds()\n\t\tthroughput := mb / sec\n\t\tdvid.Debugf(\"Transfer throughput (%s): %5.2f MB/s (%s in %4.1f seconds). Total %s\\n\", t.name, throughput, humanize.Bytes(t.lastBytes), sec, humanize.Bytes(t.totalBytes))\n\n\t\tt.lastTime = time.Now()\n\t\tt.lastBytes = 0\n\t}\n}", "func (w *streamWorker) initBucketFilter(bucketFilter map[string]*common.TsVbuuid,\n\tbucketSessionId BucketSessionId) {\n\n\tw.lock.Lock()\n\tdefer w.lock.Unlock()\n\n\t//allocate a new filter for the buckets which don't\n\t//have a filter yet\n\tfor b, q := range w.reader.bucketQueueMap {\n\t\tif _, ok := w.bucketFilter[b]; !ok {\n\t\t\tlogging.Debugf(\"MutationStreamReader::initBucketFilter Added new filter \"+\n\t\t\t\t\"for Bucket %v Stream %v\", b, w.streamId)\n\n\t\t\t//if there is non-nil filter, use that. otherwise use a zero filter.\n\t\t\tif filter, ok := bucketFilter[b]; ok && filter != nil {\n\t\t\t\tw.bucketFilter[b] = filter.Copy()\n\t\t\t\tw.bucketPrevSnapMap[b] = filter.Copy()\n\t\t\t\t//reset vbuuids to 0 in filter. mutations for a vbucket are\n\t\t\t\t//only processed after streambegin is received, which will set\n\t\t\t\t//the vbuuid again.\n\t\t\t\tfor i := 0; i < len(filter.Vbuuids); i++ {\n\t\t\t\t\tw.bucketFilter[b].Vbuuids[i] = 0\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tw.bucketFilter[b] = common.NewTsVbuuid(b, int(q.queue.GetNumVbuckets()))\n\t\t\t\tw.bucketPrevSnapMap[b] = common.NewTsVbuuid(b, int(q.queue.GetNumVbuckets()))\n\t\t\t}\n\n\t\t\tw.bucketSyncDue[b] = false\n\t\t\tw.bucketFirstSnap[b] = make(firstSnapFlag, int(q.queue.GetNumVbuckets()))\n\t\t\tw.bucketSessionId[b] = bucketSessionId[b]\n\n\t\t\t//reset stat for bucket\n\t\t\tstats := w.reader.stats.Get()\n\t\t\tif rstats, ok := stats.buckets[b]; ok {\n\t\t\t\trstats.mutationQueueSize.Set(0)\n\t\t\t}\n\t\t}\n\t}\n\n\t//remove the bucket filters for which bucket doesn't exist anymore\n\tfor b, _ := range w.bucketFilter {\n\t\tif _, ok := w.reader.bucketQueueMap[b]; !ok {\n\t\t\tlogging.Debugf(\"MutationStreamReader::initBucketFilter Deleted filter \"+\n\t\t\t\t\"for Bucket %v Stream %v\", b, w.streamId)\n\t\t\tdelete(w.bucketFilter, b)\n\t\t\tdelete(w.bucketPrevSnapMap, b)\n\t\t\tdelete(w.bucketSyncDue, b)\n\t\t\tdelete(w.bucketFirstSnap, b)\n\t\t\tdelete(w.bucketSessionId, b)\n\t\t}\n\t}\n\n}", "func getTabularMetric(c *gin.Context) {\n\tparams, err := parseMetricParams(c)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tparams.Start, _ = bi.GetRoundedTime(params.Start, params.Granularity)\n\n\tr, err := getRangeInGranularities(params.Start, params.End, params.Granularity)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tif r > 10000 {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": \"Too many results to tabulate\",\n\t\t})\n\t\treturn\n\t}\n\n\tinput, err := getDataOverRange(mongoSession, biModule.Rules[params.RuleIndex],\n\t\tparams.Granularity, params.Start, params.End, params.Value)\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tdataArray := make([]bson.M, 0)\n\tfor i := 0; i < len(input); i++ {\n\t\tvar ticks int\n\t\tinputStartTime, ok := input[i][\"start\"].(time.Time)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch params.Granularity {\n\t\tcase bi.Monthly:\n\t\t\tticks = 12\n\t\tcase bi.Daily:\n\t\t\tswitch inputStartTime.Month() {\n\t\t\tcase time.April:\n\t\t\t\tfallthrough\n\t\t\tcase time.June:\n\t\t\t\tfallthrough\n\t\t\tcase time.September:\n\t\t\t\tfallthrough\n\t\t\tcase time.November:\n\t\t\t\tticks = 30\n\t\t\tcase time.February:\n\t\t\t\tticks = 28 // TODO: account for leap years\n\t\t\tdefault:\n\t\t\t\tticks = 31\n\t\t\t}\n\t\tcase bi.Hourly:\n\t\t\tticks = 24\n\t\tdefault:\n\t\t\tticks = 60\n\t\t}\n\n\t\tgranularityField, err := getGranularityField(params.Granularity)\n\t\tif err != nil {\n\t\t\tc.JSON(400, gin.H{\n\t\t\t\t\"error\": \"Not a valid time granularity\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tdataField, ok := input[i][granularityField].(bson.M)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < ticks; j++ {\n\t\t\tindex := j\n\t\t\tif params.Granularity == bi.Monthly ||\n\t\t\t\tparams.Granularity == bi.Daily {\n\t\t\t\t// days and months start on 1, not 0\n\t\t\t\tindex = j + 1\n\t\t\t}\n\t\t\tval := convert.ToFloat64(dataField[strconv.Itoa(index)], 0)\n\t\t\tcTime, _ := addGranularitiesToTime(inputStartTime, params.Granularity, j)\n\n\t\t\tif cTime.Before(params.Start) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif cTime.After(params.End) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdataArray = append(dataArray, bson.M{\n\t\t\t\t\"value\": val,\n\t\t\t\t\"time\": cTime.Format(timeLayout),\n\t\t\t})\n\t\t}\n\t}\n\n\tc.IndentedJSON(200, gin.H{\n\t\t\"data\": dataArray,\n\t})\n\n}", "func (db *DumbDB) GetLimited(bucket string, size int, cookie []byte) (ret_val [][]byte, err error) {\n\tret_val = make([][]byte, size)\n\titr := 0\n\terr = db.dbP.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(bucket))\n\t\tif bkt == nil {\n\t\t\tdb.err_log.Println(\"Bucket not created yet.\")\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tc := bkt.Cursor()\n\n\t\tinit_kv := make([][]byte, 2)\n\t\tif cookie != nil {\n\t\t\t// This will seek to the last result of the\n\t\t\t// previous search. Initialize the first to the previous val.\n\t\t\t_k, _ := c.Seek(cookie)\n\t\t\tif _k == nil {\n\t\t\t\tdb.err_log.Println(\"Got invalid cookie.\")\n\t\t\t\treturn bolt.ErrKeyRequired\n\t\t\t}\n\t\t\tinit_kv[0], init_kv[1] = c.Prev()\n\t\t} else {\n\t\t\tinit_kv[0], init_kv[1] = c.Last()\n\t\t}\n\n\t\tfor k, v := init_kv[0], init_kv[1]; k != nil && itr < size; k, v = c.Prev() {\n\t\t\tret_val[itr] = v\n\t\t\tdb.info_log.Println(\"Added value\")\n\t\t\titr++\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}", "func TestAccumulatorCycle_ManyValues(t *testing.T) {\n var targetSampleCount = uint32(100) // the sample count is larger than the number of values provided within this test\n \n var accumulator = NewAccumulator(\"stream\", 0, math.MaxInt64, OrdinalInterval, targetSampleCount)\n \n var overallSum = 0.0\n var overallCount = 0\n \n var values = [5]float64{2.0,4.0,6.0,8.0,10.0}\n var addedValues = make([]float64, 0, 100)\n \n for _,v := range values {\n var valuesToAdd = targetSampleCount\n \n if v == 6 {\n valuesToAdd = 5\n }\n \n for i:=uint32(0);i<valuesToAdd;i++ {\n accumulator.Include(NewOrdinalValue(\"test\",1,v))\n overallSum += v\n overallCount++\n addedValues = append(addedValues, v)\n } \n }\n \n var overallMean = overallSum / float64(overallCount)\n \n // finalise the accumulator and gather statistics\n var statistics = accumulator.Finalise()\n\n assert.Equal(t, uint64(overallCount), statistics.Count, \"Unexpected count\")\n assert.Equal(t, overallMean, statistics.Mean, \"Unexpected mean\")\n assert.Equal(t, 2.0, statistics.Minimum, \"Unexpected minimum\")\n assert.Equal(t, 10.0, statistics.Maximum, \"Unexpected maximum\")\n assert.Equal(t, overallSum, statistics.Sum, \"Unexpected sum\")\n \n // determine the sample set that would have been used\n var samplingRateDenominator = 1\n var maxSamplingRate = 1.5\n var expectedSampleCount = overallCount\n var rate = float64(expectedSampleCount) / float64(targetSampleCount)\n \n for rate > maxSamplingRate {\n samplingRateDenominator *= 2\n expectedSampleCount = int(math.Floor(float64(expectedSampleCount) / 2.0))\n rate = float64(expectedSampleCount) / float64(targetSampleCount)\n }\n \n var sampleValues = make([]float64, 0, 100)\n var sampleCount = uint32(0)\n var sampleSum = 0.0\n \n for k,v := range addedValues {\n if (k + 1) % samplingRateDenominator == 0 {\n sampleValues = append(sampleValues, v)\n sampleCount++\n sampleSum += v\n }\n }\n \n var sampleMean = sampleSum / float64(sampleCount)\n var sumSqSampleErr = 0.0\n \n for _,v := range sampleValues {\n sumSqSampleErr += math.Pow(v-sampleMean,2)\n }\n \n var sampleStandardDeviation = math.Sqrt(sumSqSampleErr / float64(sampleCount))\n \n assert.Equal(t, sampleStandardDeviation, statistics.SampleStandardDeviation, \"Unexpected standard deviation\")\n assert.Equal(t, sampleMean / sampleStandardDeviation, statistics.CoefficientOfVariation, \"Unexpected coefficient of variation\")\n assert.Equal(t, sampleMean, statistics.SampleMean, \"Sample mean must equal mean when all values are included in the sample set\")\n assert.Equal(t, sampleSum, statistics.SampleSum, \"Sample sum must equal sum when all values are included in the sample set\")\n assert.Equal(t, sampleCount, statistics.SampleCount, \"Sample count must count when all values are included in the sample set\")\n}", "func splitBuckets(h *Histogram, feedback *QueryFeedback) ([]bucket, []bool, int64) {\n\tbktID2FB, numTotalFBs := buildBucketFeedback(h, feedback)\n\tbuckets := make([]bucket, 0, h.Len())\n\tisNewBuckets := make([]bool, 0, h.Len())\n\tsplitCount := getSplitCount(numTotalFBs, defaultBucketCount-h.Len())\n\tfor i := 0; i < h.Len(); i++ {\n\t\tbktFB, ok := bktID2FB[i]\n\t\t// No feedback, just use the original one.\n\t\tif !ok {\n\t\t\tbuckets = append(buckets, bucket{h.GetLower(i), h.GetUpper(i), h.bucketCount(i), h.Buckets[i].Repeat})\n\t\t\tisNewBuckets = append(isNewBuckets, false)\n\t\t\tcontinue\n\t\t}\n\t\t// Distribute the total split count to bucket based on number of bucket feedback.\n\t\tnewBktNums := splitCount * len(bktFB.feedback) / numTotalFBs\n\t\tbkts := bktFB.splitBucket(newBktNums, h.TotalRowCount(), float64(h.bucketCount(i)))\n\t\tbuckets = append(buckets, bkts...)\n\t\tif len(bkts) == 1 {\n\t\t\tisNewBuckets = append(isNewBuckets, false)\n\t\t} else {\n\t\t\tfor i := 0; i < len(bkts); i++ {\n\t\t\t\tisNewBuckets = append(isNewBuckets, true)\n\t\t\t}\n\t\t}\n\t}\n\ttotCount := int64(0)\n\tfor _, bkt := range buckets {\n\t\ttotCount += bkt.Count\n\t}\n\treturn buckets, isNewBuckets, totCount\n}", "func vgCollect(ch chan<- prometheus.Metric, vgs []map[string]string) {\n for _, vg := range vgs {\n vgSizeF, err := strconv.ParseFloat(strings.Trim(vg[\"vg_size\"], \"B\"), 64)\n if err != nil {\n log.Print(err)\n return\n }\n ch <- prometheus.MustNewConstMetric(vgSizeMetric, prometheus.GaugeValue, vgSizeF, vg[\"vg_name\"], vg[\"vg_uuid\"])\n\n vgFreeF, err := strconv.ParseFloat(strings.Trim(vg[\"vg_free\"], \"B\"), 64)\n if err != nil {\n log.Print(err)\n return\n }\n ch <- prometheus.MustNewConstMetric(vgFreeMetric, prometheus.GaugeValue, vgFreeF, vg[\"vg_name\"], vg[\"vg_uuid\"])\n }\n}", "func TTLBucket(ttl time.Duration) string {\n\tupperBound := sort.Search(\n\t\tlen(bucketBoundaries),\n\t\tfunc(i int) bool {\n\t\t\treturn ttl <= bucketBoundaries[i].Value\n\t\t},\n\t)\n\tif upperBound >= len(bucketBoundaries) {\n\t\treturn OverflowBucket\n\t} else {\n\t\treturn bucketBoundaries[upperBound].Label\n\t}\n}", "func unmarshalValues(buf []byte, dest metric.Values) metric.Values {\n\tif buf[0] != formatVersion {\n\t\tpanic(\"unsupported format version\")\n\t}\n\n\tn := (len(buf) - formatVersionSize) / sampleSize\n\n\tif cap(dest) < n {\n\t\tdest = make(metric.Values, n)\n\t} else {\n\t\tdest = dest[0:n]\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\toffset := formatVersionSize + i*sampleSize\n\t\tdest[i].Timestamp = clientmodel.TimestampFromUnix(int64(binary.LittleEndian.Uint64(buf[offset:])))\n\t\tdest[i].Value = clientmodel.SampleValue(math.Float64frombits(binary.LittleEndian.Uint64(buf[offset+8:])))\n\t}\n\treturn dest\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}" ]
[ "0.61096376", "0.6018294", "0.56954724", "0.5651117", "0.54883426", "0.5447687", "0.54123515", "0.540613", "0.5204343", "0.5188483", "0.5144134", "0.5125972", "0.5121473", "0.5109636", "0.51069444", "0.5105892", "0.50866896", "0.5072913", "0.5051326", "0.50378215", "0.50259495", "0.5022103", "0.50152117", "0.50108206", "0.49760404", "0.49717885", "0.49676427", "0.495496", "0.49518877", "0.4948482", "0.49450657", "0.49409547", "0.49256006", "0.49247864", "0.49246144", "0.49150765", "0.49137238", "0.4913096", "0.4912113", "0.48962212", "0.4896119", "0.48935133", "0.48876438", "0.48771608", "0.48739964", "0.48370624", "0.4826374", "0.48119435", "0.48080328", "0.48060083", "0.48010573", "0.47969514", "0.4796158", "0.47926298", "0.47925818", "0.47873726", "0.4780171", "0.4776843", "0.47763586", "0.47748882", "0.47732753", "0.47728252", "0.47517294", "0.4746911", "0.4739224", "0.47372705", "0.47275043", "0.47265333", "0.47257638", "0.47190973", "0.47158042", "0.4714849", "0.47125345", "0.4709983", "0.470805", "0.47043145", "0.47007707", "0.46926248", "0.4691303", "0.46883562", "0.46850374", "0.467694", "0.4673934", "0.46696046", "0.46672118", "0.46650186", "0.4664767", "0.46645504", "0.46626616", "0.46625045", "0.4661571", "0.46575698", "0.4652683", "0.46481612", "0.4644452", "0.46440622", "0.46422708", "0.46408853", "0.46354586", "0.46329558" ]
0.5975178
2
lookUpIdx looks for scaledValue's index in histogramBucketValues TODO: change linear time to O(log(N)) with binary search
func lookUpIdx(scaledValue int) int { scaledValue32 := int32(scaledValue) if scaledValue32 < maxArrayValue { //constant return val2Bucket[scaledValue] } for i := maxArrayValueIndex; i < numValues; i++ { if histogramBucketValues[i] > scaledValue32 { return i } } log.Fatalf("never reached/bug") return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IndexLookup(x *suffixarray.Index, s []byte, n int) []int", "func init() {\n\tval2Bucket = make([]int, maxArrayValue)\n\tmaxArrayValueIndex = -1\n\tfor i, value := range histogramBucketValues {\n\t\tif value == maxArrayValue {\n\t\t\tmaxArrayValueIndex = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif maxArrayValueIndex == -1 {\n\t\tlog.Fatalf(\"Bug boundary maxArrayValue=%d not found in bucket list %v\", maxArrayValue, histogramBucketValues)\n\t}\n\tidx := 0\n\tfor i := int32(0); i < maxArrayValue; i++ {\n\t\tif i >= histogramBucketValues[idx] {\n\t\t\tidx++\n\t\t}\n\t\tval2Bucket[i] = idx\n\t}\n\t// coding bug detection (aka impossible if it works once) until 1000\n\tif idx != maxArrayValueIndex {\n\t\tlog.Fatalf(\"Bug in creating histogram index idx %d vs index %d up to %d\", idx, int(maxArrayValue), maxArrayValue)\n\t}\n}", "func (h *hashTable) insert(val []byte) {\n\tif h.search(val) {\n\t\treturn\n\t}\n\tif len(h.bucketSlice) == 0 {\n\t\th.bucketSlice = append(h.bucketSlice, newBucket())\n\t}\n\tprobeIdx := hashFunc(val) % uint32(bucketCnt)\n\tisInserted := false\nLoop:\n\tfor _, bucket := range h.bucketSlice {\n\t\t// if the bucket is already full, skip it\n\t\tif bucket.wrapped {\n\t\t\tcontinue\n\t\t}\n\t\t// if the index is not taken yet, map it\n\t\tif bucket.data[probeIdx] == nil {\n\t\t\tbucket.data[probeIdx] = val\n\t\t\tisInserted = true\n\t\t\tbreak\n\t\t}\n\t\t// linear probe\n\t\tfor idx, elem := range bucket.data {\n\t\t\tif uint32(idx) == probeIdx {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif elem == nil {\n\t\t\t\tbucket.data[idx] = val\n\t\t\t\tisInserted = true\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t}\n\t\tbucket.wrapped = true\n\t}\n\tif !isInserted {\n\t\tnb := newBucket()\n\t\tnb.data[probeIdx] = val\n\t\th.bucketSlice = append(h.bucketSlice, nb)\n\t}\n}", "func (bl *lfList) bucketValue(b int) int {\n return int(atomic.LoadInt32(&bl.b[b]))\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func bucketIndex(index int) int {\n\treturn (MaxRoutingTableSize - 1) - index\n}", "func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error {\n\tkind := desc.NumberKind()\n\tasFloat := number.CoerceToFloat64(kind)\n\n\tbucketID := len(c.boundaries)\n\tfor i, boundary := range c.boundaries {\n\t\tif asFloat < boundary {\n\t\t\tbucketID = i\n\t\t\tbreak\n\t\t}\n\t}\n\t// Note: Binary-search was compared using the benchmarks. The following\n\t// code is equivalent to the linear search above:\n\t//\n\t// bucketID := sort.Search(len(c.boundaries), func(i int) bool {\n\t// return asFloat < c.boundaries[i]\n\t// })\n\t//\n\t// The binary search wins for very large boundary sets, but\n\t// the linear search performs better up through arrays between\n\t// 256 and 512 elements, which is a relatively large histogram, so we\n\t// continue to prefer linear search.\n\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tc.state.count++\n\tc.state.sum.AddNumber(kind, number)\n\tc.state.bucketCounts[bucketID]++\n\n\treturn nil\n}", "func (x *Index) Lookup(s []byte, n int) (result []int) {}", "func (x *Index) Lookup(s []byte, n int) (result []int)", "func (idx *LearnedIndex) Lookup(key float64) (offsets []int, err error) {\n\tguess, lower, upper := idx.GuessIndex(key)\n\ti := 0\n\t// k, o, err := store.Get(guess_i)\n\t// st, err := store.STExtract(guess_i+1, upper+1)\n\n\tif key > idx.ST.Keys[guess] {\n\t\tsubKeys := idx.ST.Keys[guess+1 : upper+1]\n\t\ti = sort.SearchFloat64s(subKeys, key) + guess + 1\n\t} else if key <= idx.ST.Keys[guess] {\n\t\tsubKeys := idx.ST.Keys[lower : guess+1]\n\t\ti = sort.SearchFloat64s(subKeys, key) + lower\n\t}\n\n\t// iterate to get all equal keys\n\tfor ; i < upper+1; i++ {\n\t\tif idx.ST.Keys[i] == key {\n\t\t\toffsets = append(offsets, idx.ST.Offsets[i])\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(offsets) == 0 {\n\t\terr = fmt.Errorf(\"The following key <%f> is not found in the index\", key)\n\t}\n\n\treturn offsets, err\n}", "func (m *cmap) insert(key keyt, upd Memop) (ret MemopRes) {\n\tnow := time.Now()\n\tival := cval{key: key}\n\n\t// we do some additional trickery here so that when we recompute bins\n\t// in the loop below, we don't need to do further allocations\n\tnh := int(m.hashes)\n\tvar bins_ [MAX_HASHES]int\n\tbins := bins_[0:nh]\n\tm.kbins(key, bins)\n\n\t// Check if this element is already present\n\tm.lock_in_order(bins...)\n\tfor bi, bin := range bins {\n\t\tb := &m.bins[bin]\n\t\tki, v := b.has(key, now)\n\t\tif ki != -1 {\n\t\t\tival.bno = bi\n\t\t\tival.val, ret = upd(v.val, true)\n\t\t\tif ret.T == STORED {\n\t\t\t\tb.setv(ki, &ival)\n\t\t\t\tb.vals[ki].read = true\n\t\t\t\tb.vals[ki].tag = key[0]\n\t\t\t}\n\t\t\tm.unlock(bins...)\n\t\t\treturn\n\t\t}\n\t}\n\tm.unlock(bins...)\n\n\t// if the operation fails if a current element does not exist,\n\t// there is no point doing the expensive insert search\n\t_, ret = upd(Memval{}, false)\n\tif ret.T != STORED {\n\t\treturn ret\n\t}\n\n\t// Item not currently present, is there room without a search?\n\tfor i, b := range bins {\n\t\tif m.bins[b].available(now) {\n\t\t\tival.bno = i\n\t\t\tret = m.bins[b].add(&ival, upd, now)\n\t\t\tif ret.T != SERVER_ERROR {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Keep trying to find a cuckoo path of replacements\n\tfor {\n\t\tpath := m.search(now, bins...)\n\t\tif path == nil {\n\t\t\tif m.evict() {\n\t\t\t\treturn m.insert(key, upd)\n\t\t\t}\n\t\t\treturn MemopRes{\n\t\t\t\tT: SERVER_ERROR,\n\t\t\t\tE: errors.New(\"no storage space found for element\"),\n\t\t\t}\n\t\t}\n\n\t\tfreeing := path[0].from\n\n\t\t// recompute bins because #hashes might have changed\n\t\tif nh != int(m.hashes) {\n\t\t\tnh = int(m.hashes)\n\t\t\tbins = bins_[0:nh]\n\t\t\tm.kbins(key, bins)\n\t\t}\n\n\t\t// sanity check that this path will make room in the right bin\n\t\ttobin := -1\n\t\tfor i, bin := range bins {\n\t\t\tif freeing == bin {\n\t\t\t\ttobin = i\n\t\t\t}\n\t\t}\n\t\tif tobin == -1 {\n\t\t\tpanic(fmt.Sprintf(\"path %v leads to occupancy in bin %v, but is unhelpful for key %s with bins: %v\", path, freeing, key, bins))\n\t\t}\n\n\t\t// only after the search do we acquire locks\n\t\tif m.validate_execute(path, now) {\n\t\t\tival.bno = tobin\n\n\t\t\t// after replacements, someone else might have beaten\n\t\t\t// us to the free slot, so we need to do add under a\n\t\t\t// lock too\n\t\t\tret = m.bins[freeing].add(&ival, upd, now)\n\t\t\tif ret.T != SERVER_ERROR {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (routingTable *RoutingTable) getBucketIndex(id *KademliaID) int {\n\troutingTable.mutex.Lock()\n\tdefer routingTable.mutex.Unlock()\n\n\tdistance := id.CalcDistance(routingTable.me.ID)\n\tfor i := 0; i < IDLength; i++ {\n\t\tfor j := 0; j < 8; j++ {\n\t\t\tif (distance[i]>>uint8(7-j))&0x1 != 0 {\n\t\t\t\treturn i*8 + j\n\t\t\t}\n\t\t}\n\t}\n\n\treturn IDLength*8 - 1\n}", "func (ix *IndexedBucket) indexLookup(bucket *bolt.Bucket, key string) []string {\n\tsearchPrefix := []byte(key)\n\tsearchPrefixLen := len(searchPrefix)\n\tret := []string{}\n\tcursor := bucket.Cursor()\n\tfor k, _ := cursor.Seek(searchPrefix); bytes.HasPrefix(k, searchPrefix); k, _ = cursor.Next() {\n\t\tkeyPrefixLen, val := fromIndexEntry(k)\n\t\t// Make sure the index value matches the target exactly.\n\t\tif keyPrefixLen != searchPrefixLen {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, val)\n\t}\n\treturn ret\n}", "func Lookup(k byte, x *[16]byte) int32", "func BinarySearch(target_map []int, value int) int {\n\n\tstart_index := 0\n\tend_index := len(target_map) - 1\n\n\tfor start_index <= end_index {\n\t\tmedian := (start_index + end_index) / 2\n\n\t\tif target_map[median] < value {\n\t\t\tstart_index = median + 1\n\t\t} else {\n\t\t\tend_index = median - 1\n\t\t}\n\t}\n\n\tif start_index == len(target_map) || target_map[start_index] != value {\n\t\treturn -1\n\t} else {\n\t\treturn start_index\n\t}\n}", "func (shard *hashShard) searchToInsert(key KeyType, hashValue IndexType) IndexType {\n\t// hval := shard.mhash(key)\n\tvar x IndexType = 0\n\tidx := (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\n\tfor (*shard.data)[idx].isOccupied {\n\t\tx++\n\t\tidx = (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\t}\n\treturn idx\n}", "func TestLogarithmIndexMin(t *testing.T) {\n\tfor scale := MinScale; scale <= MaxScale; scale++ {\n\t\tm, err := NewMapping(scale)\n\t\trequire.NoError(t, err)\n\n\t\tminIndex := m.MapToIndex(MinValue)\n\n\t\tmapped, err := m.LowerBoundary(minIndex)\n\t\trequire.NoError(t, err)\n\n\t\tcorrectMinIndex := int64(exponent.MinNormalExponent) << scale\n\t\trequire.Greater(t, correctMinIndex, int64(math.MinInt32))\n\n\t\tcorrectMapped := roundedBoundary(scale, int32(correctMinIndex))\n\t\trequire.Equal(t, correctMapped, MinValue)\n\t\trequire.InEpsilon(t, mapped, MinValue, 1e-6)\n\n\t\trequire.Equal(t, minIndex, int32(correctMinIndex))\n\n\t\t// Subnormal values map to the min index:\n\t\trequire.Equal(t, m.MapToIndex(MinValue/2), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/3), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/100), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1050), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1.1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1074), int32(correctMinIndex))\n\n\t\t// One smaller index will underflow.\n\t\t_, err = m.LowerBoundary(minIndex - 1)\n\t\trequire.Equal(t, err, mapping.ErrUnderflow)\n\t}\n}", "func BuildColumn(ctx context.Context, numBuckets, id int64, ndv int64, count int64, samples []types.Datum) (*Histogram, error) {\n\tif count == 0 {\n\t\treturn &Histogram{ID: id}, nil\n\t}\n\tsc := ctx.GetSessionVars().StmtCtx\n\terr := types.SortDatums(sc, samples)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\thg := &Histogram{\n\t\tID: id,\n\t\tNDV: ndv,\n\t\tBuckets: make([]Bucket, 1, numBuckets),\n\t}\n\tvaluesPerBucket := float64(count)/float64(numBuckets) + 1\n\n\t// As we use samples to build the histogram, the bucket number and repeat should multiply a factor.\n\tsampleFactor := float64(count) / float64(len(samples))\n\tndvFactor := float64(count) / float64(ndv)\n\tif ndvFactor > sampleFactor {\n\t\tndvFactor = sampleFactor\n\t}\n\tbucketIdx := 0\n\tvar lastCount int64\n\tfor i := int64(0); i < int64(len(samples)); i++ {\n\t\tcmp, err := hg.Buckets[bucketIdx].Value.CompareDatum(sc, samples[i])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\ttotalCount := float64(i+1) * sampleFactor\n\t\tif cmp == 0 {\n\t\t\t// The new item has the same value as current bucket value, to ensure that\n\t\t\t// a same value only stored in a single bucket, we do not increase bucketIdx even if it exceeds\n\t\t\t// valuesPerBucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\tif float64(hg.Buckets[bucketIdx].Repeats) == ndvFactor {\n\t\t\t\thg.Buckets[bucketIdx].Repeats = int64(2 * sampleFactor)\n\t\t\t} else {\n\t\t\t\thg.Buckets[bucketIdx].Repeats += int64(sampleFactor)\n\t\t\t}\n\t\t} else if totalCount-float64(lastCount) <= valuesPerBucket {\n\t\t\t// The bucket still have room to store a new item, update the bucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\thg.Buckets[bucketIdx].Value = samples[i]\n\t\t\thg.Buckets[bucketIdx].Repeats = int64(ndvFactor)\n\t\t} else {\n\t\t\tlastCount = hg.Buckets[bucketIdx].Count\n\t\t\t// The bucket is full, store the item in the next bucket.\n\t\t\tbucketIdx++\n\t\t\thg.Buckets = append(hg.Buckets, Bucket{\n\t\t\t\tCount: int64(totalCount),\n\t\t\t\tValue: samples[i],\n\t\t\t\tRepeats: int64(ndvFactor),\n\t\t\t})\n\t\t}\n\t}\n\treturn hg, nil\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}", "func (this *MyHashMap) Get(key int) int {\n\tindex := key & (this.b - 1)\n\tfor e := range this.bucket[index] {\n\t\tif this.bucket[index][e].key == key {\n\t\t\treturn this.bucket[index][e].value\n\t\t}\n\t}\n\treturn -1\n}", "func scaledValue(unscaled *big.Int, scale, newScale int) int64 {\n\tdif := scale - newScale\n\tif dif == 0 {\n\t\treturn unscaled.Int64()\n\t}\n\n\t// Handle scale up\n\t// This is an easy case, we do not need to care about rounding and overflow.\n\t// If any intermediate operation causes overflow, the result will overflow.\n\tif dif < 0 {\n\t\treturn unscaled.Int64() * int64(math.Pow10(-dif))\n\t}\n\n\t// Handle scale down\n\t// We have to be careful about the intermediate operations.\n\n\t// fast path when unscaled < max.Int64 and exp(10,dif) < max.Int64\n\tconst log10MaxInt64 = 19\n\tif unscaled.Cmp(maxInt64) < 0 && dif < log10MaxInt64 {\n\t\tdivide := int64(math.Pow10(dif))\n\t\tresult := unscaled.Int64() / divide\n\t\tmod := unscaled.Int64() % divide\n\t\tif mod != 0 {\n\t\t\treturn result + 1\n\t\t}\n\t\treturn result\n\t}\n\n\t// We should only convert back to int64 when getting the result.\n\tdivisor := intPool.Get().(*big.Int)\n\texp := intPool.Get().(*big.Int)\n\tresult := intPool.Get().(*big.Int)\n\tdefer func() {\n\t\tintPool.Put(divisor)\n\t\tintPool.Put(exp)\n\t\tintPool.Put(result)\n\t}()\n\n\t// divisor = 10^(dif)\n\t// TODO: create loop up table if exp costs too much.\n\tdivisor.Exp(bigTen, exp.SetInt64(int64(dif)), nil)\n\t// reuse exp\n\tremainder := exp\n\n\t// result = unscaled / divisor\n\t// remainder = unscaled % divisor\n\tresult.DivMod(unscaled, divisor, remainder)\n\tif remainder.Sign() != 0 {\n\t\treturn result.Int64() + 1\n\t}\n\n\treturn result.Int64()\n}", "func (e errChunkIterator) AtHistogram() (int64, *histogram.Histogram) { panic(\"not implemented\") }", "func (s *CollapsingLowestDenseStore) adjust(newMinIndex, newMaxIndex int) {\n\tif newMaxIndex-newMinIndex+1 > len(s.bins) {\n\t\t// The range of indices is too wide, buckets of lowest indices need to be collapsed.\n\t\tnewMinIndex = newMaxIndex - len(s.bins) + 1\n\t\tif newMinIndex >= s.maxIndex {\n\t\t\t// There will be only one non-empty bucket.\n\t\t\ts.bins = make([]float64, len(s.bins))\n\t\t\ts.offset = newMinIndex\n\t\t\ts.minIndex = newMinIndex\n\t\t\ts.bins[0] = s.count\n\t\t} else {\n\t\t\tshift := s.offset - newMinIndex\n\t\t\tif shift < 0 {\n\t\t\t\t// Collapse the buckets.\n\t\t\t\tn := float64(0)\n\t\t\t\tfor i := s.minIndex; i < newMinIndex; i++ {\n\t\t\t\t\tn += s.bins[i-s.offset]\n\t\t\t\t}\n\t\t\t\ts.resetBins(s.minIndex, newMinIndex-1)\n\t\t\t\ts.bins[newMinIndex-s.offset] += n\n\t\t\t\ts.minIndex = newMinIndex\n\t\t\t\t// Shift the buckets to make room for newMaxIndex.\n\t\t\t\ts.shiftCounts(shift)\n\t\t\t} else {\n\t\t\t\t// Shift the buckets to make room for newMinIndex.\n\t\t\t\ts.shiftCounts(shift)\n\t\t\t\ts.minIndex = newMinIndex\n\t\t\t}\n\t\t}\n\t\ts.maxIndex = newMaxIndex\n\t\ts.isCollapsed = true\n\t} else {\n\t\ts.centerCounts(newMinIndex, newMaxIndex)\n\t}\n}", "func (h *binaryHeap) Index(val int) int {\n\tfor i, v := range h.items {\n\t\tif v == val {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func (pal *CGBPalette) updateIndex(value byte) {\n\tpal.index = value & 0x3F\n\tpal.inc = bits.Test(value, 7)\n}", "func (d *Dictionary) GetValueIndex(i int) int {\n\tindiceData := d.data.buffers[1].Bytes()\n\t// we know the value is non-negative per the spec, so\n\t// we can use the unsigned value regardless.\n\tswitch d.indices.DataType().ID() {\n\tcase arrow.UINT8, arrow.INT8:\n\t\treturn int(uint8(indiceData[d.data.offset+i]))\n\tcase arrow.UINT16, arrow.INT16:\n\t\treturn int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])\n\tcase arrow.UINT32, arrow.INT32:\n\t\tidx := arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert(bits.UintSize == 64 || idx <= math.MaxInt32, \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\tcase arrow.UINT64, arrow.INT64:\n\t\tidx := arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i]\n\t\tdebug.Assert((bits.UintSize == 32 && idx <= math.MaxInt32) || (bits.UintSize == 64 && idx <= math.MaxInt64), \"arrow/dictionary: truncation of index value\")\n\t\treturn int(idx)\n\t}\n\tdebug.Assert(false, \"unreachable dictionary index\")\n\treturn -1\n}", "func (t *nfkcTrie) lookupValue(n uint32, b byte) uint16 {\n\tswitch {\n\tcase n < 90:\n\t\treturn uint16(nfkcValues[n<<6+uint32(b)])\n\tdefault:\n\t\tn -= 90\n\t\treturn uint16(nfkcSparse.lookup(n, b))\n\t}\n}", "func getIndexAndFingerprint(data []byte, bucketPow uint) (uint, fingerprint) {\n\thash := metro.Hash64(data, 1337)\n\tfp := getFingerprint(hash)\n\t// Use most significant bits for deriving index.\n\ti1 := uint(hash>>32) & masks[bucketPow]\n\treturn i1, fingerprint(fp)\n}", "func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 {\n\tswitch {\n\tcase n < 44:\n\t\treturn uint16(nfcValues[n<<6+uint32(b)])\n\tdefault:\n\t\tn -= 44\n\t\treturn uint16(nfcSparse.lookup(n, b))\n\t}\n}", "func getBucketScore(bkts []bucket, totalCount float64, id int) bucketScore {\n\tpreCount, count := float64(bkts[id-1].Count), float64(bkts[id].Count)\n\t// do not merge if the result bucket is too large\n\tif (preCount + count) > maxBucketFraction*totalCount {\n\t\treturn bucketScore{id, math.MaxFloat64}\n\t}\n\t// Merge them if the result bucket is already too small.\n\tif (preCount + count) < minBucketFraction*totalCount {\n\t\treturn bucketScore{id, 0}\n\t}\n\tlow, mid, high := bkts[id-1].Lower, bkts[id-1].Upper, bkts[id].Upper\n\t// If we choose to merge, err is the absolute estimate error for the previous bucket.\n\terr := calcFraction4Datums(low, high, mid)*(preCount+count) - preCount\n\treturn bucketScore{id, math.Abs(err / (preCount + count))}\n}", "func (id ID) BucketIndex(root ID, limit int) int {\n\tdistance := id.Distance(root).Int()\n\tfor i := 0; i < limit; i++ {\n\t\tif b := distance.Bit(i); b != 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\t// IDs are equal.\n\treturn limit - 1\n}", "func (c *Float64sCache) index(size int) int {\n\tindex := -1\n\tfor i := range c.ps {\n\t\tif c.ps[i].size < size {\n\t\t\tcontinue\n\t\t}\n\t\tif c.ps[i].size == size {\n\t\t\tindex = i\n\t\t}\n\t\tbreak\n\t}\n\treturn index\n}", "func checkIndexBounds(indices *Data, upperlimit uint64) error {\n\tif indices.length == 0 {\n\t\treturn nil\n\t}\n\n\tvar maxval uint64\n\tswitch indices.dtype.ID() {\n\tcase arrow.UINT8:\n\t\tmaxval = math.MaxUint8\n\tcase arrow.UINT16:\n\t\tmaxval = math.MaxUint16\n\tcase arrow.UINT32:\n\t\tmaxval = math.MaxUint32\n\tcase arrow.UINT64:\n\t\tmaxval = math.MaxUint64\n\t}\n\t// for unsigned integers, if the values array is larger than the maximum\n\t// index value (especially for UINT8/UINT16), then there's no need to\n\t// boundscheck. for signed integers we still need to bounds check\n\t// because a value could be < 0.\n\tisSigned := maxval == 0\n\tif !isSigned && upperlimit > maxval {\n\t\treturn nil\n\t}\n\n\tstart := indices.offset\n\tend := indices.offset + indices.length\n\n\t// TODO(ARROW-15950): lift BitSetRunReader from parquet to utils\n\t// and use it here for performance improvement.\n\n\tswitch indices.dtype.ID() {\n\tcase arrow.INT8:\n\t\tdata := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt8(data[start:end])\n\t\tif min < 0 || max >= int8(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT8:\n\t\tdata := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint8(data[start:end])\n\t\tif max >= uint8(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT16:\n\t\tdata := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt16(data[start:end])\n\t\tif min < 0 || max >= int16(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT16:\n\t\tdata := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint16(data[start:end])\n\t\tif max >= uint16(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT32:\n\t\tdata := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt32(data[start:end])\n\t\tif min < 0 || max >= int32(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT32:\n\t\tdata := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint32(data[start:end])\n\t\tif max >= uint32(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: max: %d\", max)\n\t\t}\n\tcase arrow.INT64:\n\t\tdata := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\tmin, max := utils.GetMinMaxInt64(data[start:end])\n\t\tif min < 0 || max >= int64(upperlimit) {\n\t\t\treturn fmt.Errorf(\"contains out of bounds index: min: %d, max: %d\", min, max)\n\t\t}\n\tcase arrow.UINT64:\n\t\tdata := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())\n\t\t_, max := utils.GetMinMaxUint64(data[indices.offset : indices.offset+indices.length])\n\t\tif max >= upperlimit {\n\t\t\treturn fmt.Errorf(\"contains out of bounds value: max: %d\", max)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid type for bounds checking: %T\", indices.dtype)\n\t}\n\n\treturn nil\n}", "func getIndex(k uint64, p, pPrime uint) uint64 {\n\tif k&1 == 1 {\n\t\tindex := extractShift(k, 7, p+6) // erratum from paper, start index is 7, not 6\n\t\treturn index\n\t} else {\n\t\tindex := extractShift(k, 1, p) // erratum from paper, end index is p, not p+1\n\t\treturn index\n\t}\n}", "func (it *emptyIterator) AtHistogram() (int64, *histogram.Histogram) { return 0, nil }", "func (m HMSketch) insert(kvs map[string]string, value, count float64) HMSketch {\n\thMux.Lock()\n\tfor key, val := range kvs {\n\t\tlocation := hash(key, val)\n\t\tif _, ok := m.Index[location]; !ok {\n\t\t\tm.Index[location] = m.Max\n\t\t\tm.Max++\n\t\t\tm.Registers = append(m.Registers, hist.New(m.Resolution))\n\t\t}\n\t\tm.Registers[m.Index[location]] = m.Registers[m.Index[location]].Insert(value, count)\n\t}\n\thMux.Unlock()\n\treturn m\n}", "func (h *batchHistogram) update(his *metrics.Float64Histogram, sum float64) {\n\tcounts, buckets := his.Counts, his.Buckets\n\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\t// Clear buckets.\n\tfor i := range h.counts {\n\t\th.counts[i] = 0\n\t}\n\t// Copy and reduce buckets.\n\tvar j int\n\tfor i, count := range counts {\n\t\th.counts[j] += count\n\t\tif buckets[i+1] == h.buckets[j+1] {\n\t\t\tj++\n\t\t}\n\t}\n\tif h.hasSum {\n\t\th.sum = sum\n\t}\n}", "func (h *hashLongestMatchQuickly) Store(data []byte, mask uint, ix uint) {\n\tvar key uint32 = h.HashBytes(data[ix&mask:])\n\tvar off uint32 = uint32(ix>>3) % uint32(h.bucketSweep)\n\t/* Wiggle the value with the bucket sweep range. */\n\th.buckets[key+off] = uint32(ix)\n}", "func CalculateBucketID(params []*dpfpb.DpfParameters, prefixes [][]uint128.Uint128, levels []int32, previousLevel int32) ([]uint128.Uint128, error) {\n\tif err := CheckExpansionParameters(params, prefixes, levels, previousLevel); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// For direct expansion, return empty slice to avoid generating extra data.\n\t// Because in this case, the bucket ID equals the vector index.\n\tif len(levels) == 1 && previousLevel == -1 {\n\t\treturn nil, nil\n\t}\n\n\tvar prefixBitSize int32\n\tif len(levels) > 1 {\n\t\tprefixBitSize = params[levels[len(levels)-2]].GetLogDomainSize()\n\t} else {\n\t\tprefixBitSize = params[previousLevel].GetLogDomainSize()\n\t}\n\tfinalBitSize := params[levels[len(levels)-1]].GetLogDomainSize()\n\tfinalPrefixes := prefixes[len(prefixes)-1]\n\n\texpansionBits := finalBitSize - prefixBitSize\n\texpansionSize := uint64(1) << expansionBits\n\tids := make([]uint128.Uint128, uint64(len(finalPrefixes))*expansionSize)\n\ti := uint64(0)\n\tfor _, p := range finalPrefixes {\n\t\tprefix := p.Lsh(uint(expansionBits))\n\t\tfor j := uint64(0); j < expansionSize; j++ {\n\t\t\tids[i] = prefix.Or(uint128.From64(j))\n\t\t\ti++\n\t\t}\n\t}\n\treturn ids, nil\n}", "func buildBucketFeedback(h *Histogram, feedback *QueryFeedback) (map[int]*BucketFeedback, int) {\n\tbktID2FB := make(map[int]*BucketFeedback)\n\tif len(feedback.Feedback) == 0 {\n\t\treturn bktID2FB, 0\n\t}\n\ttotal := 0\n\tsc := &stmtctx.StatementContext{TimeZone: time.UTC}\n\tmin, max := GetMinValue(h.Tp), GetMaxValue(h.Tp)\n\tfor _, fb := range feedback.Feedback {\n\t\tskip, err := fb.adjustFeedbackBoundaries(sc, &min, &max)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"adjust feedback boundaries failed\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif skip {\n\t\t\tcontinue\n\t\t}\n\t\tidx := h.Bounds.UpperBound(0, fb.Lower)\n\t\tbktIdx := 0\n\t\t// The last bucket also stores the feedback that falls outside the upper bound.\n\t\tif idx >= h.Bounds.NumRows()-1 {\n\t\t\tbktIdx = h.Len() - 1\n\t\t} else if h.Len() == 1 {\n\t\t\tbktIdx = 0\n\t\t} else {\n\t\t\tif idx == 0 {\n\t\t\t\tbktIdx = 0\n\t\t\t} else {\n\t\t\t\tbktIdx = (idx - 1) / 2\n\t\t\t}\n\t\t\t// Make sure that this feedback lies within the bucket.\n\t\t\tif chunk.Compare(h.Bounds.GetRow(2*(bktIdx+1)), 0, fb.Upper) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ttotal++\n\t\tbkt := bktID2FB[bktIdx]\n\t\tif bkt == nil {\n\t\t\tbkt = &BucketFeedback{lower: h.GetLower(bktIdx), upper: h.GetUpper(bktIdx)}\n\t\t\tbktID2FB[bktIdx] = bkt\n\t\t}\n\t\tbkt.feedback = append(bkt.feedback, fb)\n\t\t// Update the bound if necessary.\n\t\tres, err := bkt.lower.CompareDatum(nil, fb.Lower)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"compare datum failed\", zap.Any(\"value1\", bkt.lower), zap.Any(\"value2\", fb.Lower), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif res > 0 {\n\t\t\tbkt.lower = fb.Lower\n\t\t}\n\t\tres, err = bkt.upper.CompareDatum(nil, fb.Upper)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Debug(\"compare datum failed\", zap.Any(\"value1\", bkt.upper), zap.Any(\"value2\", fb.Upper), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif res < 0 {\n\t\t\tbkt.upper = fb.Upper\n\t\t}\n\t}\n\treturn bktID2FB, total\n}", "func TestExponentIndexMin(t *testing.T) {\n\tfor scale := MinScale; scale <= MaxScale; scale++ {\n\t\tm, err := NewMapping(scale)\n\t\trequire.NoError(t, err)\n\n\t\tminIndex := m.MapToIndex(MinValue)\n\n\t\tmapped, err := m.LowerBoundary(minIndex)\n\t\trequire.NoError(t, err)\n\n\t\tcorrectMinIndex := int64(exponent.MinNormalExponent) << scale\n\t\trequire.Greater(t, correctMinIndex, int64(math.MinInt32))\n\n\t\tcorrectMapped := roundedBoundary(scale, int32(correctMinIndex))\n\t\trequire.Equal(t, correctMapped, MinValue)\n\t\trequire.InEpsilon(t, mapped, MinValue, 1e-6)\n\n\t\trequire.Equal(t, minIndex, int32(correctMinIndex))\n\n\t\t// Subnormal values map to the min index:\n\t\trequire.Equal(t, m.MapToIndex(MinValue/2), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/3), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(MinValue/100), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1050), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1.1p-1073), int32(correctMinIndex))\n\t\trequire.Equal(t, m.MapToIndex(0x1p-1074), int32(correctMinIndex))\n\n\t\t// One smaller index will underflow.\n\t\t_, err = m.LowerBoundary(minIndex - 1)\n\t\trequire.Equal(t, err, mapping.ErrUnderflow)\n\t}\n}", "func (h *indexedHeap) put(key string, exp uint64, bytes uint) int {\n\tidx := 0\n\tif len(h.entries) < h.maxidx {\n\t\t// Steal index from previously removed entry\n\t\t// capacity > size is guaranteed\n\t\tn := len(h.entries)\n\t\tidx = h.entries[:n+1][n].idx\n\t} else {\n\t\tidx = h.maxidx\n\t\th.maxidx++\n\t\th.indices = append(h.indices, idx)\n\t}\n\t// Push manually to avoid allocation\n\th.pushInternal(heapEntry{\n\t\tkey: key, exp: exp, idx: idx, bytes: bytes,\n\t})\n\theap.Fix(h, h.Len()-1)\n\treturn idx\n}", "func UIntIdx(list []uint, indices []int, element uint) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element > value {\n\t\t\tleft = middle + 1\n\t\t} else if element < value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func getHistogram(src [][3]int, size float64, pixels *[HistSize][3]float64, hist *[HistSize]float64) {\n\tvar ind, r, g, b, i int\n\tvar inr, ing, inb int\n\n\tfor i = range src {\n\t\tr = src[i][0]\n\t\tg = src[i][1]\n\t\tb = src[i][2]\n\n\t\tinr = r >> Shift\n\t\ting = g >> Shift\n\t\tinb = b >> Shift\n\n\t\tind = (inr << (2 * HistBits)) + (ing << HistBits) + inb\n\t\tpixels[ind][0], pixels[ind][1], pixels[ind][2] = float64(r), float64(g), float64(b)\n\t\thist[ind]++\n\t}\n\n\t// normalize weight by the number of pixels in the image\n\tfor i = 0; i < HistSize; i++ {\n\t\thist[i] /= size\n\t}\n}", "func interpolationSearch(x int, arr []int) int {\r\n\r\n\t//sort array\r\n\tsort.Ints(arr)\r\n\r\n\tfmt.Printf(\"Sorted: %v, arr lenght:%d\\n\", arr, len(arr))\r\n\r\n\tif len(arr) != 0 {\r\n\r\n\t\tmiddle :=\r\n\t\t\t((x - arr[0]) * (len(arr) - 0)) / (arr[len(arr)-1] -\r\n\t\t\t\tarr[0])\r\n\r\n\t\tfmt.Printf(\"middle:%d\\n\", middle)\r\n\r\n\t\tif arr[middle] == x {\r\n\t\t\tfmt.Printf(\"Finded!, value: %d\\n\", arr[middle])\r\n\t\t\treturn arr[middle]\r\n\t\t}\r\n\r\n\t\t//if middle is greater than x\r\n\t\tif x < arr[middle] {\r\n\t\t\treturn binarySearch(x, arr[0:middle])\r\n\t\t}\r\n\r\n\t\t//if middle is less than x\r\n\t\tif x > arr[middle] {\r\n\t\t\treturn binarySearch(x, arr[middle:len(arr)])\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tfmt.Printf(\"Cannot find: %d\\n\", x)\r\n\treturn -1\r\n\r\n}", "func (s *segmentKeysIndex) lookup(key []byte) (leftPos int, rightPos int) {\n\ti, j := 0, s.numKeys\n\n\tif i == j || s.numKeys < 2 {\n\t\t// The index either wasn't used or isn't of any use.\n\t\trightPos = s.srcKeyCount\n\t\treturn\n\t}\n\n\t// If key smaller than the first key, return early.\n\tkeyStart := s.offsets[0]\n\tkeyEnd := s.offsets[1]\n\tcmp := bytes.Compare(key, s.data[keyStart:keyEnd])\n\tif cmp < 0 {\n\t\treturn\n\t}\n\n\tindexOfLastKey := s.numKeys - 1\n\n\t// If key larger than last key, return early.\n\tkeyStart = s.offsets[indexOfLastKey]\n\tkeyEnd = uint32(s.numKeyBytes)\n\tcmp = bytes.Compare(s.data[keyStart:keyEnd], key)\n\tif cmp < 0 {\n\t\tleftPos = (indexOfLastKey) * s.hop\n\t\trightPos = s.srcKeyCount\n\t\treturn\n\t}\n\n\tfor i < j {\n\t\th := i + (j-i)/2\n\n\t\tkeyStart = s.offsets[h]\n\t\tif h < indexOfLastKey {\n\t\t\tkeyEnd = s.offsets[h+1]\n\t\t} else {\n\t\t\tkeyEnd = uint32(s.numKeyBytes)\n\t\t}\n\n\t\tcmp = bytes.Compare(s.data[keyStart:keyEnd], key)\n\t\tif cmp == 0 {\n\t\t\tleftPos = h * s.hop\n\t\t\trightPos = leftPos + 1\n\t\t\treturn // Direct hit.\n\t\t} else if cmp < 0 {\n\t\t\tif i == h {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti = h\n\t\t} else {\n\t\t\tj = h\n\t\t}\n\t}\n\n\tleftPos = i * s.hop\n\trightPos = j * s.hop\n\n\treturn\n}", "func UIntPtrIdx(list []uintptr, indices []int, element uintptr) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element > value {\n\t\t\tleft = middle + 1\n\t\t} else if element < value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func (hm *HashMap) getIndex(key string) uint64 {\n\thasher := hm.hasher.Get().(hash.Hash64)\n\thasher.Reset()\n\thasher.Write([]byte(key))\n\tindex := hasher.Sum64() % hm.size\n\thm.hasher.Put(hasher)\n\treturn index\n}", "func (v Data) BiSearch(value PicData, cmp func(a, b PicData) uint8) (int, bool) {\n\tstart, end := 0, len(v)\n\tif start == end {\n\t\treturn -1, false\n\t}\n\tfor {\n\t\tmid := start + (end-start)/2\n\t\tswitch cmp(v[mid], value) {\n\t\tcase 0:\n\t\t\treturn mid, true\n\t\tcase 1:\n\t\t\tend = mid + 0\n\t\tcase 2:\n\t\t\tstart = mid + 1\n\t\t}\n\n\t\tif start == end {\n\t\t\treturn start, start < len(v) && cmp(v[start], value) == 0\n\t\t}\n\t}\n}", "func (h *hashMap) initializeBucket(index uint32) *bucket {\n\tparentIndex := h.getParentIndex(index)\n\n\tif h.bucketSegments.getBucket(parentIndex) == nil {\n\t\th.initializeBucket(parentIndex)\n\t}\n\n\tdummy := h.bucketSegments.getBucket(parentIndex).getDummy(index)\n\n\tif dummy != nil {\n\t\th.bucketSegments.setBucket(index, dummy)\n\t}\n\n\treturn dummy\n}", "func lookupBinarySearch(vertical bool, lookupValue, lookupArray, matchMode, searchMode formulaArg) (matchIdx int, wasExact bool) {\n\tvar tableArray []formulaArg\n\tif vertical {\n\t\tfor _, row := range lookupArray.Matrix {\n\t\t\ttableArray = append(tableArray, row[0])\n\t\t}\n\t} else {\n\t\ttableArray = lookupArray.Matrix[0]\n\t}\n\tlow, high, lastMatchIdx := 0, len(tableArray)-1, -1\n\tcount := high\n\tfor low <= high {\n\t\tmid := low + (high-low)/2\n\t\tcell := tableArray[mid]\n\t\tlhs := cell\n\t\tif lookupValue.Type == ArgNumber {\n\t\t\tif lhs = cell.ToNumber(); lhs.Type == ArgError {\n\t\t\t\tlhs = cell\n\t\t\t}\n\t\t} else if lookupValue.Type == ArgMatrix && vertical {\n\t\t\tlhs = lookupArray\n\t\t} else if lookupValue.Type == ArgString {\n\t\t\tlhs = newStringFormulaArg(cell.Value())\n\t\t}\n\t\tresult := compareFormulaArg(lhs, lookupValue, matchMode, false)\n\t\tif result == criteriaEq {\n\t\t\tmatchIdx, wasExact = mid, true\n\t\t\tif searchMode.Number == searchModeDescBinary {\n\t\t\t\tmatchIdx = count - matchIdx\n\t\t\t}\n\t\t\treturn\n\t\t} else if result == criteriaG {\n\t\t\thigh = mid - 1\n\t\t} else if result == criteriaL {\n\t\t\tmatchIdx = mid\n\t\t\tif cell.Type != ArgEmpty {\n\t\t\t\tlastMatchIdx = matchIdx\n\t\t\t}\n\t\t\tlow = mid + 1\n\t\t} else {\n\t\t\treturn -1, false\n\t\t}\n\t}\n\tmatchIdx, wasExact = lastMatchIdx, true\n\treturn\n}", "func (a *Agent) InsertInterpolate(lower float64, upper float64, count uint) {\n\tkeys := make([]Key, 0)\n\tfor k := agentConfig.key(lower); k <= agentConfig.key(upper); k++ {\n\t\tkeys = append(keys, k)\n\t}\n\twhatsLeft := int(count)\n\tdistance := upper - lower\n\tkStartIdx := 0\n\tlowerB := agentConfig.binLow(keys[kStartIdx])\n\tkEndIdx := 1\n\tvar remainder float64\n\tfor kEndIdx < len(keys) && whatsLeft > 0 {\n\t\tupperB := agentConfig.binLow(keys[kEndIdx])\n\t\t// ((upperB - lowerB) / distance) is the ratio of the distance between the current buckets to the total distance\n\t\t// which tells us how much of the remaining value to put in this bucket\n\t\tfkn := ((upperB - lowerB) / distance) * float64(count)\n\t\t// only track the remainder if fkn is >1 because we designed this to not store a bunch of 0 count buckets\n\t\tif fkn > 1 {\n\t\t\tremainder += fkn - float64(int(fkn))\n\t\t}\n\t\tkn := int(fkn)\n\t\tif remainder > 1 {\n\t\t\tkn++\n\t\t\tremainder--\n\t\t}\n\t\tif kn > 0 {\n\t\t\t// Guard against overflow at the end\n\t\t\tif kn > whatsLeft {\n\t\t\t\tkn = whatsLeft\n\t\t\t}\n\t\t\ta.Sketch.Basic.InsertN(lowerB, float64(kn))\n\t\t\ta.CountBuf = append(a.CountBuf, KeyCount{k: keys[kStartIdx], n: uint(kn)})\n\t\t\twhatsLeft -= kn\n\t\t\tkStartIdx = kEndIdx\n\t\t\tlowerB = upperB\n\t\t}\n\t\tkEndIdx++\n\t}\n\tif whatsLeft > 0 {\n\t\ta.Sketch.Basic.InsertN(agentConfig.binLow(keys[kStartIdx]), float64(whatsLeft))\n\t\ta.CountBuf = append(a.CountBuf, KeyCount{k: keys[kStartIdx], n: uint(whatsLeft)})\n\t}\n\ta.flush()\n}", "func (idx *LearnedIndex) GuessIndex(key float64) (guess, lower, upper int) {\n\tguess = scale(idx.M.Predict(key), idx.Len)\n\tlower = idx.MinErrBound + guess\n\tif lower < 0 {\n\t\tlower = 0\n\t} else if lower > idx.Len-1 {\n\t\tlower = idx.Len - 1\n\t}\n\tupper = guess + idx.MaxErrBound\n\tif upper > idx.Len-1 {\n\t\tupper = idx.Len - 1\n\t} else if upper < 0 {\n\t\tupper = 0\n\t}\n\n\tif guess < 0 {\n\t\tguess = 0\n\t} else if guess > idx.Len-1 {\n\t\tguess = idx.Len - 1\n\t}\n\treturn guess, lower, upper\n}", "func findPivot(values []uint64, minIndex int) (pivot int, maxBefore uint64) {\n\t// First construct a table where minRight[i] is the minimum value in [i..n)\n\tn := len(values)\n\tminRight := make([]uint64, n)\n\tvar min uint64 = math.MaxUint64\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif values[i] < min {\n\t\t\tmin = values[i]\n\t\t}\n\t\tminRight[i] = min\n\t}\n\t// Now scan left-to-right tracking the running max and looking for a pivot:\n\tmaxBefore = 0\n\tfor pivot = 0; pivot < n-1; pivot++ {\n\t\tif values[pivot] > maxBefore {\n\t\t\tmaxBefore = values[pivot]\n\t\t}\n\t\tif pivot >= minIndex && maxBefore < minRight[pivot+1] {\n\t\t\tbreak\n\t\t}\n\t}\n\t//log.Printf(\"PIVOT: %v @%d -> %d\", values, minIndex, pivot)\n\treturn\n}", "func (ht *HashTable) nextBucket(bucket int) int {\n\tif bucket >= ht.numBuckets {\n\t\treturn 0\n\t}\n\tbucketAddr := bucket * BUCKET_SIZE\n\tnextUint, err := binary.Varint(ht.Buf[bucketAddr : bucketAddr+10])\n\tnext := int(nextUint)\n\tif next == 0 {\n\t\treturn 0\n\t} else if err < 0 || next <= bucket || next >= ht.numBuckets || next < INITIAL_BUCKETS {\n\t\tfmt.Errorf(\"Bad hash table - repair ASAP %s\", ht.Path)\n\t\treturn 0\n\t} else {\n\t\treturn next\n\t}\n}", "func UpdateHistogram(h *Histogram, feedback *QueryFeedback) *Histogram {\n\tbuckets, isNewBuckets, totalCount := splitBuckets(h, feedback)\n\tbuckets = mergeBuckets(buckets, isNewBuckets, float64(totalCount))\n\thist := buildNewHistogram(h, buckets)\n\t// Update the NDV of primary key column.\n\tif feedback.Tp == PkType {\n\t\thist.NDV = int64(hist.TotalRowCount())\n\t}\n\treturn hist\n}", "func (b Bucket) splitBucket(splitPoint, lowerBound int64) (Bucket, Bucket) {\n\tupperBound := (int64)(*b.UpperBound.(*tree.DInt))\n\n\t// The bucket size calculation has a -1 because NumRange does not\n\t// include values equal to UpperBound.\n\tbucketSize := upperBound - lowerBound - 1\n\tif bucketSize <= 0 {\n\t\tpanic(\"empty bucket should have been skipped\")\n\t}\n\n\tif splitPoint >= upperBound || splitPoint <= lowerBound {\n\t\tpanic(fmt.Sprintf(\"splitPoint (%d) must be between UpperBound (%d) and lowerBound (%d)\",\n\t\t\tsplitPoint, upperBound, lowerBound))\n\t}\n\n\t// Make the lower bucket.\n\tlowerMatchSize := splitPoint - lowerBound - 1\n\tlowerNumRange := (int64)(float64(b.NumRange) * float64(lowerMatchSize) / float64(bucketSize))\n\tlowerNumEq := (int64)(float64(b.NumRange) / float64(bucketSize))\n\tbucLower := Bucket{NumEq: lowerNumEq, NumRange: lowerNumRange, UpperBound: makeDatum(splitPoint)}\n\n\t// Make the upper bucket.\n\tupperMatchSize := upperBound - splitPoint - 1\n\tbucUpper := b\n\tbucUpper.NumRange = (int64)(float64(b.NumRange) * float64(upperMatchSize) / float64(bucketSize))\n\n\treturn bucLower, bucUpper\n}", "func UIntIdxDesc(list []uint, indices []int, element uint) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element < value {\n\t\t\tleft = middle + 1\n\t\t} else if element > value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func (ms HistogramBucketExemplar) Value() float64 {\n\treturn (*ms.orig).Value\n}", "func bucketOffset(compressed bool, offset int64) int64 {\n\tif compressed {\n\t\treturn 0\n\t}\n\treturn offset\n}", "func (it *emptyIterator) AtFloatHistogram() (int64, *histogram.FloatHistogram) { return 0, nil }", "func (c *Compressor) get(h uint32, si int) int {\n\th &= htSize - 1\n\ti := 0\n\tif c.inUse[h/32]&(1<<(h%32)) != 0 {\n\t\ti = int(c.table[h])\n\t}\n\ti += si &^ winMask\n\tif i >= si {\n\t\t// Try previous 64kiB block (negative when in first block).\n\t\ti -= winSize\n\t}\n\treturn i\n}", "func vmap(value float64, low1 float64, high1 float64, low2 float64, high2 float64) float64 {\n\treturn low2 + (high2-low2)*(value-low1)/(high1-low1)\n}", "func vmap(value float64, low1 float64, high1 float64, low2 float64, high2 float64) float64 {\n\treturn low2 + (high2-low2)*(value-low1)/(high1-low1)\n}", "func vmap(value float64, low1 float64, high1 float64, low2 float64, high2 float64) float64 {\n\treturn low2 + (high2-low2)*(value-low1)/(high1-low1)\n}", "func UInt64Idx(list []uint64, indices []int, element uint64) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element > value {\n\t\t\tleft = middle + 1\n\t\t} else if element < value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func UInt8Idx(list []uint8, indices []int, element uint8) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element > value {\n\t\t\tleft = middle + 1\n\t\t} else if element < value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func (mh *ModHasher) MapBucket(location uint64) int {\n\treturn int(location % mh.Buckets)\n}", "func UIntPtrIdxDesc(list []uintptr, indices []int, element uintptr) (int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element < value {\n\t\t\tleft = middle + 1\n\t\t} else if element > value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func (histogram Histogram) Map(min int, max int, width int, height int) {\n\n\t// TODO: Remove floating point operations!\n\n\tsum := 0\n\tscale := float32(max-min)/float32(width*height)\n\t\n\tbinCount := len(histogram)\n\n\tfor i := 0; i < binCount; i++ {\n\t\tsum += histogram[i]\n\t\thistogram[i] = (min + int(float32(sum)*scale))\n\t\tif histogram[i] > max {\n\t\t\thistogram[i] = max\n\t\t}\n\t}\n}", "func (s *summary) findInsertionIndex(x float64) int {\n\t// Binary search is only worthwhile if we have a lot of keys.\n\tif len(s.means) < 250 {\n\t\tfor i, mean := range s.means {\n\t\t\tif mean > x {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn len(s.means)\n\t}\n\n\treturn sort.Search(len(s.means), func(i int) bool {\n\t\treturn s.means[i] > x\n\t})\n}", "func (bng *binningP1D) coordToIndex(x float64) int {\n\tswitch {\n\tdefault:\n\t\ti := int((x - bng.xrange.Min) * bng.xstep)\n\t\treturn i\n\tcase x < bng.xrange.Min:\n\t\treturn UnderflowBin1D\n\tcase x >= bng.xrange.Max:\n\t\treturn OverflowBin1D\n\t}\n}", "func storeUIntIndex (txn *badger.Txn, key uint64, value []byte, prefix byte) error {\r\n\r\n\tindex := make([]byte, 8)\r\n\tbinary.LittleEndian.PutUint64(index, key)\r\n\tindex = append ([]byte{prefix}, index...)\r\n\r\n\treturn txn.Set(index, value)\r\n}", "func (n *Node) indexForBitPos(bp int) int {\n\t// TODO: an optimization could reuse the same 'mask' here and change the size\n\t// as needed. This isnt yet done as the bitset package doesnt make it easy\n\t// to do.\n\n\t// make a bitmask (all bits set) 'bp' bits long\n\tmask := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(bp)), nil), big.NewInt(1))\n\tmask.And(mask, n.Bitfield)\n\n\treturn popCount(mask)\n}", "func (t table) findIx(w int) int {\n\tfor i := range t.ws {\n\t\tw -= t.ws[i]\n\t\tif w < 0 {\n\t\t\treturn i\n\t\t}\n\t}\n\tpanic(\"weight out of table bounds\")\n}", "func (shard *hashShard) searchExists(key KeyType, hashValue IndexType) IndexType {\n\tvar x IndexType = 0\n\tvar idx = (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\tfor (*shard.data)[idx].isTomb {\n\t\tif (*shard.data)[idx].isOccupied && (*shard.data)[idx].key == key {\n\t\t\treturn idx\n\t\t}\n\t\tx++\n\t\tidx = (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\t}\n\n\treturn idx\n}", "func CalculateValuesForCurrentIndexes(repository repositories.StockRepository) map[string]float64 {\n\tresult := map[string]float64{}\n\n\tindexes := repository.GetIndexesArray()\n\tprintln(\"Obtaining company data for each index...\")\n\n\t// TODO implement concurrency here\n\tfor _, index := range indexes {\n\t\tcompany := repository.GetCompanyForIndex(index)\n\t\tif !isCompanyEmpty(company) {\n\t\t\tvalue := calculateValue(company)\n\t\t\tresult[index] = value\n\t\t\tfmt.Printf(\"Done for index: %v \\n\", index)\n\t\t}\n\t}\n\n\treturn result\n}", "func (s *histValues[N]) Aggregate(value N, attr attribute.Set) {\n\t// Accept all types to satisfy the Aggregator interface. However, since\n\t// the Aggregation produced by this Aggregator is only float64, convert\n\t// here to only use this type.\n\tv := float64(value)\n\n\t// This search will return an index in the range [0, len(s.bounds)], where\n\t// it will return len(s.bounds) if value is greater than the last element\n\t// of s.bounds. This aligns with the buckets in that the length of buckets\n\t// is len(s.bounds)+1, with the last bucket representing:\n\t// (s.bounds[len(s.bounds)-1], +∞).\n\tidx := sort.SearchFloat64s(s.bounds, v)\n\n\ts.valuesMu.Lock()\n\tdefer s.valuesMu.Unlock()\n\n\tb, ok := s.values[attr]\n\tif !ok {\n\t\t// N+1 buckets. For example:\n\t\t//\n\t\t// bounds = [0, 5, 10]\n\t\t//\n\t\t// Then,\n\t\t//\n\t\t// buckets = (-∞, 0], (0, 5.0], (5.0, 10.0], (10.0, +∞)\n\t\tb = newBuckets(len(s.bounds) + 1)\n\t\t// Ensure min and max are recorded values (not zero), for new buckets.\n\t\tb.min, b.max = v, v\n\t\ts.values[attr] = b\n\t}\n\tb.bin(idx, v)\n}", "func (ba *FilterBitArray) ValueAt(i uint) byte {\n\tif i < ba.Capacity() {\n\t\treturn (*ba)[i/byteSize] & (1 << (i % byteSize))\n\t}\n\treturn 0\n}", "func GetBucketIndexFromKey(key []byte, numberOfBins int) int {\n\tcrc := crc32.ChecksumIEEE(key)\n\treturn int(math.Mod(float64(crc), float64(numberOfBins)))\n}", "func (g Grid) GetValueAt(p *Point) float32 {\n\n\tif(p.X<g.Header.Lo1 || p.X>g.Header.Lo2){\n\t\treturn float32(-9999);\n\t}\n\n\tif(p.Y>g.Header.La1 || p.Y<g.Header.La2){\n\t\treturn float32(-9999);\n\t}\n\n\tidxX := int(((p.X - g.Header.Lo1) / g.Width()) * float64(g.Header.Nx-1))\n\tidxY := int(((g.Header.La1 - p.Y) / g.Height()) * float64(g.Header.Ny-1))\n\n\tul := g.GetValueAtIdx(idxX, idxY)\n\tur := g.GetValueAtIdx(idxX+1, idxY)\n\tll := g.GetValueAtIdx(idxX, idxY+1)\n\tlr := g.GetValueAtIdx(idxX+1, idxY+1)\n\n\tv:=BilinearInterpolation(&ll,&ul,&lr,&ur,p)\n\n\treturn float32(v)\n}", "func (vectorizer *Vectorizer) indexMap(src Map) {\n\tfor _, key := range src.orderedKeys() {\n\t\telem := src[key]\n\t\tif vectorizer.indexes[key] == nil {\n\t\t\tvectorizer.indexes[key] = index{}\n\t\t}\n\t\tif vectorizer.indexes[key][elem] == 0 {\n\t\t\tvectorizer.indexes[key][elem] = vectorizer.nextID(key)\n\t\t}\n\t}\n}", "func (this *MyHashMap) Get(key int) int {\n\thashCode := key % 1111\n\tbucket := this.buckets[hashCode]\n\tfor bucket != nil {\n\t\tif bucket.K == key {\n\t\t\treturn bucket.V\n\t\t}\n\t\tbucket = bucket.Next\n\t}\n\treturn -1\n}", "func ScissorIndexed(index uint32, left int32, bottom int32, width int32, height int32) {\n C.glowScissorIndexed(gpScissorIndexed, (C.GLuint)(index), (C.GLint)(left), (C.GLint)(bottom), (C.GLsizei)(width), (C.GLsizei)(height))\n}", "func (p BigIntSlice) Search(x *big.Int) int { return SearchBigInts(p, x) }", "func UIntPtrIdxRngDesc(list []uintptr, indices []int, element uintptr) (int, int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element < value {\n\t\t\tleft = middle + 1\n\t\t} else if element > value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\tfrom := uintptrIdxRngL(list, indices, element, left, middle-1)\n\t\t\tto := uintptrIdxRngR(list, indices, element, middle+1, right)\n\t\t\treturn from, to, true\n\t\t}\n\t}\n\treturn left, left + 1, false\n}", "func (it *pushdownSeriesIterator) AtHistogram() (int64, *histogram.Histogram) {\n\tpanic(\"not implemented\")\n}", "func (l *GroupLookup) lookupGroup(key flux.GroupKey) int {\n\tif l.lastIndex >= 0 {\n\t\tkg := l.groups[l.lastIndex]\n\t\tif !key.Less(kg.First()) {\n\t\t\t// If the next group doesn't exist or has a first value that is\n\t\t\t// greater than this key, then we can return the last index and\n\t\t\t// avoid performing a binary search.\n\t\t\tif l.lastIndex == len(l.groups)-1 || key.Less(l.groups[l.lastIndex+1].First()) {\n\t\t\t\treturn l.lastIndex\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find the last group where the first key is less than or equal\n\t// than the key we are looking for. This means we need to search for\n\t// the first group where the first key is greater than the key we are setting\n\t// and use the group before that one.\n\tindex := sort.Search(len(l.groups), func(i int) bool {\n\t\treturn key.Less(l.groups[i].First())\n\t}) - 1\n\tif index >= 0 {\n\t\tl.lastIndex = index\n\t}\n\treturn index\n}", "func (t *WindowedThroughput) updateMaps() {\n\tcurrentIndex := t.indexGenerator.GetCurrentIndex()\n\tlookbackIndexes := t.indexGenerator.DurationToIndexes(t.LookbackFrequencyDuration)\n\taggregateCounts := t.countList.AggregateCounts(currentIndex, lookbackIndexes)\n\n\t// Apply the same aggregation algorithm as total throughput\n\t// Short circuit if no traffic\n\tt.numKeys = len(aggregateCounts)\n\tif t.numKeys == 0 {\n\t\t// no traffic during the last period.\n\t\tt.lock.Lock()\n\t\tdefer t.lock.Unlock()\n\t\tt.savedSampleRates = make(map[string]int)\n\t\treturn\n\t}\n\t// figure out our target throughput per key over the lookback window.\n\ttotalGoalThroughput := t.GoalThroughputPerSec * t.LookbackFrequencyDuration.Seconds()\n\t// floor the throughput but min should be 1 event per bucket per time period\n\tthroughputPerKey := math.Max(1, float64(totalGoalThroughput)/float64(t.numKeys))\n\t// for each key, calculate sample rate by dividing counted events by the\n\t// desired number of events\n\tnewSavedSampleRates := make(map[string]int)\n\tfor k, v := range aggregateCounts {\n\t\trate := int(math.Max(1, (float64(v) / float64(throughputPerKey))))\n\t\tnewSavedSampleRates[k] = rate\n\t}\n\t// save newly calculated sample rates\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tt.savedSampleRates = newSavedSampleRates\n}", "func (v IntVec) BiSearch(value int, cmp func(a, b int) uint8) (int, bool) {\n\tstart, end := 0, len(v)\n\tif start == end {\n\t\treturn 0, false\n\t}\n\tfor {\n\t\tmid := start + (end-start)/2\n\t\tswitch cmp(v[mid], value) {\n\t\tcase 0:\n\t\t\treturn mid, true\n\t\tcase 1:\n\t\t\tend = mid + 0\n\t\tcase 2:\n\t\t\tstart = mid + 1\n\t\t}\n\n\t\tif start == end {\n\t\t\treturn start, start < len(v) && cmp(v[start], value) == 0\n\t\t}\n\t}\n}", "func valueLimiter(index indexedCluster, cluster []cell) (changes []cell) {\n\tupperBound := len(index)\n\tfor i := 2; i <= upperBound; i++ {\n\t\tchanges = append(changes, valueLimiterChild(i, []int{}, index, cluster)...)\n\t}\n\treturn changes\n}", "func (bg *bufferedGroup) updateLocationIndex() {\n bg.locationIndex = make(map[string]int)\n for i, bi := range bg.images {\n if _, found := bg.locationIndex[bi.nearestCityKey]; found == false {\n locationTimekey := bi.LocationTimekey()\n bg.locationIndex[locationTimekey] = i\n }\n }\n}", "func UIntIdxRngDesc(list []uint, indices []int, element uint) (int, int, bool) {\n\tleft := 0\n\tright := len(indices) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalueIndex := indices[middle]\n\t\tvalue := list[valueIndex]\n\t\tif element < value {\n\t\t\tleft = middle + 1\n\t\t} else if element > value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\tfrom := uintIdxRngL(list, indices, element, left, middle-1)\n\t\t\tto := uintIdxRngR(list, indices, element, middle+1, right)\n\t\t\treturn from, to, true\n\t\t}\n\t}\n\treturn left, left + 1, false\n}", "func (v Int32Vec) BiSearch(value int32, cmp func(a, b int32) uint8) (int, bool) {\n\tstart, end := 0, len(v)\n\tif start == end {\n\t\treturn 0, false\n\t}\n\tfor {\n\t\tmid := start + (end-start)/2\n\t\tswitch cmp(v[mid], value) {\n\t\tcase 0:\n\t\t\treturn mid, true\n\t\tcase 1:\n\t\t\tend = mid + 0\n\t\tcase 2:\n\t\t\tstart = mid + 1\n\t\t}\n\n\t\tif start == end {\n\t\t\treturn start, start < len(v) && cmp(v[start], value) == 0\n\t\t}\n\t}\n}", "func (obj *SparseRealVector) ValueAt(i int) float64 {\n if i < 0 || i >= obj.Dim() {\n panic(\"index out of bounds\")\n }\n if v, ok := obj.values[i]; ok {\n return v.GetValue()\n } else {\n return 0.0\n }\n}", "func (filter *BloomFilter) getIndexes(key interface{}) []uint {\n\tindexes := make([]uint, filter.hashCount)\n\tkeyBytes, _ := getBytes(key)\n\tmax := uint(filter.capacity)\n\th1, h2 := murmur3Hash(keyBytes)\n\n\tfor hashIndex := 0; hashIndex < filter.hashCount; hashIndex++ {\n\t\ti := uint(hashIndex)\n\t\tindexes[i] = (uint(h1) + i*uint(h2) + i*i) % max\n\t}\n\n\treturn indexes\n}", "func index(element *fields.QualifiedHash, group []*fields.QualifiedHash) int {\n\tfor i, current := range group {\n\t\tif element.Equals(current) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func getIndexAndFingerprint(data []byte, bucketIndexMask uint) (uint, fingerprint) {\n\thash := metro.Hash64(data, 1337)\n\tf := getFingerprint(hash)\n\t// Use least significant bits for deriving index.\n\ti1 := uint(hash) & bucketIndexMask\n\treturn i1, f\n}", "func (r *Range) InternalRangeLookup(args *InternalRangeLookupRequest, reply *InternalRangeLookupResponse) {\n\tif !bytes.HasPrefix(args.Key, KeyMetaPrefix) {\n\t\treply.Error = util.Errorf(\"invalid metadata key: %q\", args.Key)\n\t\treturn\n\t}\n\n\t// Validate that key is not outside the range. Since the keys encoded in metadata keys are\n\t// the end keys of the range the metadata represent, the check args.Key >= r.Meta.StartKey\n\t// may result in false negatives.\n\tif bytes.Compare(args.Key, r.Meta.EndKey) >= 0 {\n\t\treply.Error = util.Errorf(\"key outside the range %v with end key %q\", r.Meta.RangeID, r.Meta.EndKey)\n\t\treturn\n\t}\n\n\t// We want to search for the metadata key just greater than args.Key.\n\tnextKey := MakeKey(args.Key, Key{0})\n\tkvs, err := r.engine.scan(nextKey, KeyMax, 1)\n\tif err != nil {\n\t\treply.Error = err\n\t\treturn\n\t}\n\t// We should have gotten the key with the same metadata level prefix as we queried.\n\tmetaPrefix := args.Key[0:len(KeyMeta1Prefix)]\n\tif len(kvs) != 1 || !bytes.HasPrefix(kvs[0].Key, metaPrefix) {\n\t\treply.Error = util.Errorf(\"key not found in range %v\", r.Meta.RangeID)\n\t\treturn\n\t}\n\n\tif err = gob.NewDecoder(bytes.NewBuffer(kvs[0].Value.Bytes)).Decode(&reply.Range); err != nil {\n\t\treply.Error = err\n\t\treturn\n\t}\n\tif bytes.Compare(args.Key, reply.Range.StartKey) < 0 {\n\t\t// args.Key doesn't belong to this range. We are perhaps searching the wrong node?\n\t\treply.Error = util.Errorf(\"no range found for key %q in range: %+v\", args.Key, r.Meta)\n\t\treturn\n\t}\n\treply.EndKey = kvs[0].Key\n}", "func (self *Weights) addIndexWeight(i int, w weight) {\n\tif self.Scale == nil {\n\t\tself.Scale = make([]ScaleEntry,0,500)\n\t}\n\tl := len(self.Scale)\n\tif l == 0 {\n\t\tself.Scale = append(self.Scale,ScaleEntry{I:i,W:w})\n\t} else {\n\t\tself.Scale= append(self.Scale,ScaleEntry{I:i,W:(self.Scale[l-1].W+w)})\n\t}\n}" ]
[ "0.5866949", "0.5790993", "0.56843865", "0.5672725", "0.5624339", "0.55591005", "0.5526882", "0.5522118", "0.54889005", "0.5477909", "0.5371118", "0.53150356", "0.52869827", "0.52800244", "0.5228432", "0.5199461", "0.5171201", "0.5151533", "0.51369053", "0.511599", "0.5109656", "0.50984704", "0.50405914", "0.50394696", "0.50366545", "0.5035336", "0.502818", "0.49983633", "0.49956182", "0.4992215", "0.49818382", "0.4980161", "0.49543282", "0.49453673", "0.49431065", "0.4939573", "0.49284402", "0.49122262", "0.4911963", "0.49087992", "0.49026376", "0.4884084", "0.48766613", "0.48734516", "0.48730552", "0.4871231", "0.48478553", "0.484679", "0.48394045", "0.4838959", "0.48383796", "0.4830833", "0.4818815", "0.4801302", "0.4793825", "0.4790623", "0.4788447", "0.4786441", "0.47854778", "0.4779786", "0.47797492", "0.47793514", "0.4776397", "0.4776397", "0.4776397", "0.47731245", "0.47550708", "0.47519642", "0.4750001", "0.47357196", "0.4727303", "0.47155347", "0.47126302", "0.4709919", "0.47096714", "0.47065407", "0.470611", "0.46939865", "0.46907315", "0.4690543", "0.467399", "0.46698135", "0.46695715", "0.4667062", "0.46648905", "0.46621004", "0.46523544", "0.4650758", "0.4648818", "0.46485466", "0.46456656", "0.46431738", "0.4639055", "0.46363217", "0.46224433", "0.461783", "0.46171203", "0.46132454", "0.46122104", "0.4612004" ]
0.8456239
0
Record records a data point.
func (h *Histogram) Record(v float64) { h.RecordN(v, 1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *notifier) RecordAdd(x, y int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tNew: &Point{x, y, value},\n\t\t}})\n}", "func (s *StoragePointsWriterRecorder) Record(ctx context.Context, run *taskmodel.Run) error {\n\ttags := models.NewTags(map[string]string{\n\t\tstatusTag: run.Status,\n\t\ttaskIDTag: run.TaskID.String(),\n\t})\n\n\t// log an error if we have incomplete data on finish\n\tif !run.ID.Valid() ||\n\t\trun.ScheduledFor.IsZero() ||\n\t\trun.StartedAt.IsZero() ||\n\t\trun.FinishedAt.IsZero() ||\n\t\trun.Status == \"\" {\n\t\ts.log.Error(\"Run missing critical fields\", zap.String(\"run\", fmt.Sprintf(\"%+v\", run)), zap.String(\"runID\", run.ID.String()))\n\t}\n\n\tfields := map[string]interface{}{}\n\tfields[runIDField] = run.ID.String()\n\tfields[startedAtField] = run.StartedAt.Format(time.RFC3339Nano)\n\tfields[finishedAtField] = run.FinishedAt.Format(time.RFC3339Nano)\n\tfields[scheduledForField] = run.ScheduledFor.Format(time.RFC3339)\n\tfields[requestedAtField] = run.RequestedAt.Format(time.RFC3339)\n\n\tstartedAt := run.StartedAt\n\tif startedAt.IsZero() {\n\t\tstartedAt = time.Now().UTC()\n\t}\n\n\tlogBytes, err := json.Marshal(run.Log)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields[logField] = string(logBytes)\n\n\tpoint, err := models.NewPoint(s.destination.Measurement, tags, fields, startedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.cli.WriteV2(influxdb.FluxWrite{\n\t\tBucket: s.destination.Bucket,\n\t\tOrg: s.destination.Org,\n\t\tOrgID: s.destination.OrgID,\n\t\tPoints: models.Points{point},\n\t})\n}", "func (ts *TimeSeries) AddPoint(value float64) Record {\n\trecord := newRecord(value)\n\tts.AddRecord(record)\n\treturn *record\n}", "func (a *Activity) Record(samples []*Sample, altitudeReference string) error {\n\tdata := struct {\n\t\tSamples []*Sample `json:\"samples\"`\n\t\tActivityId int `json:\"activityId\"`\n\t\tAltitudeReference string `json:\"altitudeReference\"`\n\t}{\n\t\tSamples: samples,\n\t\tActivityId: a.Id,\n\t\tAltitudeReference: altitudeReference,\n\t}\n\treq, err := a.c.newRequestJSON(\"POST\", a.c.apiURL+\"/activity/record\", &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := a.c.doRequest(req, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (tracer *TraceLogger) Record(context string, data []byte) {\n\tgo func() {\n\t\ttracer.traceMutex.Lock()\n\t\tdefer tracer.traceMutex.Unlock()\n\t\tif tracer.fileHandle == nil || tracer.isReplaying {\n\t\t\treturn\n\t\t}\n\t\tts := stratuxClock.Time.Format(time.RFC3339Nano)\n\t\ttracer.csvWriter.Write([]string {ts, context, string(data)})\n\t}()\n}", "func (c *Counter) Record(v float64) {\n\tc.RecordN(v, 1)\n}", "func (s *Collector) Record(name string, stats []*Stat) error {\n\treturn NOT_IMPLEMENTED\n}", "func (r *rawHist) record(t int64, v float64) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tr.buf = append(r.buf, &pb.Sample{\n\t\tDatetime: t,\n\t\tValue: v,\n\t})\n\tif int32(len(r.buf)) >= GetRawHistBufLimit() {\n\t\tbuf := r.buf\n\t\tr.buf = make([]*pb.Sample, 0, GetRawHistBufLimit()/2)\n\t\tgo r.assembleAndSend(buf)\n\t}\n}", "func (info HistogramFloat64) Record(e *Config, key *keys.Float64) {\n\tdata := &HistogramFloat64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (g *StableGauge) Record(value int64) {\n\tg.gauge.Record(value)\n}", "func (t *TimeSeries) Add(timestamp time.Time, datum float64) {\n\tt.records = append(t.records, &Record{\n\t\ttimestamp: timestamp,\n\t\tDatum: datum,\n\t})\n}", "func (h *PCPHistogram) Record(val int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValue(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func (b *ServerBackend) AddDPointRecord(server string, user string, record *DPointRecord) bool {\n\t// Validate user and server\n\tuserdata := b.GetUserData(server, user)\n\tif userdata == nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not get userdata\")\n\t\treturn false\n\t}\n\n\tpoints, err := strconv.ParseInt(record.Points, 10, 32)\n\tif err != nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not parse int\")\n\t\treturn false\n\t}\n\n\tdata := fromilyclient.DPointRecord{\n\t\tPoints: int32(points),\n\t\tReason: record.Reason,\n\t}\n\n\tif b.Client.CreateDPointRecord(server, user, &data) != nil {\n\t\tfmt.Println(\"ADD_DPOINT: Could not create record\")\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (mb *MetricsBuilder) RecordBigipNodeDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipNodeDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (summary *Summary) Record(name string, data interface{}) {\n\titem, ok := summary.Data[name]\n\tif !ok {\n\t\titem = new(Metrics)\n\t\titem.Keys = make(map[string]Metric)\n\t\tsummary.Data[name] = item\n\t}\n\n\titem.Hits++\n\trecordMembers(reflect.ValueOf(data).Elem(), item.Keys, \"\")\n}", "func (c *StepLookbackAccumulator) AddPoint(dp ts.Datapoint) {\n\tif dp.TimestampNanos.Before(c.earliestLookback) {\n\t\t// this datapoint is too far in the past, it can be dropped.\n\t\treturn\n\t}\n\n\tc.datapoints = append(c.datapoints, xts.Datapoint{\n\t\tTimestamp: dp.TimestampNanos,\n\t\tValue: dp.Value,\n\t})\n}", "func (g *Gauge) Record(value int64) {\n\tatomic.StoreInt64(&g.value, value)\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (x *Writer) emitDataRecord(p []byte) error {\n\t// collect all the stuff that goes into this type of record\n\tvar data = []interface{}{\n\t\tbyte(len(p)), // byte count\n\t\tx.addr, // standard 16-bit base address\n\t\tbyte(Data), // record type\n\t\tp, // slice of data\n\t}\n\n\terr := x.emitRecord(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"emitDataRecord: %v\", err)\n\t}\n\n\tx.addr += uint16(len(p))\n\n\treturn nil\n}", "func (self *Client) data(dataPoints models.DataPoints) {\n\tlog.WithFields(log.Fields{\n\t\t\"points\": dataPoints,\n\t}).Debug(\"New datapoints\")\n\t// TODO: Send dataPoints to remote\n}", "func (mb *MetricsBuilder) RecordBigipPoolDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (d *Distribution) AddPoint(timestamp time.Time, value float64) {\n\td.Values = append(d.Values, MetricValue{Timestamp: timestamp, Value: value})\n}", "func (mb *MetricsBuilder) RecordMysqlLogOperationsDataPoint(ts pcommon.Timestamp, inputVal string, logOperationsAttributeValue AttributeLogOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlLogOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlLogOperations.recordDataPoint(mb.startTime, ts, val, logOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordBigipVirtualServerDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipVirtualServerDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (n *notifier) RecordMove(x1, y1, x2, y2 int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tOld: &Point{x1, y1, value},\n\t\t\tNew: &Point{x2, y2, value},\n\t\t}})\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapSearchRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsLdapSearchRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsOperationRateDataPoint(ts pcommon.Timestamp, val float64, operationTypeAttributeValue AttributeOperationType) {\n\tmb.metricActiveDirectoryDsOperationRate.recordDataPoint(mb.startTime, ts, val, operationTypeAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationObjectRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection) {\n\tmb.metricActiveDirectoryDsReplicationObjectRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (info HistogramInt64) Record(e *Config, key *keys.Int64) {\n\tdata := &HistogramInt64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (mb *MetricsBuilder) RecordMysqlOperationsDataPoint(ts pcommon.Timestamp, inputVal string, operationsAttributeValue AttributeOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlOperations.recordDataPoint(mb.startTime, ts, val, operationsAttributeValue.String())\n\treturn nil\n}", "func (metric *Float64Metric) Record(tags map[string]string, measurement float64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (nv *NetView) Record(counters string, rastCtr int) {\n\tnv.DataMu.Lock()\n\tdefer nv.DataMu.Unlock()\n\tif counters != \"\" {\n\t\tnv.LastCtrs = counters\n\t}\n\tnv.Data.PrjnType = nv.Params.PrjnType\n\tnv.Data.Record(nv.LastCtrs, rastCtr, nv.Params.Raster.Max)\n\tnv.RecTrackLatest() // if we make a new record, then user expectation is to track latest..\n}", "func (mb *MetricsBuilder) RecordBigipPoolMemberDataTransmittedDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolMemberDataTransmitted.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (e *LogLoss) Record(probability float64, weight float64) {\n\te.mu.Lock()\n\te.weight += weight\n\te.sum += weight * math.Log(probability+e.Epsilon)\n\te.mu.Unlock()\n}", "func (mb *MetricsBuilder) RecordMysqlDoubleWritesDataPoint(ts pcommon.Timestamp, inputVal string, doubleWritesAttributeValue AttributeDoubleWrites) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlDoubleWrites, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlDoubleWrites.recordDataPoint(mb.startTime, ts, val, doubleWritesAttributeValue.String())\n\treturn nil\n}", "func (mc *metricsConfig) record(ctx context.Context, mss []stats.Measurement, ros ...stats.Options) error {\n\tif mc == nil || mc.backendDestination == none {\n\t\t// Don't record data points if the metric config is not initialized yet or if\n\t\t// the defined backend is \"none\" explicitly.\n\t\treturn nil\n\t}\n\n\topt, err := optionForResource(metricskey.GetResource(ctx))\n\tif err != nil {\n\t\treturn err\n\t}\n\tros = append(ros, opt)\n\n\treturn stats.RecordWithOptions(ctx, append(ros, stats.WithMeasurements(mss...))...)\n}", "func (t *PersonalRecordChaincode) addRecord(APIstub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 4 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 4\")\n\t}\n\n\tvar record = Record{Date: args[1], Position: args[2], Name: args[3]}\n\n\trecordAsBytes, _ := json.Marshal(record)\n\tAPIstub.PutState(args[0], recordAsBytes)\n\n\treturn shim.Success(nil)\n\n}", "func Record(ctx context.Context, ms ...Measurement) {\n\treq := &recordReq{\n\t\tnow: time.Now(),\n\t\ttm: tag.FromContext(ctx),\n\t\tms: ms,\n\t}\n\tdefaultWorker.c <- req\n}", "func (ts *Timeseries) AddNewPoint(v float64, x interface{}) error {\n\tts.Lock()\n\tdefer ts.Unlock() // unlocks at the end\n\n\tswitch T := x.(type) {\n\tcase int64:\n\t\tts.XY[T] = v\n\tcase time.Time:\n\t\tts.XY[T.UnixNano()] = v\n\tcase int:\n\t\tts.XY[int64(T)] = v\n\tdefault:\n\t\treturn fmt.Errorf(\"Adding point not possible\")\n\t}\n\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlHandlersDataPoint(ts pcommon.Timestamp, inputVal string, handlerAttributeValue AttributeHandler) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlHandlers, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlHandlers.recordDataPoint(mb.startTime, ts, val, handlerAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapBindLastSuccessfulTimeDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsLdapBindLastSuccessfulTime.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordAerospikeNamespaceGeojsonRegionQueryPointsDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for AerospikeNamespaceGeojsonRegionQueryPoints, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricAerospikeNamespaceGeojsonRegionQueryPoints.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (tw *TimingsWrapper) Record(name string, startTime time.Time) {\n\tif tw.name == \"\" {\n\t\ttw.timings.Record([]string{name}, startTime)\n\t\treturn\n\t}\n\ttw.timings.Record([]string{tw.name, name}, startTime)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsLdapBindRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsLdapBindRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordFlinkJobLastCheckpointTimeDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJobLastCheckpointTime, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJobLastCheckpointTime.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func Record(cl *Client, span *ssf.SSFSpan, done chan<- error) error {\n\tif cl == nil {\n\t\treturn ErrNoClient\n\t}\n\n\top := func(ctx context.Context, s backend) {\n\t\terr := s.sendSync(ctx, span)\n\t\tif done != nil {\n\t\t\tdone <- err\n\t\t}\n\t}\n\tselect {\n\tcase cl.ops <- op:\n\t\treturn nil\n\tdefault:\n\t}\n\treturn ErrWouldBlock\n}", "func (repository *RecordCommandRepositoryCircuitBreaker) InsertRecord(data repositoryTypes.CreateRecord) (entity.Record, error) {\n\toutput := make(chan entity.Record, 1)\n\thystrix.ConfigureCommand(\"insert_record\", config.Settings())\n\terrors := hystrix.Go(\"insert_record\", func() error {\n\t\trecord, err := repository.RecordCommandRepositoryInterface.InsertRecord(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutput <- record\n\t\treturn nil\n\t}, nil)\n\n\tselect {\n\tcase out := <-output:\n\t\treturn out, nil\n\tcase err := <-errors:\n\t\treturn entity.Record{}, err\n\t}\n}", "func (s *session) AddRecord(key string, member interface{}, unixstamp int64) error {\n\taction, err := s.addRecord(key, member, unixstamp)\n\tif err != nil {\n\t\treturn s.catch(\"AddRecord: \"+action, err)\n\t}\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlRowOperationsDataPoint(ts pcommon.Timestamp, inputVal string, rowOperationsAttributeValue AttributeRowOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlRowOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlRowOperations.recordDataPoint(mb.startTime, ts, val, rowOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlPageOperationsDataPoint(ts pcommon.Timestamp, inputVal string, pageOperationsAttributeValue AttributePageOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlPageOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlPageOperations.recordDataPoint(mb.startTime, ts, val, pageOperationsAttributeValue.String())\n\treturn nil\n}", "func (s *ReprTimeSeries) AddPoint(t int64, min float64, max float64, last float64, sum float64, count int64) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.Stats = append(s.Stats, &repr.StatRepr{\n\t\tTime: t,\n\t\tMin: repr.CheckFloat(min),\n\t\tMax: repr.CheckFloat(max),\n\t\tLast: repr.CheckFloat(last),\n\t\tSum: repr.CheckFloat(sum),\n\t\tCount: count,\n\t})\n\tif t > s.curTime {\n\t\ts.curTime = t\n\t}\n\tif t < s.T0 {\n\t\ts.T0 = t\n\t}\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolDataPagesDataPoint(ts pcommon.Timestamp, val int64, bufferPoolDataAttributeValue AttributeBufferPoolData) {\n\tmb.metricMysqlBufferPoolDataPages.recordDataPoint(mb.startTime, ts, val, bufferPoolDataAttributeValue.String())\n}", "func (r *Recorder) Write(record *Record) {\n\tif r == nil || record == nil {\n\t\treturn\n\t}\n\trecord.Write(r.data)\n}", "func (c Client) WritePoint(db, measurement string, data interface{}) error {\n\tt, tags, fields, err := encode(data)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.WritePointTagsFields(db, measurement, tags, fields, t)\n}", "func (mb *MetricsBuilder) RecordAerospikeNodeQueryTrackedDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for AerospikeNodeQueryTracked, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricAerospikeNodeQueryTracked.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (p *Profiler) Record(name string) func() {\n\tif p == nil {\n\t\t// If the profiler instance doesn't exist, then don't attempt to operate on it.\n\t\treturn func() {}\n\t}\n\tstart := p.now()\n\treturn func() {\n\t\tp.AddProfile(Profile{\n\t\t\tName: name,\n\t\t\tStart: start,\n\t\t\tFinish: p.now(),\n\t\t})\n\t}\n}", "func (p *Provider) record(tx *lease.Tx) {\n\tvar ops uint64 // Total number of consumptive ops (really op effects)\n\n\tfor _, op := range tx.Ops() {\n\t\tif op.Type == lease.Update && op.UpdateType() == lease.Renew {\n\t\t\t// Don't record renewals\n\t\t\tcontinue\n\t\t}\n\t\tfor _, effect := range op.Effects() {\n\t\t\tif !effect.Consumptive() {\n\t\t\t\t// Only record effects that affect consumption\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.log.Printf(\"TX %s\", effect.String())\n\t\t\tops++\n\t\t}\n\t}\n\n\tp.add(ops)\n}", "func (f *flusher) Record(mtype int, name string, value interface{}, flush bool) {\n\tf.mu.Lock()\n\tf.sink.Record(mtype, name, value)\n\tif flush {\n\t\tf.sink.Flush()\n\t}\n\tf.mu.Unlock()\n}", "func (log *Logger) record(format string, args ...interface{}) []byte {\n\treturn []byte(\n\t\ttime.Now().Format(\"2006/01/02 15:04:05\") +\n\t\t\t\": \" +\n\t\t\tfmt.Sprintf(format, args...) +\n\t\t\t\"\\n\",\n\t)\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationPropertyRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection) {\n\tmb.metricActiveDirectoryDsReplicationPropertyRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsNotificationQueuedDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsNotificationQueued.recordDataPoint(mb.startTime, ts, val)\n}", "func (r *Recorder) Record(ctx context.Context, outDir string) error {\n\tvs, err := r.timeline.StopRecording(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to stop timeline\")\n\t}\n\n\tpv := perf.NewValues()\n\ttimeElapsed := time.Since(r.startTime)\n\tpv.Set(perf.Metric{\n\t\tName: \"Recorder.ElapsedTime\",\n\t\tUnit: \"s\",\n\t\tDirection: perf.SmallerIsBetter,\n\t}, float64(timeElapsed.Seconds()))\n\tpv.Merge(vs)\n\n\treturn pv.Save(outDir)\n}", "func (gWal *GenericWAL) writeCheckpointRecord(data []byte) (int64, error) {\n doneCh := make(chan *Response)\n\n if gWal.lostOwnership {\n return -1, ErrLostOwnership\n }\n\n lsn, errAdd := gWal.wal.AddCheckpointEntry(data, false, /* skipChecksum */\n doneCh)\n\n if errAdd != nil {\n glog.Errorf(\"could not add wal entry :: %v\", errAdd)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n response := <-doneCh\n if response == nil {\n glog.Errorf(\"could not persist checkpoint record to wal\")\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n if response.Result != nil {\n glog.Errorf(\"could not persist checkpoint record to wal :: %v\",\n response.Result)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n return int64(lsn), nil\n}", "func (l *Logger) Record(remoteAddr net.IP, hijacked bool, qtype uint16, question string, answers ...string) {\n\tif l.mode == LogDiscard {\n\t\treturn\n\t}\n\tif l.mode == LogHijacked && !hijacked {\n\t\treturn\n\t}\n\tl.wg.Add(1)\n\tl.queue <- LogEntry{\n\t\tTime: l.now(),\n\t\tRemoteAddr: remoteAddr,\n\t\tHijacked: hijacked,\n\t\tQtype: qtype,\n\t\tQuestion: question,\n\t\tAnswers: answers,\n\t}\n}", "func (sr *StoredRecording) Data(key *ari.Key) (*ari.StoredRecordingData, error) {\n\tif key == nil || key.ID == \"\" {\n\t\treturn nil, errors.New(\"storedRecording key not supplied\")\n\t}\n\n\tdata := new(ari.StoredRecordingData)\n\tif err := sr.client.get(\"/recordings/stored/\"+key.ID, data); err != nil {\n\t\treturn nil, dataGetError(err, \"storedRecording\", \"%v\", key.ID)\n\t}\n\n\tdata.Key = sr.client.stamp(key)\n\n\treturn data, nil\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolPagesDataPoint(ts pcommon.Timestamp, inputVal string, bufferPoolPagesAttributeValue AttributeBufferPoolPages) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlBufferPoolPages, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlBufferPoolPages.recordDataPoint(mb.startTime, ts, val, bufferPoolPagesAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordMysqlCommandsDataPoint(ts pcommon.Timestamp, inputVal string, commandAttributeValue AttributeCommand) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlCommands, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlCommands.recordDataPoint(mb.startTime, ts, val, commandAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsBindRateDataPoint(ts pcommon.Timestamp, val float64, bindTypeAttributeValue AttributeBindType) {\n\tmb.metricActiveDirectoryDsBindRate.recordDataPoint(mb.startTime, ts, val, bindTypeAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordFlinkOperatorRecordCountDataPoint(ts pcommon.Timestamp, inputVal string, operatorNameAttributeValue string, recordAttributeValue AttributeRecord) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkOperatorRecordCount, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkOperatorRecordCount.recordDataPoint(mb.startTime, ts, val, operatorNameAttributeValue, recordAttributeValue.String())\n\treturn nil\n}", "func (n *notifier) RecordReplace(x, y int, orig, repl interface{}) {\n\tn.add([]Update{Update{\n\t\tOld: &Point{x, y, orig},\n\t\tNew: &Point{x, y, repl},\n\t}})\n}", "func (mb *MetricsBuilder) RecordRedisReplicationOffsetDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisReplicationOffset.recordDataPoint(mb.startTime, ts, val)\n}", "func (p *printer) recordLine(linePtr *int) {\n\tp.linePtr = linePtr\n}", "func (w *NamedHistogram) Record(elapsed time.Duration) {\n\tmaxLatency := time.Duration(w.mu.current.HighestTrackableValue())\n\tif elapsed < minLatency {\n\t\telapsed = minLatency\n\t} else if elapsed > maxLatency {\n\t\telapsed = maxLatency\n\t}\n\n\tw.mu.Lock()\n\terr := w.mu.current.RecordValue(elapsed.Nanoseconds())\n\tw.mu.Unlock()\n\n\tif err != nil {\n\t\t// Note that a histogram only drops recorded values that are out of range,\n\t\t// but we clamp the latency value to the configured range to prevent such\n\t\t// drops. This code path should never happen.\n\t\tpanic(fmt.Sprintf(`%s: recording value: %s`, w.name, err))\n\t}\n}", "func (mb *MetricsBuilder) RecordRedisNetInputDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisNetInput.recordDataPoint(mb.startTime, ts, val)\n}", "func (n *notifier) RecordRemove(x, y int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tOld: &Point{x, y, value},\n\t\t}})\n}", "func (metric *Int64Metric) Record(tags map[string]string, measurement int64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func (self *averageCache) Insert(dataPoints []*whisper.TimeSeriesPoint) {\n\tlog.WithFields(log.Fields{\n\t\t\"cache\": self.name,\n\t}).Debug(\"Insert\")\n\tself.inputChan <- dataPoints\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolOperationsDataPoint(ts pcommon.Timestamp, inputVal string, bufferPoolOperationsAttributeValue AttributeBufferPoolOperations) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlBufferPoolOperations, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlBufferPoolOperations.recordDataPoint(mb.startTime, ts, val, bufferPoolOperationsAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsNameCacheHitRateDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricActiveDirectoryDsNameCacheHitRate.recordDataPoint(mb.startTime, ts, val)\n}", "func (r *Recorder) Record(mediaSSRC uint32, sequenceNumber uint16, arrivalTime int64) {\n\tr.mediaSSRC = mediaSSRC\n\tif sequenceNumber < 0x0fff && (r.lastSequenceNumber&0xffff) > 0xf000 {\n\t\tr.cycles += 1 << 16\n\t}\n\tr.receivedPackets = insertSorted(r.receivedPackets, pktInfo{\n\t\tsequenceNumber: r.cycles | uint32(sequenceNumber),\n\t\tarrivalTime: arrivalTime,\n\t})\n\tr.lastSequenceNumber = sequenceNumber\n}", "func (log *Logger) Records(msg string, fd interface{}) {\n\tlog.pipeline[msg] = fd\n}", "func (b *Bucket) AddData(dataPoint data.Point) error {\n\terr := b.shards[b.index].AddData(dataPoint)\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif !errors.Is(err, ErrShardMaxReached) {\n\t\treturn err\n\t}\n\n\tvar m metrics.Metric\n\n\t// we have reached max timestamp for the current shard, make a new one\n\tif m, err = metrics.FromDescriptor(b.descriptor); err != nil {\n\t\treturn err\n\t}\n\tif err := m.AddData(dataPoint); err != nil {\n\t\treturn err\n\t}\n\n\tshard := NewShard(m, b.shardDuration)\n\n\tb.shards = append(b.shards, shard)\n\tb.index++\n\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordBigipPoolAvailabilityDataPoint(ts pcommon.Timestamp, val int64, availabilityStatusAttributeValue AttributeAvailabilityStatus) {\n\tmb.metricBigipPoolAvailability.recordDataPoint(mb.startTime, ts, val, availabilityStatusAttributeValue.String())\n}", "func (mb *MetricsBuilder) RecordBigipNodeAvailabilityDataPoint(ts pcommon.Timestamp, val int64, availabilityStatusAttributeValue AttributeAvailabilityStatus) {\n\tmb.metricBigipNodeAvailability.recordDataPoint(mb.startTime, ts, val, availabilityStatusAttributeValue.String())\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func (mb *MetricsBuilder) RecordFlinkJobCheckpointInProgressDataPoint(ts pcommon.Timestamp, inputVal string) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkJobCheckpointInProgress, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkJobCheckpointInProgress.recordDataPoint(mb.startTime, ts, val)\n\treturn nil\n}", "func (s *KinesisService) PutRecord(req *PutRecordRequest) (result *PutRecordResult, err error) {\n\n\tresult = new(PutRecordResult)\n\terr = s.wrapperSignAndDo(\"Kinesis_20131202.PutRecord\", req, result)\n\treturn\n}", "func (srv *InfluxSrv) Write(measurement string, fields map[string]interface{}, tags map[string]string) {\n\tsrv.writer.WritePoint(influxdb.NewPoint(measurement, tags, fields, time.Now()))\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationOperationPendingDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsReplicationOperationPending.recordDataPoint(mb.startTime, ts, val)\n}", "func (mb *MetricsBuilder) RecordMysqlLocksDataPoint(ts pcommon.Timestamp, inputVal string, locksAttributeValue AttributeLocks) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MysqlLocks, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMysqlLocks.recordDataPoint(mb.startTime, ts, val, locksAttributeValue.String())\n\treturn nil\n}", "func (gWal *GenericWAL) writeDataRecord(data []byte) (int64, error) {\n doneCh := make(chan *Response)\n\n if gWal.lostOwnership {\n return -1, ErrLostOwnership\n }\n\n lsn, errAdd := gWal.wal.AddDataEntry(data, false /* skipChecksum */, doneCh)\n if errAdd != nil {\n glog.Errorf(\"could not add wal entry :: %v\", errAdd)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n response := <-doneCh\n if response == nil {\n glog.Errorf(\"could not persist delta record to wal\")\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n\n if response.Result != nil {\n glog.Errorf(\"could not persist delta record to wal :: %v\", response.Result)\n gWal.lostOwnership = true\n return -1, ErrLostOwnership\n }\n return int64(lsn), nil\n}", "func (c *Client) AddRecord(ctx context.Context, zone, recordName, recordValue string) error {\n\tdomain, err := c.getDomain(ctx, zone)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecord := Record{DomainID: domain.ID, Name: recordName, Value: recordValue, Type: \"TXT\"}\n\n\terr = c.addTxtRecord(ctx, record)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.publishRecords(ctx, domain.ID)\n}", "func (o *EntryTracker) Record() *EntryRecord {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\n\tvar r EntryRecord\n\tif len(o.streams) > 0 {\n\t\tr.Streams = make(map[types.StreamPath]*StreamEntryRecord, len(o.streams))\n\t\tfor k, v := range o.streams {\n\t\t\tr.Streams[k] = v.record()\n\t\t}\n\t}\n\treturn &r\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsReplicationValueRateDataPoint(ts pcommon.Timestamp, val float64, directionAttributeValue AttributeDirection, valueTypeAttributeValue AttributeValueType) {\n\tmb.metricActiveDirectoryDsReplicationValueRate.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String(), valueTypeAttributeValue.String())\n}", "func (t *ZramInfoTracker) Record(pv *perf.Values) {\n\tif !t.hasZram {\n\t\treturn\n\t}\n\n\tfor i, stat := range t.stats {\n\t\tpv.Set(perf.Metric{\n\t\t\tName: t.prefix + \"RAM.Zram.\" + zramFieldNames[i],\n\t\t\tUnit: \"bytes\",\n\t\t\tDirection: perf.SmallerIsBetter,\n\t\t}, stat)\n\t}\n}", "func (vt *perfSchemaTable) AddRecord(ctx sessionctx.Context, r []types.Datum, skipHandleCheck bool) (recordID int64, err error) {\n\treturn 0, table.ErrUnsupportedOp\n}", "func (src *Source) StoreSavepoint() {\n\tsrc.savepointStack = append(src.savepointStack, &savepoint{\n\t\tcurrent: src.current,\n\t})\n}", "func NewRecord() *Record {\n\trecord := new(Record)\n\trecord.Formatted = new(bytes.Buffer)\n\treturn record\n}" ]
[ "0.7321669", "0.6991361", "0.6834238", "0.6516929", "0.64530843", "0.6376556", "0.6280639", "0.625649", "0.6252531", "0.6237906", "0.6132665", "0.612506", "0.60354906", "0.60345125", "0.6005778", "0.5993227", "0.59865916", "0.595146", "0.5946505", "0.59002554", "0.5885247", "0.58831114", "0.585158", "0.58467525", "0.581802", "0.5789543", "0.5783429", "0.57560873", "0.5752794", "0.5737017", "0.57337654", "0.5717129", "0.5708306", "0.56973016", "0.5680644", "0.56615627", "0.5644605", "0.56051266", "0.56027853", "0.5601796", "0.5601041", "0.5587749", "0.5566232", "0.55433905", "0.5539408", "0.55269486", "0.55267376", "0.55249363", "0.55137956", "0.5504769", "0.550279", "0.5499125", "0.5498905", "0.5468015", "0.54636484", "0.5461485", "0.54598176", "0.54538006", "0.5437438", "0.5433776", "0.54240125", "0.5421191", "0.539755", "0.53953046", "0.5388757", "0.53875554", "0.53611743", "0.53575253", "0.53533185", "0.5343173", "0.5329281", "0.53225374", "0.53185606", "0.53123873", "0.53057146", "0.5297677", "0.52857447", "0.5262405", "0.5262092", "0.5254877", "0.5247429", "0.5245295", "0.52447134", "0.52299714", "0.52294827", "0.5201413", "0.51982105", "0.5198131", "0.519694", "0.5187185", "0.5178688", "0.5175154", "0.51684326", "0.5154603", "0.515326", "0.51525706", "0.51474214", "0.51465595", "0.5144451", "0.5143458" ]
0.61025167
12
RecordN efficiently records a data point N times.
func (h *Histogram) RecordN(v float64, n int) { h.Counter.RecordN(v, n) h.record(v, n) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *PCPHistogram) RecordN(val, n int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValues(val, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func (c *Counter) RecordN(v float64, n int) {\n\tisFirst := (c.Count == 0)\n\tc.Count += int64(n)\n\tif isFirst {\n\t\tc.Min = v\n\t\tc.Max = v\n\t} else if v < c.Min {\n\t\tc.Min = v\n\t} else if v > c.Max {\n\t\tc.Max = v\n\t}\n\ts := v * float64(n)\n\tc.Sum += s\n\tc.sumOfSquares += (s * s)\n}", "func RecordFilteredInN(n int) {\n\tstats.Record(context.Background(), mRecordsFilteredIn.M(int64(n)))\n}", "func MemoryRecordN(b *MemoryBackend, n int) *Record {\n\tnode := b.Head()\n\tfor i := 0; i < n; i++ {\n\t\tif node == nil {\n\t\t\tbreak\n\t\t}\n\t\tnode = node.Next()\n\t}\n\tif node == nil {\n\t\treturn nil\n\t}\n\treturn node.Record\n}", "func RecordFilteredOutN(n int) {\n\tstats.Record(context.Background(), mRecordsFilteredOut.M(int64(n)))\n}", "func (r *Dbfgo) GetRecordN(n int64) Record {\n\tvar record Record\n\tr.reader.Seek(0, 0)\n\trecordlen := r.Header.Recordlen\n\tstart := r.Header.Headerlen + n*r.Header.Recordlen\n\tbuf := make([]byte, recordlen)\n\t_, err := r.reader.ReadAt(buf, start)\n\tif err != nil {\n\t\treturn record\n\t}\n\ttempdata := map[string]string{}\n\t//record is deleted if there is a '*'\n\trecord.NotDeleted = (string(buf[0:1]) != \"*\")\n\ta := int64(1)\n\tfor _, val := range r.Fields {\n\t\tfieldlen := val.FieldLen\n\t\ttempdata[val.Name] = strings.Trim(fmt.Sprintf(\"%s\", buf[a:a+fieldlen]), \" \")\n\t\ta = a + fieldlen\n\t}\n\trecord.Data = tempdata\n\treturn record\n}", "func (c *Counter) Record(v float64) {\n\tc.RecordN(v, 1)\n}", "func (h *PCPHistogram) MustRecordN(val, n int64) {\n\tif err := h.RecordN(val, n); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func record(ctx context.Context, ms ...stats.Measurement) {\n\tstats.Record(ctx, ms...)\n}", "func (nv *NetView) Record(counters string, rastCtr int) {\n\tnv.DataMu.Lock()\n\tdefer nv.DataMu.Unlock()\n\tif counters != \"\" {\n\t\tnv.LastCtrs = counters\n\t}\n\tnv.Data.PrjnType = nv.Params.PrjnType\n\tnv.Data.Record(nv.LastCtrs, rastCtr, nv.Params.Raster.Max)\n\tnv.RecTrackLatest() // if we make a new record, then user expectation is to track latest..\n}", "func BenchmarkLastNWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastN\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func (r *rawHist) record(t int64, v float64) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\tr.buf = append(r.buf, &pb.Sample{\n\t\tDatetime: t,\n\t\tValue: v,\n\t})\n\tif int32(len(r.buf)) >= GetRawHistBufLimit() {\n\t\tbuf := r.buf\n\t\tr.buf = make([]*pb.Sample, 0, GetRawHistBufLimit()/2)\n\t\tgo r.assembleAndSend(buf)\n\t}\n}", "func NewRecords(n int) *Records {\n\treturn &Records{\n\t\tarr: make([]*Record, 0, n),\n\t\tm: make(map[string]*Record, 100),\n\t\tdups: make(map[string]struct{}, 10),\n\t}\n}", "func (d *Dataset) RecordCount() int {\n\tcount := 0\n\tif d.BlockCount() > 0 {\n\t\tfor _, block := range d.blocks {\n\t\t\tcount += block.RecordCount()\n\t\t}\n\t}\n\n\treturn count\n}", "func (h *Histogram) Record(v float64) {\n\th.RecordN(v, 1)\n}", "func (b *recBatch) appendRecord(pr promisedRec, nums recordNumbers) {\n\tb.wireLength += nums.wireLength\n\tb.v1wireLength += messageSet1Length(pr.Record)\n\tb.records = append(b.records, promisedNumberedRecord{\n\t\tnums,\n\t\tpr,\n\t})\n}", "func (h *HistCompat) RecordValues(value int64, n int64) error {\n\th.addWeightedValue(value, n)\n\n\treturn nil\n}", "func (h *MultiHistCompat) RecordValues(value int64, n int64) error {\n\th.addWeightedValue(value, n)\n\n\treturn nil\n}", "func (n *notifier) RecordAdd(x, y int, value interface{}) {\n\tn.add([]Update{\n\t\tUpdate{\n\t\t\tNew: &Point{x, y, value},\n\t\t}})\n}", "func (x *Writer) emitDataRecord(p []byte) error {\n\t// collect all the stuff that goes into this type of record\n\tvar data = []interface{}{\n\t\tbyte(len(p)), // byte count\n\t\tx.addr, // standard 16-bit base address\n\t\tbyte(Data), // record type\n\t\tp, // slice of data\n\t}\n\n\terr := x.emitRecord(data)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"emitDataRecord: %v\", err)\n\t}\n\n\tx.addr += uint16(len(p))\n\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordFlinkOperatorRecordCountDataPoint(ts pcommon.Timestamp, inputVal string, operatorNameAttributeValue string, recordAttributeValue AttributeRecord) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkOperatorRecordCount, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkOperatorRecordCount.recordDataPoint(mb.startTime, ts, val, operatorNameAttributeValue, recordAttributeValue.String())\n\treturn nil\n}", "func updateN(n int, b *testing.B) {\n\tb.StopTimer()\n\tw := benchWorld()\n\tp := benchPlayer()\n\n\tvar bds boids\n\tboidVal := bds.Generate(rand.New(rand.NewSource(rand.Int63())), n)\n\tbds = boidVal.Interface().(boids)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tUpdateBoids(uint(i), bds, p, w)\n\t}\n}", "func (record) RecordCount(b []byte) int {\n\treturn len(b) / recordLength\n}", "func (s *Simulator) BatchN() int {\n\tn := s.PointN() / s.BatchSize\n\tif s.PointN()%s.BatchSize != 0 {\n\t\tn++\n\t}\n\treturn n\n}", "func (c *Prometheus) TrackMetricN(section string, operation *bucket.MetricOperation, n int) Client {\n\tb := bucket.NewPrometheus(section, operation, true, c.unicode)\n\tmetric := b.Metric()\n\tmetricTotal := b.MetricTotal()\n\n\tmetricInc := c.getIncrementer(metric)\n\tmetricTotalInc := c.getIncrementer(metricTotal)\n\n\tmetric = c.prepareMetric(metric)\n\tmetricTotal = c.prepareMetric(metricTotal)\n\tmetricInc.IncrementN(metric, n, operation.Labels)\n\tmetricTotalInc.IncrementN(metricTotal, n, operation.Labels)\n\n\treturn c\n}", "func (b *recBatch) calculateRecordNumbers(r *Record) recordNumbers {\n\ttsMillis := r.Timestamp.UnixNano() / 1e6\n\ttsDelta := int32(tsMillis - b.firstTimestamp)\n\toffsetDelta := int32(len(b.records)) // since called before adding record, delta is the current end\n\n\tl := 1 + // attributes, int8 unused\n\t\tkbin.VarintLen(tsDelta) +\n\t\tkbin.VarintLen(offsetDelta) +\n\t\tkbin.VarintLen(int32(len(r.Key))) +\n\t\tlen(r.Key) +\n\t\tkbin.VarintLen(int32(len(r.Value))) +\n\t\tlen(r.Value) +\n\t\tkbin.VarintLen(int32(len(r.Headers))) // varint array len headers\n\n\tfor _, h := range r.Headers {\n\t\tl += kbin.VarintLen(int32(len(h.Key))) +\n\t\t\tlen(h.Key) +\n\t\t\tkbin.VarintLen(int32(len(h.Value))) +\n\t\t\tlen(h.Value)\n\t}\n\n\treturn recordNumbers{\n\t\twireLength: int32(kbin.VarintLen(int32(l)) + l),\n\t\tlengthField: int32(l),\n\t\ttimestampDelta: tsDelta,\n\t}\n}", "func (info HistogramInt64) Record(e *Config, key *keys.Int64) {\n\tdata := &HistogramInt64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (h *Histogram) record(v float64, count int) {\n\t// Scaled value to bucketize - we subtract epsilon because the interval\n\t// is open to the left ] start, end ] so when exactly on start it has\n\t// to fall on the previous bucket. TODO add boundary tests\n\tscaledVal := (v-h.Offset)/h.Divider - 0.0001\n\tvar idx int\n\tif scaledVal <= firstValue {\n\t\tidx = 0\n\t} else if scaledVal > lastValue {\n\t\tidx = numBuckets - 1 // last bucket is for > last value\n\t} else {\n\t\t// else we look it up\n\t\tidx = lookUpIdx(int(scaledVal))\n\t}\n\th.Hdata[idx] += int32(count)\n}", "func NewRecord(row []string, filename string, n int) (Record, error) {\n\tvar record Record = Record{}\n\tif len(row) < 3 {\n\t\treturn record, fmt.Errorf(\"Not enough columns in file %s after %d records\",\n\t\t\tfilename, n)\n\t}\n\tif row[1] == \"1\" || strings.ToLower(row[1]) == \"true\" {\n\t\trecord.Sensor = true\n\t} else if row[1] != \"0\" && strings.ToLower(row[1]) != \"false\" {\n\t\treturn record, fmt.Errorf(\"Expected 'true' or 'false' in file %s after %d records\",\n\t\t\tfilename, n)\n\t}\n\tfor _, col := range row[2:] {\n\t\trecord.Address += col\n\t}\n\trecord.Source = filename\n\trecord.ID = row[0]\n\treturn record, nil\n}", "func (mb *MetricsBuilder) RecordBigipNodePacketCountDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipNodePacketCount.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func BenchmarkLastNMeanWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastNMean\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func (metric *Int64Metric) Record(tags map[string]string, measurement int64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func testSetN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Set(Key(i), i)\n\t}\n}", "func (summary *Summary) Record(name string, data interface{}) {\n\titem, ok := summary.Data[name]\n\tif !ok {\n\t\titem = new(Metrics)\n\t\titem.Keys = make(map[string]Metric)\n\t\tsummary.Data[name] = item\n\t}\n\n\titem.Hits++\n\trecordMembers(reflect.ValueOf(data).Elem(), item.Keys, \"\")\n}", "func (s *Collector) Record(name string, stats []*Stat) error {\n\treturn NOT_IMPLEMENTED\n}", "func (p *SimplePipeline) DoN(n int, fs ...ProcessFunc) (total uint) {\n\ttotal = uint(0)\n\tread := p.BlockSize()\n\tfor i := 0; i < n && read != p.BlockSize(); i++ {\n\t\t// TODO(jwall): Is it safe to share the buffer?\n\t\tout := NewSimpleBuffer(p.BufSize())\n\t\tdefer out.Free()\n\t\tread = p.do(fs)\n\t\ttotal += read\n\t}\n\treturn\n}", "func TestFileRecorder(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"/tmp\", \"file-recorder\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tfr, err := pool.NewFileRecorder(path.Join(dir, \"file-recorder\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer fr.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tif err := fr.Put([]byte(fmt.Sprintf(\"nice to meet you %d\", i))); err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 100; i < 50000; i++ {\n\t\t\tif err := fr.Put([]byte(fmt.Sprintf(\"nice to meet you %d\", i))); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor i := 0; i < 100; i++ {\n\t\tif bs, err := fr.GetN(20); err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t} else {\n\t\t\t// for _, b := range bs {\n\t\t\t// \tb\n\t\t\t// \t// fmt.Println(string(b))\n\t\t\t// }\n\t\t\tif len(bs) != 20 {\n\t\t\t\tif err := fr.Rewind(); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\twg.Wait()\n}", "func (info HistogramFloat64) Record(e *Config, key *keys.Float64) {\n\tdata := &HistogramFloat64Data{Info: &info, key: key}\n\te.subscribe(key, data.record)\n}", "func (metric *Float64Metric) Record(tags map[string]string, measurement float64) error {\n\tvar mutators []tag.Mutator\n\n\ttagMapMutex.RLock()\n\tdefer tagMapMutex.RUnlock()\n\n\tfor tagName, tagValue := range tags {\n\t\ttagKey, ok := tagMap[tagName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"referencing none existing tag %q in metric %q\", tagName, metric.name)\n\t\t}\n\t\tmutators = append(mutators, tag.Upsert(tagKey, tagValue))\n\t}\n\n\treturn stats.RecordWithTags(\n\t\tcontext.Background(),\n\t\tmutators,\n\t\tmetric.measure.M(measurement))\n}", "func FixedLengthRecordDataset(scope *Scope, filenames tf.Output, header_bytes tf.Output, record_bytes tf.Output, footer_bytes tf.Output, buffer_size tf.Output, optional ...FixedLengthRecordDatasetAttr) (handle tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"FixedLengthRecordDataset\",\n\t\tInput: []tf.Input{\n\t\t\tfilenames, header_bytes, record_bytes, footer_bytes, buffer_size,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (mb *MetricsBuilder) RecordFlinkTaskRecordCountDataPoint(ts pcommon.Timestamp, inputVal string, recordAttributeValue AttributeRecord) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for FlinkTaskRecordCount, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricFlinkTaskRecordCount.recordDataPoint(mb.startTime, ts, val, recordAttributeValue.String())\n\treturn nil\n}", "func (mb *MetricsBuilder) RecordBigipPoolPacketCountDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolPacketCount.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (s *StoragePointsWriterRecorder) Record(ctx context.Context, run *taskmodel.Run) error {\n\ttags := models.NewTags(map[string]string{\n\t\tstatusTag: run.Status,\n\t\ttaskIDTag: run.TaskID.String(),\n\t})\n\n\t// log an error if we have incomplete data on finish\n\tif !run.ID.Valid() ||\n\t\trun.ScheduledFor.IsZero() ||\n\t\trun.StartedAt.IsZero() ||\n\t\trun.FinishedAt.IsZero() ||\n\t\trun.Status == \"\" {\n\t\ts.log.Error(\"Run missing critical fields\", zap.String(\"run\", fmt.Sprintf(\"%+v\", run)), zap.String(\"runID\", run.ID.String()))\n\t}\n\n\tfields := map[string]interface{}{}\n\tfields[runIDField] = run.ID.String()\n\tfields[startedAtField] = run.StartedAt.Format(time.RFC3339Nano)\n\tfields[finishedAtField] = run.FinishedAt.Format(time.RFC3339Nano)\n\tfields[scheduledForField] = run.ScheduledFor.Format(time.RFC3339)\n\tfields[requestedAtField] = run.RequestedAt.Format(time.RFC3339)\n\n\tstartedAt := run.StartedAt\n\tif startedAt.IsZero() {\n\t\tstartedAt = time.Now().UTC()\n\t}\n\n\tlogBytes, err := json.Marshal(run.Log)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields[logField] = string(logBytes)\n\n\tpoint, err := models.NewPoint(s.destination.Measurement, tags, fields, startedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.cli.WriteV2(influxdb.FluxWrite{\n\t\tBucket: s.destination.Bucket,\n\t\tOrg: s.destination.Org,\n\t\tOrgID: s.destination.OrgID,\n\t\tPoints: models.Points{point},\n\t})\n}", "func (mb *MetricsBuilder) RecordBigipVirtualServerPacketCountDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipVirtualServerPacketCount.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (m *metricFlinkOperatorRecordCount) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func WriteCount(buffer []byte, offset int, value byte, valueCount int) {\n for i := 0; i < valueCount; i++ {\n buffer[offset + i] = value\n }\n}", "func readRawRecords(n int, in []byte) []kmsg.Record {\n\trs := make([]kmsg.Record, n)\n\tfor i := 0; i < n; i++ {\n\t\tlength, used := kbin.Varint(in)\n\t\ttotal := used + int(length)\n\t\tif used == 0 || length < 0 || len(in) < total {\n\t\t\treturn rs[:i]\n\t\t}\n\t\tif err := (&rs[i]).ReadFrom(in[:total]); err != nil {\n\t\t\treturn rs[:i]\n\t\t}\n\t\tin = in[total:]\n\t}\n\treturn rs\n}", "func (f *flusher) RecordNumeric64(mtype int, name string, value num64.Numeric64, flush bool) {\n\tf.mu.Lock()\n\tf.sink.RecordNumeric64(mtype, name, value)\n\tif flush {\n\t\tf.sink.Flush()\n\t}\n\tf.mu.Unlock()\n}", "func (a *Activity) Record(samples []*Sample, altitudeReference string) error {\n\tdata := struct {\n\t\tSamples []*Sample `json:\"samples\"`\n\t\tActivityId int `json:\"activityId\"`\n\t\tAltitudeReference string `json:\"altitudeReference\"`\n\t}{\n\t\tSamples: samples,\n\t\tActivityId: a.Id,\n\t\tAltitudeReference: altitudeReference,\n\t}\n\treq, err := a.c.newRequestJSON(\"POST\", a.c.apiURL+\"/activity/record\", &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := a.c.doRequest(req, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RecordBatch(ctx context.Context, labels LabelSet, batch ...Measurement) {\n\tGlobalMeter().RecordBatch(ctx, labels, batch...)\n}", "func (mb *MetricsBuilder) RecordBigipVirtualServerRequestCountDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricBigipVirtualServerRequestCount.recordDataPoint(mb.startTime, ts, val)\n}", "func Record(ctx context.Context, ms ...Measurement) {\n\treq := &recordReq{\n\t\tnow: time.Now(),\n\t\ttm: tag.FromContext(ctx),\n\t\tms: ms,\n\t}\n\tdefaultWorker.c <- req\n}", "func (r *Recorder) Record(mediaSSRC uint32, sequenceNumber uint16, arrivalTime int64) {\n\tr.mediaSSRC = mediaSSRC\n\tif sequenceNumber < 0x0fff && (r.lastSequenceNumber&0xffff) > 0xf000 {\n\t\tr.cycles += 1 << 16\n\t}\n\tr.receivedPackets = insertSorted(r.receivedPackets, pktInfo{\n\t\tsequenceNumber: r.cycles | uint32(sequenceNumber),\n\t\tarrivalTime: arrivalTime,\n\t})\n\tr.lastSequenceNumber = sequenceNumber\n}", "func GenerateData[N Number](len int, dtype DataType) []Element[N] {\n\tres := make([]Element[N], len)\n\tt := int64(0)\n\tfor i := 0; i < len; i++ {\n\t\tswitch dtype {\n\t\tcase Int32:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(int32(i)),\n\t\t\t}\n\t\tcase Float32:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(float32(i)),\n\t\t\t}\n\t\tcase Float64:\n\t\t\tres[i] = Element[N]{\n\t\t\t\tTimestamp: t,\n\t\t\t\tValue: N(float64(i)),\n\t\t\t}\n\t\t}\n\t\tt += 3\n\t}\n\treturn res\n}", "func (t *ZramInfoTracker) Record(pv *perf.Values) {\n\tif !t.hasZram {\n\t\treturn\n\t}\n\n\tfor i, stat := range t.stats {\n\t\tpv.Set(perf.Metric{\n\t\t\tName: t.prefix + \"RAM.Zram.\" + zramFieldNames[i],\n\t\t\tUnit: \"bytes\",\n\t\t\tDirection: perf.SmallerIsBetter,\n\t\t}, stat)\n\t}\n}", "func (h *PCPHistogram) Record(val int64) error {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\terr := h.h.RecordValue(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn h.update()\n}", "func (d *DB) recordMetrics() {\n\tticker := time.NewTicker(time.Second * time.Duration(30))\n\n\tfor range ticker.C {\n\t\tvar streamCount float64\n\t\terr := d.DB.Get(&streamCount, `SELECT COUNT(*) FROM streams`)\n\t\tif err != nil {\n\t\t\td.logger.Log(\n\t\t\t\t\"msg\", \"error counting streams\",\n\t\t\t\t\"err\", err,\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\tStreamGauge.Set(streamCount)\n\t}\n}", "func (i *TelemetryStorage) RecordEventsStats(dataType int, count int64) {\n\tswitch dataType {\n\tcase constants.EventsDropped:\n\t\tatomic.AddInt64(&i.records.eventsDropped, count)\n\tcase constants.EventsQueued:\n\t\tatomic.AddInt64(&i.records.eventsQueued, count)\n\t}\n}", "func (recBuf *recBuf) bufferRecord(pr promisedRec, abortOnNewBatch bool) bool {\n\trecBuf.mu.Lock()\n\tdefer recBuf.mu.Unlock()\n\n\t// Timestamp after locking to ensure sequential, and truncate to\n\t// milliseconds to avoid some accumulated rounding error problems\n\t// (see Shopify/sarama#1455)\n\tpr.Timestamp = time.Now().Truncate(time.Millisecond)\n\n\tnewBatch := true\n\tdrainBatch := recBuf.batchDrainIdx == len(recBuf.batches)\n\n\tproduceVersionKnown := atomic.LoadUint32(&recBuf.sink.produceVersionKnown) == 1\n\tif !drainBatch {\n\t\tbatch := recBuf.batches[len(recBuf.batches)-1]\n\t\trecordNumbers := batch.calculateRecordNumbers(pr.Record)\n\n\t\tnewBatchLength := batch.wireLength + recordNumbers.wireLength\n\n\t\t// If we do not know the broker version, we may be talking\n\t\t// to <0.11.0 and be using message sets. Until we know the\n\t\t// broker version, we pessimisitically cut our batch off using\n\t\t// the largest record length numbers.\n\t\tif !produceVersionKnown {\n\t\t\tv1newBatchLength := batch.v1wireLength + messageSet1Length(pr.Record)\n\t\t\tif v1newBatchLength > newBatchLength { // we only check v1 since it is larger than v0\n\t\t\t\tnewBatchLength = v1newBatchLength\n\t\t\t}\n\t\t} else {\n\t\t\t// If we do know our broker version and it is indeed\n\t\t\t// an old one, we use the appropriate length.\n\t\t\tswitch recBuf.sink.produceVersion {\n\t\t\tcase 0, 1:\n\t\t\t\tnewBatchLength = batch.v0wireLength() + messageSet0Length(pr.Record)\n\t\t\tcase 2:\n\t\t\t\tnewBatchLength = batch.v1wireLength + messageSet1Length(pr.Record)\n\t\t\t}\n\t\t}\n\n\t\tif batch.tries == 0 && newBatchLength <= recBuf.maxRecordBatchBytes {\n\t\t\tnewBatch = false\n\t\t\tbatch.appendRecord(pr, recordNumbers)\n\t\t}\n\t}\n\n\tif newBatch {\n\t\tnewBatch := recBuf.newRecordBatch(pr)\n\n\t\t// Before we decide to keep this new batch, if this single record is too\n\t\t// large for a batch, then we immediately fail it.\n\t\tnewBatchLength := newBatch.wireLength\n\t\tif !produceVersionKnown && newBatch.v1wireLength > newBatchLength {\n\t\t\tnewBatchLength = newBatch.v1wireLength\n\t\t} else {\n\t\t\tswitch recBuf.sink.produceVersion {\n\t\t\tcase 0, 1:\n\t\t\t\tnewBatchLength = newBatch.v0wireLength()\n\t\t\tcase 2:\n\t\t\t\tnewBatchLength = newBatch.v1wireLength\n\t\t\t}\n\t\t}\n\t\tif newBatchLength > recBuf.maxRecordBatchBytes {\n\t\t\trecBuf.cl.finishRecordPromise(pr, kerr.MessageTooLarge)\n\t\t\treturn true\n\t\t}\n\n\t\tif abortOnNewBatch {\n\t\t\treturn false\n\t\t}\n\t\trecBuf.batches = append(recBuf.batches, newBatch)\n\t}\n\n\tif recBuf.cl.cfg.linger == 0 {\n\t\tif drainBatch {\n\t\t\trecBuf.sink.maybeDrain()\n\t\t}\n\t} else {\n\t\t// With linger, if this is a new batch but not the first, we\n\t\t// stop lingering and begin draining. The drain loop will\n\t\t// restart our linger once this buffer has one batch left.\n\t\tif newBatch && !drainBatch ||\n\t\t\t// If this is the first batch, try lingering; if\n\t\t\t// we cannot, we are being flushed and must drain.\n\t\t\tdrainBatch && !recBuf.lockedMaybeStartLinger() {\n\t\t\trecBuf.lockedStopLinger()\n\t\t\trecBuf.sink.maybeDrain()\n\t\t}\n\t}\n\treturn true\n}", "func (m *HeavySyncMock) StoreRecords(p context.Context, p1 insolar.ID, p2 insolar.PulseNumber, p3 [][]byte) {\n\tcounter := atomic.AddUint64(&m.StoreRecordsPreCounter, 1)\n\tdefer atomic.AddUint64(&m.StoreRecordsCounter, 1)\n\n\tif len(m.StoreRecordsMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.StoreRecordsMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to HeavySyncMock.StoreRecords. %v %v %v %v\", p, p1, p2, p3)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.StoreRecordsMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, HeavySyncMockStoreRecordsInput{p, p1, p2, p3}, \"HeavySync.StoreRecords got unexpected parameters\")\n\n\t\treturn\n\t}\n\n\tif m.StoreRecordsMock.mainExpectation != nil {\n\n\t\tinput := m.StoreRecordsMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, HeavySyncMockStoreRecordsInput{p, p1, p2, p3}, \"HeavySync.StoreRecords got unexpected parameters\")\n\t\t}\n\n\t\treturn\n\t}\n\n\tif m.StoreRecordsFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to HeavySyncMock.StoreRecords. %v %v %v %v\", p, p1, p2, p3)\n\t\treturn\n\t}\n\n\tm.StoreRecordsFunc(p, p1, p2, p3)\n}", "func BenchmarkLastNSumWrite(b *testing.B) {\n\tfor i := 0; i < 50000; i++ {\n\t\tStoreClient.TSJSON.Write(dsID+\"benchmarkLastNSum\", []byte(\"{\\\"value\\\":\"+strconv.Itoa(i)+\"}\"))\n\t}\n}", "func (rw *recordWriter) Write(data []byte) (int, error) {\n\n\tif rw.err != nil {\n\t\treturn int(rw.n), nil\n\t}\n\n\tvar n int\n\tn, rw.err = rw.w.Write(data)\n\trw.n += uint64(n)\n\treturn n, nil\n}", "func (b *Buffer) Store(record *data.Record) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.records = append(b.records, record)\n\n\tif len(b.records) >= b.bufferSize {\n\t\tb.flush()\n\t}\n}", "func (mb *MetricsBuilder) RecordBigipNodeRequestCountDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricBigipNodeRequestCount.recordDataPoint(mb.startTime, ts, val)\n}", "func (m *metricFlinkTaskRecordCount) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func (me *Metrics) RecordStoredDataFetchTime(labels StoredDataLabels, length time.Duration) {\n\tme.StoredDataFetchTimer[labels.DataType][labels.DataFetchType].Update(length)\n}", "func (c *Client) Store(samples model.Samples) error {\n\treq := &WriteRequest{\n\t\tTimeseries: make([]*TimeSeries, 0, len(samples)),\n\t}\n\tfor _, s := range samples {\n\t\tts := &TimeSeries{\n\t\t\tLabels: make([]*LabelPair, 0, len(s.Metric)),\n\t\t}\n\t\tfor k, v := range s.Metric {\n\t\t\tts.Labels = append(ts.Labels,\n\t\t\t\t&LabelPair{\n\t\t\t\t\tName: string(k),\n\t\t\t\t\tValue: string(v),\n\t\t\t\t})\n\t\t}\n\t\tts.Samples = []*Sample{\n\t\t\t{\n\t\t\t\tValue: float64(s.Value),\n\t\t\t\tTimestampMs: int64(s.Timestamp),\n\t\t\t},\n\t\t}\n\t\treq.Timeseries = append(req.Timeseries, ts)\n\t}\n\n\tdata, err := proto.Marshal(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuf := bytes.Buffer{}\n\tif _, err := snappy.NewWriter(&buf).Write(data); err != nil {\n\t\treturn err\n\t}\n\n\thttpReq, err := http.NewRequest(\"POST\", c.url.String(), &buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.Header.Add(\"Content-Encoding\", \"snappy\")\n\n\tctx, _ := context.WithTimeout(context.Background(), c.timeout)\n\thttpResp, err := ctxhttp.Do(ctx, c.client, httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpResp.Body.Close()\n\tif httpResp.StatusCode/100 != 2 {\n\t\treturn fmt.Errorf(\"server returned HTTP status %s\", httpResp.Status)\n\t}\n\treturn nil\n}", "func (lp *LimitedCounter) ApplyN(delta int) {\n\tfor i := 0; i < delta; i++ {\n\t\tlp.counter <- 1\n\t}\n\tfor i := 0; i > delta; i-- {\n\t\t<-lp.counter\n\t}\n\n\tlp.wg.Add(delta)\n}", "func (conn *Connection) GetLimitedRecords(q interface{}, n int, doc interface{}, fields ...string) error {\n\tif len(fields) == 0 {\n\t\treturn conn.collection.Find(q).Limit(n).All(doc)\n\t}\n\n\treturn conn.collection.Find(q).Sort(fields...).Limit(n).All(doc)\n}", "func testCountN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Count()\n\t}\n}", "func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {\n\tbc.mu.RLock()\n\tdefer bc.mu.RUnlock()\n\n\tif first > last {\n\t\treturn fmt.Errorf(\"export failed: first (%d) is greater than last (%d)\", first, last)\n\t}\n\tlog.Fatal(\"Exporting batch of blocks\", \"count\", last-first+1)\n\n\tfor nr := first; nr <= last; nr++ {\n\t\tblock := bc.GetBlockByNumber(nr)\n\t\tif block == nil {\n\t\t\treturn fmt.Errorf(\"export failed on #%d: not found\", nr)\n\t\t}\n\n\t\tif err := block.EncodeRLP(w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tracer *TraceLogger) Record(context string, data []byte) {\n\tgo func() {\n\t\ttracer.traceMutex.Lock()\n\t\tdefer tracer.traceMutex.Unlock()\n\t\tif tracer.fileHandle == nil || tracer.isReplaying {\n\t\t\treturn\n\t\t}\n\t\tts := stratuxClock.Time.Format(time.RFC3339Nano)\n\t\ttracer.csvWriter.Write([]string {ts, context, string(data)})\n\t}()\n}", "func addValuesAtIndex(store *btts.BigTableTraceStore, index int32, keyValues map[string]float32, filename string, ts time.Time) error {\n\tps := paramtools.ParamSet{}\n\tparams := []paramtools.Params{}\n\tvalues := []float32{}\n\tfor k, v := range keyValues {\n\t\tp, err := query.ParseKey(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tps.AddParams(p)\n\t\tparams = append(params, p)\n\t\tvalues = append(values, v)\n\t}\n\treturn store.WriteTraces(index, params, values, ps, filename, ts)\n}", "func (mb *MetricsBuilder) RecordBigipPoolRequestCountDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricBigipPoolRequestCount.recordDataPoint(mb.startTime, ts, val)\n}", "func (m *Measurement) Record(name string, duration time.Duration) {\n\tr := m.Result(name)\n\tr.Durations = append(r.Durations, duration)\n}", "func (p *Provider) record(tx *lease.Tx) {\n\tvar ops uint64 // Total number of consumptive ops (really op effects)\n\n\tfor _, op := range tx.Ops() {\n\t\tif op.Type == lease.Update && op.UpdateType() == lease.Renew {\n\t\t\t// Don't record renewals\n\t\t\tcontinue\n\t\t}\n\t\tfor _, effect := range op.Effects() {\n\t\t\tif !effect.Consumptive() {\n\t\t\t\t// Only record effects that affect consumption\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tp.log.Printf(\"TX %s\", effect.String())\n\t\t\tops++\n\t\t}\n\t}\n\n\tp.add(ops)\n}", "func (mb *MetricsBuilder) RecordBigipPoolMemberPacketCountDataPoint(ts pcommon.Timestamp, val int64, directionAttributeValue AttributeDirection) {\n\tmb.metricBigipPoolMemberPacketCount.recordDataPoint(mb.startTime, ts, val, directionAttributeValue.String())\n}", "func (e *LogLoss) Record(probability float64, weight float64) {\n\te.mu.Lock()\n\te.weight += weight\n\te.sum += weight * math.Log(probability+e.Epsilon)\n\te.mu.Unlock()\n}", "func (dsc *DefaultConsumerStatsCollector) AddGetRecordsCalled(count int) {\n\tdsc.GetRecordsCalled.Inc(int64(count))\n}", "func (i *InMemoryPlayerStore) RecordWin(name string) {\n\ti.store[name]++\n}", "func benchmarker(n int, f action) (err error) {\n\tfor i := 0; i < n; i++ {\n\t\tif err = f(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (q *Query) Batch(n int) *Query {\n\tq.q = q.q.Batch(n)\n\treturn q\n}", "func (s Stream) Limit(n int) Stream {\n\treturn s.Pipe(func() func(r Record) (Record, error) {\n\t\tvar count int\n\n\t\treturn func(r Record) (Record, error) {\n\t\t\tif count < n {\n\t\t\t\tcount++\n\t\t\t\treturn r, nil\n\t\t\t}\n\n\t\t\treturn nil, ErrStreamClosed\n\t\t}\n\t})\n}", "func (g *Gauge) Record(value int64) {\n\tatomic.StoreInt64(&g.value, value)\n}", "func (s *SqliteServer) WriteRecords(records []gdp.Record) error {\n\tif len(records) == 0 {\n\t\treturn nil\n\t}\n\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\tstmt, err := tx.Prepare(\"INSERT INTO log_entry (hash, recno, timestamp, accuracy, prevhash, value, sig) VALUES (?, ?, ?, ?, ?, ?, ?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\tfor _, record := range records {\n\t\t_, err = stmt.Exec(\n\t\t\trecord.Hash[:],\n\t\t\trecord.RecNo,\n\t\t\trecord.Timestamp,\n\t\t\trecord.Accuracy,\n\t\t\trecord.PrevHash[:],\n\t\t\trecord.Value,\n\t\t\trecord.Sig,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tzap.S().Infow(\n\t\t\"Wrote records\",\n\t\t\"numRecords\", len(records),\n\t)\n\n\treturn nil\n}", "func (s *source) takeNBuffered(n int) (Fetch, int, bool) {\n\tvar r Fetch\n\tvar taken int\n\n\tb := &s.buffered\n\tbf := &b.fetch\n\tfor len(bf.Topics) > 0 && n > 0 {\n\t\tt := &bf.Topics[0]\n\n\t\tr.Topics = append(r.Topics, *t)\n\t\trt := &r.Topics[len(r.Topics)-1]\n\t\trt.Partitions = nil\n\n\t\ttCursors := b.usedOffsets[t.Topic]\n\n\t\tfor len(t.Partitions) > 0 && n > 0 {\n\t\t\tp := &t.Partitions[0]\n\n\t\t\trt.Partitions = append(rt.Partitions, *p)\n\t\t\trp := &rt.Partitions[len(rt.Partitions)-1]\n\t\t\trp.Records = nil\n\n\t\t\ttake := n\n\t\t\tif take > len(p.Records) {\n\t\t\t\ttake = len(p.Records)\n\t\t\t}\n\n\t\t\trp.Records = p.Records[:take]\n\t\t\tp.Records = p.Records[take:]\n\n\t\t\tn -= take\n\t\t\ttaken += take\n\n\t\t\tpCursor := tCursors[p.Partition]\n\n\t\t\tif len(p.Records) == 0 {\n\t\t\t\tt.Partitions = t.Partitions[1:]\n\n\t\t\t\tpCursor.from.setOffset(pCursor.cursorOffset)\n\t\t\t\tpCursor.from.allowUsable()\n\t\t\t\tdelete(tCursors, p.Partition)\n\t\t\t\tif len(tCursors) == 0 {\n\t\t\t\t\tdelete(b.usedOffsets, t.Topic)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tlastReturnedRecord := rp.Records[len(rp.Records)-1]\n\t\t\tpCursor.from.setOffset(cursorOffset{\n\t\t\t\toffset: lastReturnedRecord.Offset + 1,\n\t\t\t\tlastConsumedEpoch: lastReturnedRecord.LeaderEpoch,\n\t\t\t})\n\t\t}\n\n\t\tif len(t.Partitions) == 0 {\n\t\t\tbf.Topics = bf.Topics[1:]\n\t\t}\n\t}\n\n\tdrained := len(bf.Topics) == 0\n\tif drained {\n\t\ts.takeBuffered()\n\t}\n\treturn r, taken, drained\n}", "func (b *profBuf) canWriteTwoRecords(nstk1, nstk2 int) bool {\n\tbr := b.r.load()\n\tbw := b.w.load()\n\n\t// room for tag?\n\tif countSub(br.tagCount(), bw.tagCount())+len(b.tags) < 2 {\n\t\treturn false\n\t}\n\n\t// room for data?\n\tnd := countSub(br.dataCount(), bw.dataCount()) + len(b.data)\n\n\t// first record\n\twant := 2 + int(b.hdrsize) + nstk1\n\ti := int(bw.dataCount() % uint32(len(b.data)))\n\tif i+want > len(b.data) {\n\t\t// Can't fit in trailing fragment of slice.\n\t\t// Skip over that and start over at beginning of slice.\n\t\tnd -= len(b.data) - i\n\t\ti = 0\n\t}\n\ti += want\n\tnd -= want\n\n\t// second record\n\twant = 2 + int(b.hdrsize) + nstk2\n\tif i+want > len(b.data) {\n\t\t// Can't fit in trailing fragment of slice.\n\t\t// Skip over that and start over at beginning of slice.\n\t\tnd -= len(b.data) - i\n\t\ti = 0\n\t}\n\treturn nd >= want\n}", "func (w *Writer) N() int64 {\n\treturn atomic.LoadInt64(&w.n)\n}", "func (b *profBuf) canWriteRecord(nstk int) bool {\n\tbr := b.r.load()\n\tbw := b.w.load()\n\n\t// room for tag?\n\tif countSub(br.tagCount(), bw.tagCount())+len(b.tags) < 1 {\n\t\treturn false\n\t}\n\n\t// room for data?\n\tnd := countSub(br.dataCount(), bw.dataCount()) + len(b.data)\n\twant := 2 + int(b.hdrsize) + nstk\n\ti := int(bw.dataCount() % uint32(len(b.data)))\n\tif i+want > len(b.data) {\n\t\t// Can't fit in trailing fragment of slice.\n\t\t// Skip over that and start over at beginning of slice.\n\t\tnd -= len(b.data) - i\n\t}\n\treturn nd >= want\n}", "func (gp *GoPool) Add(n int) {\n\tif n < 0 {\n\t\tpanic(\"n cannot be < 0\")\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tgp.buffer <- true // take a slot in buffer channel\n\t}\n}", "func (w *NamedHistogram) Record(elapsed time.Duration) {\n\tmaxLatency := time.Duration(w.mu.current.HighestTrackableValue())\n\tif elapsed < minLatency {\n\t\telapsed = minLatency\n\t} else if elapsed > maxLatency {\n\t\telapsed = maxLatency\n\t}\n\n\tw.mu.Lock()\n\terr := w.mu.current.RecordValue(elapsed.Nanoseconds())\n\tw.mu.Unlock()\n\n\tif err != nil {\n\t\t// Note that a histogram only drops recorded values that are out of range,\n\t\t// but we clamp the latency value to the configured range to prevent such\n\t\t// drops. This code path should never happen.\n\t\tpanic(fmt.Sprintf(`%s: recording value: %s`, w.name, err))\n\t}\n}", "func WriteNShardedFiles(s beam.Scope, outputName string, n int64, lines beam.PCollection) {\n\ts = s.Scope(\"WriteNShardedFiles\")\n\n\tif n == 1 {\n\t\ttextio.Write(s, outputName, lines)\n\t\treturn\n\t}\n\tkeyed := beam.ParDo(s, &addShardKeyFn{TotalShards: n}, lines)\n\tfor i := int64(0); i < n; i++ {\n\t\tshard := beam.ParDo(s, &getShardFn{Shard: i}, keyed)\n\t\ttextio.Write(s, AddStrInPath(outputName, fmt.Sprintf(\"-%d-%d\", i+1, n)), shard)\n\t}\n}", "func RecordIoStreamBenchmark(b *testing.B, newIoStream func() rangedb.RecordIoStream) {\n\tb.Helper()\n\n\trecordTotals := []int{1, 10, 100, 1000}\n\tfor _, totalRecords := range recordTotals {\n\t\tbenchNReads(b, totalRecords, newIoStream)\n\t}\n\tfor _, totalRecords := range recordTotals {\n\t\tbenchNWrites(b, totalRecords, newIoStream)\n\t}\n}", "func (w *RecordWriter) Write(record []byte) (int, error) {\n\t_, err := w.Writer.Write([]byte{rs})\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tn, err := w.Writer.Write(record)\n\treturn n + 1, err\n}", "func (mb *MetricsBuilder) RecordMysqlBufferPoolDataPagesDataPoint(ts pcommon.Timestamp, val int64, bufferPoolDataAttributeValue AttributeBufferPoolData) {\n\tmb.metricMysqlBufferPoolDataPages.recordDataPoint(mb.startTime, ts, val, bufferPoolDataAttributeValue.String())\n}", "func (s *MQImpressionsStorage) PopNWithMetadata(n int64) ([]dtos.ImpressionQueueObject, error) {\n\tpanic(\"Not implemented for inmemory\")\n}", "func (f *FakeContext) SpanCalledN(n int) bool {\n\treturn len(f.SpanCalls) >= n\n}", "func (d *Device1Receiver) SetN(n int) {\n\td.n = n\n}", "func (mb *MetricsBuilder) RecordRedisNetOutputDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricRedisNetOutput.recordDataPoint(mb.startTime, ts, val)\n}" ]
[ "0.72103196", "0.6952949", "0.6555795", "0.63482684", "0.61493295", "0.5910554", "0.5578901", "0.55499077", "0.5537503", "0.54835016", "0.5482941", "0.5423518", "0.54116166", "0.5379708", "0.53524023", "0.5214448", "0.52071106", "0.51431227", "0.5132255", "0.51271206", "0.5103804", "0.5048629", "0.50236845", "0.49931633", "0.4978116", "0.49521008", "0.49449894", "0.4942198", "0.49296528", "0.49080396", "0.4866573", "0.48660812", "0.48617136", "0.4847573", "0.48441124", "0.48377073", "0.48277017", "0.4824613", "0.48133004", "0.48017573", "0.4777846", "0.47764584", "0.47611526", "0.47560534", "0.47503266", "0.47483653", "0.47429445", "0.4733955", "0.47327814", "0.47282094", "0.4724426", "0.4720437", "0.47108752", "0.4698616", "0.46817613", "0.4674257", "0.46614805", "0.46410617", "0.46282026", "0.462288", "0.4609554", "0.460409", "0.46018785", "0.45995232", "0.45888573", "0.4584786", "0.45782316", "0.454237", "0.45407417", "0.45177448", "0.45037627", "0.45012894", "0.44985536", "0.44982812", "0.44940636", "0.4492218", "0.44893122", "0.4478742", "0.4468722", "0.44673693", "0.44624406", "0.44454283", "0.44451582", "0.4443561", "0.44380102", "0.44341785", "0.44333953", "0.44328886", "0.44281346", "0.4423857", "0.44045934", "0.44039363", "0.44002026", "0.43978846", "0.4392688", "0.4388973", "0.43879136", "0.43860632", "0.43816194", "0.43744546" ]
0.718299
1
Records v value to count times
func (h *Histogram) record(v float64, count int) { // Scaled value to bucketize - we subtract epsilon because the interval // is open to the left ] start, end ] so when exactly on start it has // to fall on the previous bucket. TODO add boundary tests scaledVal := (v-h.Offset)/h.Divider - 0.0001 var idx int if scaledVal <= firstValue { idx = 0 } else if scaledVal > lastValue { idx = numBuckets - 1 // last bucket is for > last value } else { // else we look it up idx = lookUpIdx(int(scaledVal)) } h.Hdata[idx] += int32(count) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Counter) Record(v float64) {\n\tc.RecordN(v, 1)\n}", "func (_m *Reporter) Count(name string, value int64, 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 (h *Histogram) Record(v float64) {\n\th.RecordN(v, 1)\n}", "func (c *Counter) RecordN(v float64, n int) {\n\tisFirst := (c.Count == 0)\n\tc.Count += int64(n)\n\tif isFirst {\n\t\tc.Min = v\n\t\tc.Max = v\n\t} else if v < c.Min {\n\t\tc.Min = v\n\t} else if v > c.Max {\n\t\tc.Max = v\n\t}\n\ts := v * float64(n)\n\tc.Sum += s\n\tc.sumOfSquares += (s * s)\n}", "func Count(v Value) int {\n\tif c, ok := v.(CountedSequence); ok {\n\t\treturn c.Count()\n\t}\n\tpanic(ErrStr(ExpectedCounted, v))\n}", "func (s *plannerStats) track(result int, fmtString string, fmtVals ...interface{}) int {\n\tdesc := fmt.Sprintf(fmtString, fmtVals...)\n\ts.used = append(s.used, statItem{description: desc, value: result})\n\treturn result\n}", "func UpdateCount(key Type, val int) {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\tCountStats[key] = CountStats[key] + val\n}", "func (info Scalar) Count(e *Config, key label.Key) {\n\tdata := &Int64Data{Info: &info, key: nil}\n\te.subscribe(key, data.count)\n}", "func (t *txStats) addKV(k, v []byte) {\n\tif t.numKV == 0 {\n\t\tt.firstTime = time.Now()\n\t}\n\tt.numKV++\n\n\tvBytes := len(v)\n\tkBytes := len(k)\n\tcurBytes := uint64(kBytes + vBytes)\n\tt.lastBytes += curBytes\n\tt.totalBytes += curBytes\n\n\tswitch {\n\tcase vBytes == 0:\n\t\tt.numV0++\n\tcase vBytes < 10:\n\t\tt.numV1++\n\tcase vBytes < 100:\n\t\tt.numV10++\n\tcase vBytes < 1000:\n\t\tt.numV100++\n\tcase vBytes < 10000:\n\t\tt.numV1k++\n\tcase vBytes < 100000:\n\t\tt.numV10k++\n\tcase vBytes < 1000000:\n\t\tt.numV100k++\n\tcase vBytes < 10000000:\n\t\tt.numV1m++\n\tdefault:\n\t\tt.numV10m++\n\t}\n\n\t// Print progress?\n\tif elapsed := time.Since(t.lastTime); elapsed > time.Minute {\n\t\tmb := float64(t.lastBytes) / 1000000\n\t\tsec := elapsed.Seconds()\n\t\tthroughput := mb / sec\n\t\tdvid.Debugf(\"Transfer throughput (%s): %5.2f MB/s (%s in %4.1f seconds). Total %s\\n\", t.name, throughput, humanize.Bytes(t.lastBytes), sec, humanize.Bytes(t.totalBytes))\n\n\t\tt.lastTime = time.Now()\n\t\tt.lastBytes = 0\n\t}\n}", "func (v *Val) add(i Meta) {\n\tv.c++\n\tv.metadata[i.GetSeq()%len(v.metadata)] = i\n}", "func count(key, value string) {\n\ta := AttrCounter[key]\n\tif len(a) == 0 {\n\t\tAttrCounter[key] = append(a, value)\n\t} else {\n\t\ti := sort.SearchStrings(a, value)\n\t\tif i < len(a) && a[i] == value {\n\t\t\t// Found, thus no need to add\n\t\t\treturn\n\t\t}\n\t\tAttrCounter[key] = append(a[:i], append([]string{value}, a[i:]...)...)\n\t}\n}", "func (c CounterSnapshot) Count() int64 { return int64(c) }", "func (t *TimerSnapshot) Count() int64 { return t.histogram.Count() }", "func (kvs *keyValueServer) Count() int {\n\tkvs.cnt_signal_in <- true\n\tcnt := <-kvs.cnt_signal_out\n\treturn cnt\n}", "func WriteCount(buffer []byte, offset int, value byte, valueCount int) {\n for i := 0; i < valueCount; i++ {\n buffer[offset + i] = value\n }\n}", "func SerializeIntCountValue(value int64) string {\n\treturn fmt.Sprintf(\"count,%d\", value)\n}", "func Increment(key Type, count int) {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\n\tcountStats[key] = countStats[key] + count\n}", "func (r *R1_eg) trackValues() {\n\tr.setZeros()\n\tfor idx := range r.Register {\n\t\tr.Register[idx][idx] = 1\n\t}\n}", "func (c *CountResult) Add(k string, v int) {\n\tif c.m == nil {\n\t\tc.m = make(map[string]int)\n\t}\n\tc.m[k] = v\n}", "func (h *Histogram) RecordN(v float64, n int) {\n\th.Counter.RecordN(v, n)\n\th.record(v, n)\n}", "func Count(v uint64) (int, error) {\n\tsel := v >> 60\n\tif sel >= 16 {\n\t\treturn 0, fmt.Errorf(\"invalid selector value: %v\", sel)\n\t}\n\treturn selector[sel].n, nil\n}", "func SerializeDoubleCountValue(value float64) string {\n\treturn fmt.Sprintf(\"count,%s\", serializeFloat64(value))\n}", "func (m *MeterSnapshot) Count() int64 { return m.count }", "func (m *SearchBucket) SetCount(value *int32)() {\n m.count = value\n}", "func (m *DiscoveredSensitiveType) SetCount(value *int32)() {\n err := m.GetBackingStore().Set(\"count\", value)\n if err != nil {\n panic(err)\n }\n}", "func (cpu *CPU) v(i *Insn, v int4) (val int32) {\r\n\tif v == 3 {\r\n\t\tval = int32(i.cg2v())\r\n\t} else {\r\n\t\tval = int32(cpu.regs[v])\r\n\t}\r\n\r\n\treturn\r\n}", "func CountPrintf(f string, vals ...interface{}) {\n\tcount++\n\tfmt.Printf(fmt.Sprintf(\"%d - \", count)+f, vals...)\n}", "func IncCount(payload []byte) ([]byte, error) {\n\tgo func() {\n\t\t// Update custom metric\n\t\t_, err := wapc.HostCall(\"tarmac\", \"metrics\", \"counter\", []byte(`{\"name\":\"kv_counter_inc_called\"}`))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}()\n\n\ti := 0\n\n\t// Fetch current value from Database\n\tb, err := wapc.HostCall(\"tarmac\", \"kvstore\", \"get\", []byte(`{\"key\":\"kv_counter_example\"}`))\n\tif err == nil {\n\t\tj, err := fastjson.ParseBytes(b)\n\t\tif err != nil {\n\t\t\treturn []byte(fmt.Sprintf(`{\"status\":{\"code\":500,\"status\":\"Failed to call parse json - %s\"}}`, err)), nil\n\t\t}\n\n\t\t// Check if value is missing and return 0 if empty\n\t\tif j.GetInt(\"status\", \"code\") == 200 {\n\t\t\ts, err := base64.StdEncoding.DecodeString(string(j.GetStringBytes(\"data\")))\n\t\t\tif err == nil {\n\t\t\t\tn, err := strconv.Atoi(fmt.Sprintf(\"%s\", s))\n\t\t\t\tif err == nil {\n\t\t\t\t\ti = n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Increment Counter\n\ti += 1\n\ts := strconv.Itoa(i)\n\n\t// Store new Counter value\n\t_, err = wapc.HostCall(\"tarmac\", \"kvstore\", \"set\", []byte(fmt.Sprintf(`{\"key\":\"kv_counter_example\",\"data\":\"%s\"}`, base64.StdEncoding.EncodeToString([]byte(s)))))\n\tif err != nil {\n\t\treturn []byte(fmt.Sprintf(`{\"status\":{\"code\":500,\"status\":\"Failed to call host callback - %s\"}}`, err)), nil\n\t}\n\n\t// Return Counter value to user\n\treturn []byte(fmt.Sprintf(`{\"payload\":\"%s\",\"status\":{\"code\":200,\"status\":\"Success\"}}`, base64.StdEncoding.EncodeToString([]byte(s)))), nil\n}", "func (c *Counter) Set(v uint64) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ticksCurrent = atomic.LoadInt64(&ticks)\n\tc.v = v\n\n\t// initialize previous values to current if counter\n\t// overflows or if this is our first value\n\tif c.ticksPrevious == 0 || c.p > c.v {\n\t\tc.p = c.v\n\t\tc.ticksPrevious = c.ticksCurrent\n\t}\n}", "func PrintCount(key Type) {\n\tmutex.RLock()\n\tdefer mutex.RUnlock()\n\n\tklog.Infof(\"%s: %d\", key, CountStats[key])\n}", "func (counter *counter) addCount(n int64) {\n\tcounter.Lock()\n\tdefer counter.Unlock()\n\n\tif n <= 0 {\n\t\treturn\n\t}\n\n\t// Add the ops read and increase the count of operation.\n\t// bytes Number of ops.\n\tcounter.bytes += n\n\tcounter.ops++\n}", "func (d TestSink) Count(c *telemetry.Context, stat string, count float64) {\n\td[stat] = TestMetric{\"Count\", count, c.Tags()}\n}", "func (c *counter) increment(key string) {\n\tc.mux.Lock()\n\tfmt.Println(\"Inside increment: locked | current key value: \", c.v[key])\n\t// Lock so only one goroutine at a time can access the map c.v.\n\tc.v[key]++\n\tfmt.Println(\"Inside increment: about to unlock after incrementing\")\n\tc.mux.Unlock()\n}", "func (c CountUnit) Count(CountUnit, int8) MetricUnit {\n\tpanic(\"Cannot add another time unit\")\n}", "func (a *MovAvg) push(t time.Time, v []int) {\n\ta.q[a.w].t = t\n\tcopy(a.q[a.w].v, v)\n\tfor i := range v {\n\t\ta.sum[i] += v[i]\n\t}\n\tif a.w++; a.w == len(a.q) {\n\t\ta.w = 0\n\t}\n}", "func (self Mset) Count (value interface{}) uint64 {\n\tk, v := self.h.Get(value)\n\tif k == nil {\n\t\treturn 0\n\t} else {\n\t\treturn (*v).(uint64)\n\t}\n}", "func (c Counter) Update(token Token) {\n\tif count, ok := c.Data[token.Datum]; ok {\n\t\tc.Data[token.Datum] = count + 1\n\t} else {\n\t\tc.Data[token.Datum] = 1\n\t}\n}", "func PrintCount(key Type) {\n\tmutex.RLock()\n\tdefer mutex.RUnlock()\n\n\tklog.Infof(\"%s: %d\", key, countStats[key])\n}", "func TestGetCount_UpdatedValue(t *testing.T) {\n\tpncounter = pncounter.Increment(testNode)\n\tpncounter = pncounter.Increment(testNode)\n\tpncounter = pncounter.Increment(testNode)\n\n\texpectedCount := 3\n\tactualCount := pncounter.GetTotal()\n\n\tassert.Equal(t, expectedCount, actualCount)\n\n\tpncounter = pncounter.Clear(testNode)\n}", "func (b *baseCount) process(w word) {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tif _, ok := b.words[w]; !ok {\n\t\tb.words[w] = 0\n\t}\n\n\tb.words[w] += 1\n}", "func (c *SafeCounter) Increment(key string) {\n c.mux.Lock()\n c.v[key]++\n c.mux.Unlock()\n}", "func (c *LoggerClient) Count(name string, value int64) {\n\tc.print(\"Count\", name, value, float64(value)*c.rate)\n}", "func mapCount(itr Iterator, m *mapper) {\n\tn := 0\n\tfor k, _ := itr.Next(); k != 0; k, _ = itr.Next() {\n\t\tn++\n\t}\n\tm.emit(itr.Time(), float64(n))\n}", "func (list *APTAuditList) incrementCount() {\n\tlist.mutex.Lock()\n\tlist.count += 1\n\tlist.mutex.Unlock()\n}", "func (h HMSketch) Count(kvs map[string]string) float64 {\n\thist := h.Sketch(kvs)\n\treturn hist.Total()\n}", "func (m *Meter) Count(value int64) {\n\t_ = m.client.Count(m.name, value, m.tags)\n}", "func (g *Gauge) Record(value int64) {\n\tatomic.StoreInt64(&g.value, value)\n}", "func (vs variableSet) count() int {\n\tc := 0\n\tif vs[0] != nil {\n\t\tc++\n\t}\n\tif vs[1] != nil {\n\t\tc++\n\t}\n\tif vs[2] != nil {\n\t\tc++\n\t}\n\tif vs[3] != nil {\n\t\tc++\n\t}\n\treturn c\n}", "func (l *Layer) Count(value int) int {\n\tcount := 0\n\tfor _, b := range l.Bytes {\n\t\tif b == value {\n\t\t\tcount++\n\t\t}\n\t}\n\n\treturn count\n}", "func (c *Counter) Increment() { c.n++ }", "func Count(v interface{}) (int, error) {\n\ta := reflect.ValueOf(v)\n\tif !a.IsValid() {\n\t\treturn 0, errors.New(\"failed to get reflection value\")\n\t}\n\treturn a.NumField(), nil\n}", "func (data *Data) AddCount(cnt float64) {\n\tdata.Lock()\n\tdefer data.Unlock()\n\n\tdata.count += cnt\n\tdata.totalCount += cnt\n}", "func lisp_count(stats *Lisp_stats, key_name string, packet []byte) {\n\tif (stats == nil) {\n\t\ts, ok := lisp_decap_stats[key_name]\n\t\tif (!ok) {\n\t\t\ts = new(Lisp_stats)\n\t\t\tlisp_decap_stats[key_name] = s\n\t\t}\n\t\ts.packets += 1\n\t\ts.bytes += uint64(len(packet))\n\t\ts.last_packet = time.Now()\n\t} else {\n\t\tstats.packets += 1\n\t\tstats.bytes += uint64(len(packet))\n\t\tstats.last_packet = time.Now()\n\t}\n}", "func (obj *Count) Report() {\n\tfmt.Printf(\"Count value %d\\n\", obj.value)\n}", "func (c *Counter) Inc() {\n\tc.mux.Lock()\n\t// Lock so only one goroutine at a time can access the map c.v.\n\tc.n++\n\tc.mux.Unlock()\n}", "func (s Broker) Count(name string, value int) {\n\ts.Send(&count{Name: name, Value: value})\n}", "func (c *Client) Count(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, metricKindCount, 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 (NilTimer) Count() int64 { return 0 }", "func (s *Service) hdlVideoAuditCount() {\n\tvar (\n\t\terr error\n\t\treport *archive.Report\n\t\tctime = time.Now()\n\t\tmtime = ctime\n\t\tbs []byte\n\t)\n\tif report, err = s.arc.ReportLast(context.TODO(), archive.ReportTypeVideoAudit); err != nil {\n\t\tlog.Error(\"s.arc.ReportLast(%d) error(%v)\", archive.ReportTypeVideoAudit, err)\n\t\treturn\n\t}\n\tif report != nil && time.Now().Unix()-report.CTime.Unix() < 60*5 {\n\t\tlog.Info(\"s.arc.ReportLast(%d) 距离上一次写入还没过5分钟!\", archive.ReportTypeVideoAudit)\n\t\treturn\n\t}\n\ts.videoAuditCache.Lock()\n\tdefer s.videoAuditCache.Unlock()\n\tif bs, err = json.Marshal(s.videoAuditCache.Data); err != nil {\n\t\tlog.Error(\"json.Marshal(%v) error(%v)\", s.videoAuditCache.Data, err)\n\t\treturn\n\t}\n\tif _, err = s.arc.ReportAdd(context.TODO(), archive.ReportTypeVideoAudit, string(bs), ctime, mtime); err != nil {\n\t\tlog.Error(\"s.arc.ReportAdd(%d,%s,%v,%v) error(%v)\", archive.ReportTypeVideoAudit, string(bs), ctime, mtime, err)\n\t\treturn\n\t}\n\ts.videoAuditCache.Data = make(map[int16]map[string]int)\n}", "func (c *cpu) writev() {\n\tsp, iovcnt := popI32(c.sp)\n\tsp, iov := popPtr(sp)\n\tfd := readI32(sp)\n\tn, _, err := syscall.Syscall(syscall.SYS_WRITEV, uintptr(fd), iov, uintptr(iovcnt))\n\tif strace {\n\t\tfmt.Fprintf(os.Stderr, \"writev(%#x, %#x, %#x) %v %v\\t; %s\\n\", fd, iov, iovcnt, n, err, c.pos())\n\t}\n\tif err != 0 {\n\t\tc.setErrno(err)\n\t\twriteLong(c.rp, -1)\n\t\treturn\n\t}\n\n\twriteLong(c.rp, int64(n))\n}", "func (s *Sparse) inc(start uint, dx int32) {\n\tfor i := start + 1; i < uint(len(s.count)); i++ {\n\t\ts.count[i] += dx\n\t}\n}", "func counter(w http.ResponseWriter, r *http.Request) {\n\n\t// To avoid race conditions on concurrent requests to\n\t// increment the count variable, we must ensure that at\n\t// most one goroutine accesses the variable at a time\n\tmu.Lock()\n\tfmt.Fprintf(w, \"Count %d\\n\", count)\n\tmu.Unlock()\n}", "func Count(payload []byte) ([]byte, error) {\n\t// Fetch current value from Database\n\tb, err := wapc.HostCall(\"tarmac\", \"kvstore\", \"get\", []byte(`{\"key\":\"kv_counter_example\"}`))\n\tif err != nil {\n\t\treturn []byte(fmt.Sprintf(`{\"payload\":\"%s\",\"status\":{\"code\":200,\"status\":\"Success\"}}`, base64.StdEncoding.EncodeToString([]byte(\"0\")))), nil\n\t}\n\tj, err := fastjson.ParseBytes(b)\n\tif err != nil {\n\t\treturn []byte(fmt.Sprintf(`{\"status\":{\"code\":500,\"status\":\"Failed to call parse json - %s\"}}`, err)), nil\n\t}\n\n\t// Check if value is missing and return 0 if empty\n\tif j.GetInt(\"status\", \"code\") != 200 {\n\t\treturn []byte(fmt.Sprintf(`{\"payload\":\"%s\",\"status\":{\"code\":200,\"status\":\"Success\"}}`, base64.StdEncoding.EncodeToString([]byte(\"0\")))), nil\n\t}\n\n\t// Return KV Stored data\n\treturn []byte(fmt.Sprintf(`{\"payload\":\"%s\",\"status\":{\"code\":200,\"status\":\"Success\"}}`, j.GetStringBytes(\"data\"))), nil\n}", "func (c *Context) Inc(ctr string) {\n\tvalue := c.counters[ctr].value\n\tc.counters[ctr] = change{\n\t\tvalue: value + 1,\n\t\tlast: time.Now(),\n\t}\n}", "func (s *sizeTracker) set(key string, val int64) {\n\tif s.keyToSize == nil {\n\t\ts.keyToSize = make(map[string]int64)\n\t}\n\tprev, existed := s.keyToSize[key]\n\ts.keyToSize[key] = val\n\ts.total += val - prev\n\tif !existed {\n\t\ts.total += int64(len(key))\n\t}\n}", "func (s *TXPoolServer) increaseStats(v tc.TxnStatsType) {\n\ts.stats.Lock()\n\tdefer s.stats.Unlock()\n\ts.stats.count[v-1]++\n}", "func collectStat(ev *Event, m *map[string]int) {\n\tif m == nil {\n\t\t*m = make(map[string]int)\n\t}\n\t// stats to map\n\tif _, ok := (*m)[ev.Pid]; !ok {\n\t\t(*m)[uniquePid]++\n\t}\n\t(*m)[ev.Pid]++\n\n\t(*m)[ev.UtmM]++\n\t(*m)[ev.UtmS]++\n\n\tif _, ok := (*m)[genKey(ev.Pid, ev.UtmM)]; !ok {\n\t\t(*m)[genKey(uniquePidsUtmm, ev.UtmM)]++\n\t}\n\t(*m)[genKey(ev.Pid, ev.UtmM)]++\n\n\tif _, ok := (*m)[genKey(ev.Pid, ev.UtmS)]; !ok {\n\t\t(*m)[genKey(uniquePidsUtms, ev.UtmS)]++\n\t}\n\t(*m)[genKey(ev.Pid, ev.UtmS)]++\n\n\t(*m)[genKey(ev.UtmM, ev.UtmS)]++\n\n\tif _, ok := (*m)[genKey(ev.Pid, ev.UtmM, ev.UtmS)]; !ok {\n\t\t(*m)[genKey(uniquePidsUtms, ev.UtmM, ev.UtmS)]++\n\t}\n\t(*m)[genKey(ev.Pid, ev.UtmM, ev.UtmS)]++\n\n\t(*m)[evNumberKey]++\n\n}", "func (l *Listener) Count(name string, value float64, timestamp time.Time, endpoint string) {\n\tif len(endpoint) == 0 {\n\t\tlog.Println(\"Error - internal metrics referenced empty endpoint\")\n\t\treturn\n\t}\n\n\tl.ch <- Metric{\n\t\tKey: NewMetricKeyForApiCall(name, timestamp, endpoint),\n\t\tStats: awscsmmetrics.NewStatisticSet(value),\n\t}\n}", "func (c *Counter) Count() int64 { return c.count }", "func (b *BrainFuck) inc(v int) {\n\tb.memory.cell[b.cur()] = (b.memory.cell[b.cur()] + v) % 255\n}", "func (d *distance) add(v int) {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\td.v += v\n}", "func doubleCount(nc *NuclCov, codonPairArray []CodonPair) {\n\tfor _, cp := range codonPairArray {\n\t\ta := cp.A.Seq[2]\n\t\tb := cp.B.Seq[2]\n\t\tnc.Add(a, b)\n\t}\n}", "func (l *TestLog) V(int) InfoWriter {\n\treturn &TestLog{}\n}", "func (t *limiter) Increment(count int) {\n\tt.count += int64(count)\n}", "func (m *BarTimeRangeMutation) AddCount(i int) {\n\tif m.addcount != nil {\n\t\t*m.addcount += i\n\t} else {\n\t\tm.addcount = &i\n\t}\n}", "func testCountN(n int, hm HashMaper) {\n\tfor i := 0; i < n; i++ {\n\t\thm.Count()\n\t}\n}", "func handleCount(args ...string) (string, error) {\n\tval := args[0]\n\n\tcnt, err := GetCurrentStore().Count(val)\n\treturn fmt.Sprintf(\"%d\", cnt), err\n}", "func (kv *KV) Count() (i int) {\n\tkv.db.View(func(tx *buntdb.Tx) error {\n\t\terr := tx.Ascend(\"\", func(key, value string) bool {\n\t\t\ti++\n\t\t\treturn true\n\t\t})\n\t\treturn err\n\t})\n\treturn\n}", "func (s Client) Count(key string, count int32) error {\n\treturn s.sendStat(&Stat{Kind: Count, Count: count, Key: key})\n}", "func recordUptime() {\n\tfor range time.Tick(time.Second) {\n\t\tuptime.WithLabelValues().Inc()\n\t}\n}", "func (s *StatsdClient) Count(name string, value int64, tags []string, rate float64) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tif len(tags) == 0 {\n\t\ts.counts[name] += value\n\t}\n\n\tfor _, tag := range tags {\n\t\ts.counts[name+\":\"+tag] += value\n\t}\n\treturn nil\n}", "func (e *RuntimeStat) Record(d time.Duration, rowNum int) {\n\tatomic.AddInt32(&e.loop, 1)\n\tatomic.AddInt64(&e.consume, int64(d))\n\tatomic.AddInt64(&e.rows, int64(rowNum))\n}", "func (c *Count) Increment(by int64) {\n\tc.µ.Lock()\n\tc.val += by\n\tc.µ.Unlock()\n}", "func (c *Counter) Stat(name string, value int64) {\n\tif !c.stopped {\n\t\tc.recordChannel <- countRecord{name, value}\n\t}\n}", "func clv(cpu *CPU, step *runStep) {\n\tcpu.v = 0\n}", "func (s *Basememcached_protocolListener) EnterStatistic_value(ctx *Statistic_valueContext) {}", "func main() {\n\tvar wg sync.WaitGroup\n\n\tincrementer := 0\n\tgs := 100\n\twg.Add(gs)\n\tvar m sync.Mutex\n\n\tfor i := 0; i < gs; i++ {\n\t\tgo func() {\n\t\t\tm.Lock()\n\t\t\tv := incrementer\n\t\t\truntime.Gosched()\n\t\t\tv++\n\t\t\tincrementer = v\n\t\t\tfmt.Println(incrementer)\n\t\t\tm.Unlock()\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\tfmt.Println(\"end value:\", incrementer)\n}", "func countingValleys(n int32, s string) int32 {\n\n l, v := 0, 0\n s = strings.ToLower(s)\n for _, r := range s {\n\n if r == 'u' {\n if l < 0 && l+1 == 0 {\n v++\n }\n l++\n\n } else {\n l--\n }\n }\n return int32(v)\n}", "func (n *namest) updateCount(db *sql.DB) error {\n\t_, err :=\n\t\tdb.Exec(\"UPDATE names SET count = count + 1 WHERE name=$1\",\n\t\t\tn.Name)\n\n\treturn err\n}", "func createFrequencyTable(bytes *vector.Vector) *dictionary.Dictionary {\n\tdict := dictionary.New()\n\tfor i := 0; i < bytes.Size(); i++ {\n\t\tbyt := bytes.MustGet(i)\n\n\t\tif frequency, exists := dict.Get(byt); !exists {\n\t\t\tdict.Set(byt, 1)\n\t\t} else {\n\t\t\tdict.Set(byt, frequency.(int)+1)\n\t\t}\n\t}\n\n\treturn dict\n}", "func (n *Node) Count(count *int) {\n\t*count = *count + len(n.values)\n\n\tif n.children[0] != nil {\n\t\tfor i, _ := range n.children {\n\t\t\tn.children[i].Count(count)\n\t\t}\n\t}\n}", "func (f *Flash) Count() int {\n\treturn len(f.v)\n}", "func (m *metricBigipVirtualServerRequestCount) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}", "func countingWrite(ctx context.Context, ch chan<- []any, counter *uint32, values ...any) bool {\n\tselect {\n\tcase ch <- values:\n\t\t*counter++\n\t\treturn true\n\n\tcase <-ctx.Done():\n\t\treturn false\n\t}\n}", "func getTotalCount(a map[string]int) int {\n\tvar result int\n\tfor _, v := range a {\n\t\tresult += v\n\t}\n\treturn result\n}", "func (c *Client) Increment(k uint64, v float64, t time.Duration) error {\n\treturn types.WriteMessage(c.s, types.IncrementMessage{\n\t\tKey: k,\n\t\tVal: v,\n\t\tTTE: uint32(time.Now().Add(t).Unix()),\n\t})\n}", "func (c *PCPCounterVector) Up(instance string) { c.MustInc(1, instance) }", "func (gdt *Array) Count(value Variant) Int {\n\targ0 := gdt.getBase()\n\targ1 := value.getBase()\n\n\tret := C.go_godot_array_count(GDNative.api, arg0, arg1)\n\n\treturn Int(ret)\n}", "func (this *Tuple) Count(item interface{}, start int) int {\n\tctr := 0\n\tfor i := start; i < this.Len(); i++ {\n\t\tif TupleElemEq(this.Get(i), item) {\n\t\t\tctr += 1\n\t\t}\n\t}\n\treturn ctr\n}", "func counter(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tfmt.Fprintf(w, \"Count %d\\n\", count)\n\tmu.Unlock()\n}" ]
[ "0.622321", "0.590443", "0.58357596", "0.5790637", "0.5759379", "0.5621582", "0.5616382", "0.5555392", "0.55514765", "0.5543612", "0.55361414", "0.5502995", "0.54776734", "0.5432605", "0.53914356", "0.5390474", "0.53617525", "0.53468645", "0.5328528", "0.53281254", "0.5304133", "0.5300858", "0.5296023", "0.5289654", "0.52873147", "0.52530825", "0.5246894", "0.5244104", "0.5231619", "0.52236205", "0.5219485", "0.5200657", "0.51979965", "0.5193175", "0.5189837", "0.51877236", "0.5185858", "0.51671404", "0.51658165", "0.51565826", "0.51381266", "0.512465", "0.5116809", "0.5115611", "0.5108574", "0.5100307", "0.50845426", "0.50749934", "0.5068696", "0.50605273", "0.5057437", "0.50518197", "0.5043214", "0.5030219", "0.50289047", "0.50224066", "0.50108534", "0.5010064", "0.5008533", "0.49992606", "0.4996363", "0.49912575", "0.49899724", "0.49886537", "0.49885964", "0.49813738", "0.49736768", "0.497099", "0.49643993", "0.4959198", "0.49569792", "0.49520683", "0.49509522", "0.49468717", "0.4926839", "0.4923745", "0.4920594", "0.49197748", "0.49153855", "0.48955706", "0.48913443", "0.48912784", "0.48898274", "0.48887596", "0.48865238", "0.488524", "0.48852253", "0.4879605", "0.48786193", "0.48760915", "0.48760542", "0.48703212", "0.48679802", "0.4867827", "0.48663828", "0.4865045", "0.48644787", "0.4860089", "0.48489788", "0.48467273" ]
0.6377869
0
CalcPercentile returns the value for an input percentile e.g. for 90. as input returns an estimate of the original value threshold where 90.0% of the data is below said threshold. with 3 data points 10, 20, 30; p0p33.33 == 10, p 66.666 = 20, p100 = 30 p33.333 p66.666 = linear between 10 and 20; so p50 = 15 TODO: consider spreading the count of the bucket evenly from start to end so the % grows by at least to 1/N on start of range, and for last range when start == end we should get to that % faster
func (e *HistogramData) CalcPercentile(percentile float64) float64 { if len(e.Data) == 0 { log.Errf("Unexpected call to CalcPercentile(%g) with no data", percentile) return 0 } if percentile >= 100 { return e.Max } // We assume Min is at least a single point so at least covers 1/Count % pp := 100. / float64(e.Count) // previous percentile if percentile <= pp { return e.Min } for _, cur := range e.Data { if percentile <= cur.Percent { return cur.Start + (percentile-pp)/(cur.Percent-pp)*(cur.End-cur.Start) } pp = cur.Percent } return e.Max // not reached }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *PCPHistogram) Percentile(p float64) int64 { return h.h.ValueAtQuantile(p) }", "func Percentile(input []float64, percent float64) float64 {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\treturn PercentileOfSorted(SortCopy(input), percent)\n}", "func (c *Collector) Percentile(percent float64) float64 {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttargetCount := int(percent * float64(c.Count) / 100)\n\n\tcount := 0\n\tfor _, b := range c.Buckets {\n\t\tcount += b.Count\n\t\tif count >= targetCount {\n\t\t\treturn b.Max\n\t\t}\n\t}\n\n\treturn c.Max\n}", "func computePercentile(array []float64, targetPercentile int) float64 {\n\tif len(array) == 0 {\n\t\tpanic(\"Cannot compute the percentile of an empty array\")\n\t}\n\tsort.Float64s(array)\n\tif targetPercentile == 100 {\n\t\treturn array[len(array)-1]\n\t}\n\tindexAsFloat, fractional := math.Modf((float64(len(array)) - 1.0) * (0.01 * float64(targetPercentile)))\n\tindex := int(indexAsFloat)\n\tif len(array) == index+1 {\n\t\treturn array[index]\n\t}\n\treturn array[index]*(1-fractional) + array[index+1]*fractional\n}", "func (t *TimerSnapshot) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func Percentile(k float64, arrays ...float64) (float64, error) {\n\n\t// Check if k is a Non Numeric\n\tif math.IsNaN(k) {\n\t\treturn 0.0, errors.New(\"#VALUE!\t-\tOccurred because the supplied value of k is non-numeric\")\n\t}\n\n\tif len(arrays) == 0 || (k < 0 || k > 100) {\n\t\treturn 0.0, errors.New(\"#NUM!\t-\tOccurred because the supplied value of k is less than 0 or greater than 100 or the array is empty\")\n\t}\n\n\t// Reorder them from the smallest to the largest\n\tsort.Sort(SmallNums(arrays))\n\n\t// n = \\left \\lceil \\frac{P}{100} \\times N \\right \\rceil\n\n\tn := (k / 100) * float64(len(arrays))\n\n\tmathlib.Round(n, 0)\n\n\treturn arrays[int(n)], nil\n}", "func percentile(orderedObservations []float64, l int, p float64) float64 {\n\treturn orderedObservations[int(p*float64(l))]\n}", "func (s Sample) Percentile(pctile float64) float64 {\n\tif len(s.Xs) == 0 {\n\t\treturn math.NaN()\n\t} else if pctile <= 0 {\n\t\tmin, _ := s.Bounds()\n\t\treturn min\n\t} else if pctile >= 1 {\n\t\t_, max := s.Bounds()\n\t\treturn max\n\t}\n\n\tif !s.Sorted {\n\t\ts = *s.Copy().Sort()\n\t}\n\n\tN := float64(len(s.Xs))\n\tn := 1/3.0 + pctile*(N+1/3.0) // R8\n\tkf, frac := math.Modf(n)\n\tk := int(kf)\n\tif k <= 0 {\n\t\treturn s.Xs[0]\n\t} else if k >= len(s.Xs) {\n\t\treturn s.Xs[len(s.Xs)-1]\n\t}\n\treturn s.Xs[k-1] + frac*(s.Xs[k]-s.Xs[k-1])\n}", "func percentile(data []float64) (p25 float64, p75 float64) {\n\n\tN := float64(len(data))\n\tloc25 := int(.25 * N)\n\tloc75 := int(.75 * N)\n\tsafeData := make([]float64, len(data))\n\tcopy(safeData, data)\n\tsort.Float64s(safeData)\n\n\treturn safeData[loc25], safeData[loc75]\n}", "func (preferences *ProductPreferences) GetPercentile(val float32) float32 {\r\n\t//TODO: change to bin search.\r\n\tfor i := len(preferences.Percentiles) - 1; i >= 0; i-- {\r\n\t\tif val > preferences.Percentiles[i] {\r\n\t\t\treturn float32(i+1) / float32(DistributionSize+1)\r\n\t\t}\r\n\t}\r\n\treturn 0\r\n}", "func (t *StandardTimer) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func (NilTimer) Percentile(p float64) float64 { return 0.0 }", "func (s *UniformSample) Percentile(p float64) float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentile(s.values, p)\n}", "func PercentileOfSorted(sortedInput []float64, percent float64) float64 {\n\tindex := (percent / 100.0) * float64(len(sortedInput))\n\tpercentile := float64(0)\n\ti := int(math.RoundToEven(index))\n\tif index == float64(int64(index)) {\n\t\tpercentile = (sortedInput[i-1] + sortedInput[i]) / 2.0\n\t} else {\n\t\tpercentile = sortedInput[i-1]\n\t}\n\n\treturn percentile\n}", "func guessPercentile(curValue uint64, newValue, count uint64, perc float32) uint64 {\n\tinertness := float64(count) / iterationsRequiredPerSecond\n\n\trequireGreater := rand.Float32() > perc\n\n\tif newValue > curValue {\n\t\tif requireGreater {\n\t\t\treturn curValue\n\t\t}\n\t} else {\n\t\tif !requireGreater {\n\t\t\treturn curValue\n\t\t}\n\t}\n\n\tif requireGreater {\n\t\tinertness *= float64(perc)\n\t} else {\n\t\tinertness *= float64(1 - perc)\n\t}\n\tupdatedValue := uint64((float64(curValue)*inertness + float64(newValue)) / (inertness + 1))\n\treturn updatedValue\n}", "func percentile(dps Series, args ...float64) (a float64) {\n\tp := args[0]\n\tvar x []float64\n\tfor _, v := range dps {\n\t\tx = append(x, float64(v))\n\t}\n\tsort.Float64s(x)\n\tif p <= 0 {\n\t\treturn x[0]\n\t}\n\tif p >= 1 {\n\t\treturn x[len(x)-1]\n\t}\n\ti := p * float64(len(x)-1)\n\ti = math.Ceil(i)\n\treturn x[int(i)]\n}", "func (m *MockHistogram) Percentile(percentile float64) float64 {\n\targs := m.Called(percentile)\n\treturn args.Get(0).(float64)\n}", "func (ms SummaryValueAtPercentile) Percentile() float64 {\n\treturn (*ms.orig).Percentile\n}", "func Percentile(ts []Transaction, percent float64) float64 {\n\tSort(&ts)\n\ti := int(math.Floor(float64(len(ts)) * percent))\n\tvalue := ts[i].amount\n\treturn value\n}", "func (e *HistogramData) CalcPercentiles(percentiles []float64) *HistogramData {\n\tif e.Count == 0 {\n\t\treturn e\n\t}\n\tfor _, p := range percentiles {\n\t\te.Percentiles = append(e.Percentiles, Percentile{p, e.CalcPercentile(p)})\n\t}\n\treturn e\n}", "func TestPercentile(t *testing.T) {\n\ttables := []struct{\n\t\tvals []int // input slice\n\t\tpercentile float64 // percentile value\n\t}{\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t0},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t10},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t20},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t30},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t40},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t50},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t60},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t70},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t80},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t90},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t100},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t92},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t95},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t99},\n\t}\n\n\tfor _, tt := range tables {\n\t\tperc, _ := Percentile(tt.vals, tt.percentile)\n\t\tfmt.Println(perc)\n\t}\n}", "func ReducePercentile(percentile float64) ReduceFunc {\n\treturn func(values []interface{}) interface{} {\n\t\tvar allValues []float64\n\n\t\tfor _, v := range values {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvals := v.([]interface{})\n\t\t\tfor _, v := range vals {\n\t\t\t\tswitch v.(type) {\n\t\t\t\tcase int64:\n\t\t\t\t\tallValues = append(allValues, float64(v.(int64)))\n\t\t\t\tcase float64:\n\t\t\t\t\tallValues = append(allValues, v.(float64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsort.Float64s(allValues)\n\t\tlength := len(allValues)\n\t\tindex := int(math.Floor(float64(length)*percentile/100.0+0.5)) - 1\n\n\t\tif index < 0 || index >= len(allValues) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn allValues[index]\n\t}\n}", "func (b BundledStates) Percentile(t time.Time, percentile int) time.Duration {\n\tif percentile > 100 || percentile <= 0 {\n\t\tpanic(fmt.Errorf(\"percentile %d is out of scope\", percentile))\n\t}\n\n\tages := []time.Duration{}\n\tfor _, age := range b.ages(t) {\n\t\tages = append(ages, age)\n\t}\n\n\tif len(ages) == 0 {\n\t\treturn 0\n\t}\n\n\tsort.Sort(ByDuration(ages))\n\n\tindex := int(math.Ceil(float64(percentile)*float64(len(ages))/100) - 1)\n\tif index >= len(ages) {\n\t\tpanic(fmt.Errorf(\"Index is out of range: %d/%d\", index, len(ages)))\n\t}\n\treturn ages[index]\n}", "func (fn *formulaFuncs) PERCENTILE(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"PERCENTILE requires 2 arguments\")\n\t}\n\tarray := argsList.Front().Value.(formulaArg).ToList()\n\tk := argsList.Back().Value.(formulaArg).ToNumber()\n\tif k.Type != ArgNumber {\n\t\treturn k\n\t}\n\tif k.Number < 0 || k.Number > 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNA, formulaErrorNA)\n\t}\n\tvar numbers []float64\n\tfor _, arg := range array {\n\t\tif arg.Type == ArgError {\n\t\t\treturn arg\n\t\t}\n\t\tif arg.Type == ArgNumber {\n\t\t\tnumbers = append(numbers, arg.Number)\n\t\t}\n\t}\n\tcnt := len(numbers)\n\tsort.Float64s(numbers)\n\tidx := k.Number * (float64(cnt) - 1)\n\tbase := math.Floor(idx)\n\tif idx == base {\n\t\treturn newNumberFormulaArg(numbers[int(idx)])\n\t}\n\tnext := base + 1\n\tproportion := math.Nextafter(idx, idx) - base\n\treturn newNumberFormulaArg(numbers[int(base)] + ((numbers[int(next)] - numbers[int(base)]) * proportion))\n}", "func (t *TimerSnapshot) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func Percentile(by []string, percentile float64, input []*oproto.ValueStream) []*oproto.ValueStream {\n\toutput := []*oproto.ValueStream{{Variable: input[0].Variable}}\n\treturn output\n}", "func (t *StandardTimer) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func (s *UniformSample) Percentiles(ps []float64) []float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentiles(s.values, ps)\n}", "func (NilTimer) Percentiles(ps []float64) []float64 {\n\treturn make([]float64, len(ps))\n}", "func (res *Results) CalculatePct(pct int) float64 {\n slice := res.copyTook()\n\n l := len(slice)\n switch l {\n case 0:\n return float64(0)\n case 1:\n return slice[0]\n case 2:\n return slice[1]\n }\n\n index := int(math.Floor(((float64(l)/100)*float64(pct))+0.5) - 1)\n return slice[index]\n}", "func (s *ModelLatencyThreshold) SetPercentile(v string) *ModelLatencyThreshold {\n\ts.Percentile = &v\n\treturn s\n}", "func (ms SummaryValueAtPercentile) SetPercentile(v float64) {\n\t(*ms.orig).Percentile = v\n}", "func Quantile(p float64, xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\tpanic(\"Quantile() second argument may not be empty\")\n\t}\n\tif len(xs) == 1 {\n\t\treturn xs[0]\n\t}\n\n\t// log.Printf(\"xs = %#v\\n\", xs)\n\t// log.Printf(\"p = %.2f\\n\", p)\n\tn := float64(len(xs))\n\t// log.Printf(\"n = %.2f\\n\", n)\n\n\t// parameters for \"Definition 8\" (which the paper recommends)\n\tm := (p + 1) / 3\n\t// log.Printf(\"m = %.2f\\n\", m)\n\n\t// equations based on the parameters\n\tj := math.Floor(p*n + m)\n\tg := p*n + m - j\n\tgamma := g\n\t// log.Printf(\"j = %.2f\\n\", j)\n\t// log.Printf(\"g = %.2f\\n\", g)\n\n\t// j is 1-based but xs is 0-based, so lookups subtract 1\n\tquantile := (1-gamma)*xs[int(j)-1] + gamma*xs[int(j)]\n\t// log.Printf(\"quantile = %.2f\\n\\n\", quantile)\n\treturn quantile\n}", "func (r RetCalc) PercentileIncome(percentile float64) float64 {\n\tincomes := r.RunIncomes()\n\tix := int(percentile * float64(r.N))\n\treturn incomes[ix]\n}", "func NewPercentiles(label string, values []float64) *Percentiles {\n\tvalues = append(values[:0:0], values...)\n\tsort.Float64s(values)\n\n\tpoints := make([]Point, 0, len(values))\n\n\tmultiplier := 1 / float64(len(values)+1)\n\tfor i, v := range values {\n\t\tvar p Point\n\t\tp.X = float64(i+1) * multiplier\n\t\tp.Y = v\n\t\tpoints = append(points, p)\n\t}\n\n\treturn &Percentiles{\n\t\tLabel: label,\n\t\tData: points,\n\t}\n}", "func QuartileRange(values []float64) (float64, float64) {\n\tsorted := sortFloat64s(values)\n\treturn percentile_(sorted, 25.0), percentile_(sorted, 75.0)\n}", "func (p Pareto) Quantile(prob float64) float64 {\n\tif prob < 0 || 1 < prob {\n\t\tpanic(badPercentile)\n\t}\n\treturn p.Xm / math.Pow(1-prob, 1/p.Alpha)\n}", "func (h *Histogram) Quantile(q float64) (float64, error) {\n\thist := testutil.Histogram{\n\t\t&dto.Histogram{\n\t\t\tBucket: []*dto.Bucket{},\n\t\t},\n\t}\n\n\tfor k, v := range h.Buckets {\n\t\tupper, err := strconv.ParseFloat(k, 64)\n\t\tif err != nil {\n\t\t\treturn math.MaxFloat64, err\n\t\t}\n\n\t\tcumulativeCount := uint64(v)\n\t\thist.Bucket = append(hist.Bucket, &dto.Bucket{\n\t\t\tCumulativeCount: &cumulativeCount,\n\t\t\tUpperBound: &upper,\n\t\t})\n\t}\n\n\t// hist.Quantile expected a slice of Buckets ordered by UpperBound\n\tsort.Slice(hist.Bucket, func(i, j int) bool {\n\t\treturn *hist.Bucket[i].UpperBound < *hist.Bucket[j].UpperBound\n\t})\n\n\treturn hist.Quantile(q), nil\n}", "func quantile(vals []float64, q float64) float64 {\n\tlength := len(vals)\n\tif length == 0 {\n\t\treturn math.NaN()\n\t}\n\tindex := int(q * float64(length-1))\n\treturn vals[index]\n}", "func PERCENTILEOPT(wrapped interface{}, percentile interface{}) Expr {\n\tvar expr Expr\n\tswitch t := wrapped.(type) {\n\tcase *ptileOptimized:\n\t\texpr = &t.ptile\n\tdefault:\n\t\texpr = wrapped.(*ptile)\n\t}\n\treturn &ptileOptimized{Wrapped: expr, ptile: *expr.(*ptile), Percentile: exprFor(percentile)}\n}", "func PERCENTILEOPT(wrapped interface{}, percentile interface{}) Expr {\n\tvar expr Expr\n\tswitch t := wrapped.(type) {\n\tcase *ptileOptimized:\n\t\texpr = t.wrapped\n\tdefault:\n\t\texpr = wrapped.(*ptile)\n\t}\n\treturn &ptileOptimized{Wrapped: expr, wrapped: expr.(*ptile), Percentile: exprFor(percentile)}\n}", "func (g GumbelRight) Quantile(p float64) float64 {\n\tif p < 0 || 1 < p {\n\t\tpanic(badPercentile)\n\t}\n\treturn g.Mu - g.Beta*math.Log(-math.Log(p))\n}", "func (digest *MergingDigest) Quantile(q float64) float64 {\n\tdigest.Compress()\n\tif len(digest.summary) == 0 || q < 0.0 || q > 1.0 {\n\t\treturn math.NaN()\n\t} else if len(digest.summary) == 1 {\n\t\treturn digest.summary[0].Mean\n\t}\n\tindex := float64(digest.count) * q\n\tsum := int64(1)\n\taMean := digest.summary[0].Mean\n\taIndex := float64(0)\n\tbMean := digest.summary[0].Mean\n\tbIndex := float64(sum) + float64(digest.summary[0].Count-1)*0.5\n\tfor i := 1; i < len(digest.summary); i++ {\n\t\tif index <= bIndex {\n\t\t\tbreak\n\t\t}\n\t\tsum += digest.summary[i-1].Count\n\t\taMean = bMean\n\t\taIndex = bIndex\n\t\tbMean = digest.summary[i].Mean\n\t\tbIndex = float64(sum) + float64(digest.summary[i].Count-1)*0.5\n\t}\n\tp := (index - aIndex) / (bIndex - aIndex)\n\treturn aMean*(1.0-p) + bMean*p\n}", "func TestGetCPUPercent(t *testing.T) {\n\t// setup the faking of `cpu.Percent()`\n\toldcpuPercent := cpuPercent\n\tcpuPercent = func(interval time.Duration, percpu bool) ([]float64, error) {\n\t\tret := []float64{100}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := 100\n\tactual, err := getCPUPercent()\n\n\tassert.NoError(t, err, \"`getCPUPercent()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUPercent` should be equal to --> 100\")\n\n\t// teardown\n\tcpuPercent = oldcpuPercent\n}", "func ceilPercent(v uint64, t uint64) float64 {\n\t// Prevent division by 0 to occur\n\tif t == 0 {\n\t\treturn 0.0\n\t}\n\tvar v1i uint64\n\tv1i = v * 100 / t\n\tvar v1f float64\n\tv1f = float64(v) * 100.0 / float64(t)\n\tvar v2f float64\n\tv2f = float64(v1i)\n\tif v2f-1 < v1f && v1f <= v2f+1 {\n\t\taddF := 0.0\n\t\tif v2f < v1f {\n\t\t\taddF = 1.0\n\t\t}\n\t\tv1f = v2f + addF\n\t}\n\treturn v1f\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}", "func quantile(q float64, values vector.HeapByMaxValue) float64 {\n\tif len(values) == 0 {\n\t\treturn math.NaN()\n\t}\n\tif q < 0 {\n\t\treturn math.Inf(-1)\n\t}\n\tif q > 1 {\n\t\treturn math.Inf(+1)\n\t}\n\tsort.Sort(values)\n\n\tn := float64(len(values))\n\t// When the quantile lies between two samples,\n\t// we use a weighted average of the two samples.\n\trank := q * (n - 1)\n\n\tlowerIndex := math.Max(0, math.Floor(rank))\n\tupperIndex := math.Min(n-1, lowerIndex+1)\n\n\tweight := rank - math.Floor(rank)\n\treturn values[int(lowerIndex)].V*(1-weight) + values[int(upperIndex)].V*weight\n}", "func QuantileCI(n int, q, confidence float64) QuantileCIResult {\n\tconst debug = false\n\n\tvar res QuantileCIResult\n\tres.N = n\n\tres.Quantile = q\n\n\tif confidence >= 1 {\n\t\tres.Confidence = 1\n\t\tres.LoOrder = 0\n\t\tres.HiOrder = n + 1\n\t\treturn res\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"QuantileCI(%v, %v, %v)\\n\", n, q, confidence)\n\t}\n\n\t// There's a dearth of good information online about how to\n\t// compute this, especially in corner cases. Some useful\n\t// online resources:\n\t//\n\t// https://online.stat.psu.edu/stat415/book/export/html/835 -\n\t// The concept of intervals, some worked examples.\n\t//\n\t// http://www.milefoot.com/math/stat/ci-medians.htm - Good\n\t// walk through of summing up binomial probabilities,\n\t// continuity correction for the normal approximation.\n\n\t// The sampling distribution for order statistics is the\n\t// binomial distribution. In this distribution, k is how many\n\t// samples come before the population median; or,\n\t// alternatively, an index into the intervals between samples\n\t// (where 0 is the interval from -∞ to the first sample).\n\t// Hence, PMF(k) gives the probability that the population\n\t// median falls in interval k, or between s.Xs[k-1] and\n\t// s.Xs[k].\n\tsamp := BinomialDist{N: n, P: q}\n\n\t// l and r are the left and right order statistics of the\n\t// confidence interval.\n\tvar l, r int\n\tif samp.N <= quantileCIApproxThreshold {\n\t\tif debug {\n\t\t\tfor i := 0; i <= samp.N; i++ {\n\t\t\t\tfmt.Printf(\" %d | %v\\n\", i, samp.PMF(float64(i)))\n\t\t\t}\n\t\t}\n\n\t\t// Start with the mode and accumulate probabilities in\n\t\t// decreasing order until we pass the confidence\n\t\t// level. This uses the fact that the probabilities\n\t\t// decrease monotonically as you move out from the\n\t\t// mode.\n\t\t//\n\t\t// The binomial distribution can be have equal modes.\n\t\t// Since we want to left-bias our result, we start\n\t\t// with the lower of the two.\n\t\tx := int(math.Ceil(float64(samp.N+1)*samp.P) - 1)\n\t\tif samp.P == 0 { // Special case of the mode\n\t\t\tx = 0\n\t\t}\n\t\taccum := samp.PMF(float64(x))\n\t\tif debug {\n\t\t\tfmt.Printf(\" start %d => %v\\n\", x, accum)\n\t\t}\n\n\t\t// Compute the neighboring probabilities so we can\n\t\t// incrementally add and update them. [l, r) is the\n\t\t// interval we've summed.\n\t\tl, r = x, x+1\n\t\tlp, rp := samp.PMF(float64(l-1)), samp.PMF(float64(r))\n\t\t// If the binomial distribution has two modes, then\n\t\t// our initial selection is ambiguous.\n\t\tres.Ambiguous = rp == accum\n\n\t\t// Accumulate probabilities to reach the desired\n\t\t// confidence level. We defend against accumulation\n\t\t// errors by stopping if there's no more to\n\t\t// accumulate.\n\t\t//\n\t\t// For the particular case of q=0.5, the distribution\n\t\t// is symmetric and we could just use InvCDF like we\n\t\t// do in the normal approximation. But that doesn't\n\t\t// generalize to other quantiles, and InvCDF isn't\n\t\t// particularly efficient on the binomial distribution\n\t\t// anyway.\n\t\tfor accum < confidence && (lp > 0 || rp > 0) {\n\t\t\tres.Ambiguous = lp == rp\n\t\t\tif lp >= rp { // Left-bias\n\t\t\t\taccum += lp\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Printf(\" +left %d => %v\\n\", l-1, accum)\n\t\t\t\t}\n\t\t\t\tl--\n\t\t\t\tlp = samp.PMF(float64(l - 1))\n\t\t\t} else {\n\t\t\t\taccum += rp\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Printf(\" +right %d => %v\\n\", r, accum)\n\t\t\t\t}\n\t\t\t\tr++\n\t\t\t\trp = samp.PMF(float64(r))\n\t\t\t}\n\t\t}\n\t\tres.Confidence = accum\n\n\t\tif debug {\n\t\t\tfmt.Printf(\" final [%d,%d) => %v (ambiguous %v)\\n\", l, r, accum, res.Ambiguous)\n\t\t}\n\t} else {\n\t\t// Use the normal approximation.\n\t\tnorm := samp.NormalApprox()\n\t\talpha := (1 - confidence) / 2\n\n\t\t// Find the center \"confidence\" weight of the\n\t\t// distribution.\n\t\tl1 := norm.InvCDF(alpha)\n\t\tr1 := 2*norm.Mu - l1 // Symmetric around mean.\n\n\t\t// Find the band of the discrete binomial distribution\n\t\t// containing [l1, r1]. Because of the continuity\n\t\t// correction, point k in the binomial distribution\n\t\t// corresponds to band [k-0.5, k+0.5] in the normal\n\t\t// distribution. Hence, we round out to ℕ + 0.5\n\t\t// boundaries and then recover k.\n\t\t//\n\t\t// For example, let's say mu=2 and confidence is\n\t\t// really low. If [l1, r1] is [1.9, 2.1], that rounds\n\t\t// out to [1.5, 2.5], which is the band [2, 3) in the\n\t\t// binomial distribution. But if [l1, r1] is [1.4,\n\t\t// 2.6], that rounds out to [0.5, 3.5], which is the\n\t\t// band [1, 4) in the binomial distribution.\n\t\tfloorInt := func(x float64) int {\n\t\t\t// int(x) truncates toward 0, so floor first.\n\t\t\treturn int(math.Floor(x))\n\t\t}\n\t\tl = floorInt(math.Floor(l1-0.5)+0.5) + 1\n\t\tr = floorInt(math.Ceil(r1-0.5)+0.5) + 1\n\n\t\tif debug {\n\t\t\tfmt.Printf(\" [%v,%v] rounds to [%v,%v]\\n\", l1, r1, l, r)\n\t\t}\n\n\t\t// The actual confidence on the binomial\n\t\t// distribution is\n\t\t//\n\t\t// Pr[l <= X < r] = Pr[X <= r - 1] - Pr[X <= l - 1]\n\t\t//\n\t\t// To translate this into the normal\n\t\t// approximation, we add 0.5 to each bound for\n\t\t// the continuity correction.\n\t\tcdf := func(l, r int) float64 {\n\t\t\treturn norm.CDF(float64(r)-0.5) - norm.CDF(float64(l)-0.5)\n\t\t}\n\t\tres.Confidence = cdf(l, r)\n\t\t// The computed interval is always symmetric.\n\t\t// Try left-biasing it and see if we can do\n\t\t// better while still satisfying the\n\t\t// confidence level.\n\t\trBiased := r - 1\n\t\tif debug {\n\t\t\tfmt.Printf(\" unbiased %v, biased %v\\n\", res.Confidence, cdf(l, rBiased))\n\t\t}\n\t\tif aBiased := cdf(l, rBiased); aBiased >= confidence && aBiased < res.Confidence {\n\t\t\tif debug {\n\t\t\t\tfmt.Printf(\" taking biased\\n\")\n\t\t\t}\n\t\t\tres.Confidence, res.Ambiguous = aBiased, true\n\t\t\tr = rBiased\n\t\t}\n\t\tif l <= 0 && r >= n+1 {\n\t\t\t// The CI covers everything, but\n\t\t\t// because the normal distribution has\n\t\t\t// infinite support, the confidence\n\t\t\t// computed by CDF won't be quite 1.\n\t\t\t// Certainly the median falls between\n\t\t\t// -inf and +inf. This can happen even\n\t\t\t// in the biasing case, so we check\n\t\t\t// this in any case.\n\t\t\tif debug {\n\t\t\t\tfmt.Printf(\" adjusting for full range\\n\")\n\t\t\t}\n\t\t\tres.Confidence = 1\n\t\t\tres.Ambiguous = false\n\t\t}\n\t}\n\n\tif l < 0 {\n\t\tl = 0\n\t}\n\tif r > n+1 {\n\t\tr = n + 1\n\t}\n\tres.LoOrder, res.HiOrder = l, r\n\treturn res\n}", "func (f F) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\ty := mathext.InvRegIncBeta(0.5*f.D1, 0.5*f.D2, p)\n\treturn f.D2 * y / (f.D1 * (1 - y))\n}", "func (c ChiSquared) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\treturn mathext.GammaIncRegInv(0.5*c.K, p) * 2\n}", "func PercentilesFilter(percentiles []float64) Filter {\n\ts := make([]string, 0, len(percentiles))\n\tfor _, v := range percentiles {\n\t\ts = append(s, fmt.Sprintf(\"%v\", v))\n\t}\n\tj := strings.Join(s, \",\")\n\treturn Param(\"percentiles\", j)\n}", "func GetThreshold(scores map[int]float64, percentile float64) float64 {\n\t// Sort the scores into numerical order\n\tvalues := SortMap(scores)\n\n\tthresholdIndex := math.Round(float64(len(values)) * percentile / 100)\n\n\treturn values[int(thresholdIndex)]\n}", "func PercentOf(part int, total int) float64 {\n\treturn (float64(part) * float64(100.00)) / float64(total)\n}", "func Percent(val, total int) float64 {\n\tif total == 0 {\n\t\treturn float64(0)\n\t}\n\treturn (float64(val) / float64(total)) * 100\n}", "func FirstQuartile(values []float64) float64 {\n\treturn Percentile(values, 25.0)\n}", "func (s StudentsT) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\t// F(x) = 1 - 0.5 * I_t(x)(nu/2, 1/2)\n\t// t(x) = nu/(t^2 + nu)\n\tif p == 0.5 {\n\t\treturn s.Mu\n\t}\n\tvar y float64\n\tif p > 0.5 {\n\t\t// Know t > 0\n\t\tt := mathext.InvRegIncBeta(s.Nu/2, 0.5, 2*(1-p))\n\t\ty = math.Sqrt(s.Nu * (1 - t) / t)\n\t} else {\n\t\tt := mathext.InvRegIncBeta(s.Nu/2, 0.5, 2*p)\n\t\ty = -math.Sqrt(s.Nu * (1 - t) / t)\n\t}\n\t// Convert out of standard normal\n\treturn y*s.Sigma + s.Mu\n}", "func (r RetCalc) PercentilePath(percentile float64) Path {\n\tix := int(float64(r.N) * percentile)\n\treturn r.all_paths[ix]\n}", "func (e Exponential) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\treturn -math.Log(1-p) / e.Rate\n}", "func ParsePercentiles(percentiles string) ([]float64, error) {\n\tpercs := strings.Split(percentiles, \",\") // will make a size 1 array for empty input!\n\tres := make([]float64, 0, len(percs))\n\tfor _, pStr := range percs {\n\t\tpStr = strings.TrimSpace(pStr)\n\t\tif len(pStr) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tp, err := strconv.ParseFloat(pStr, 64)\n\t\tif err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres = append(res, p)\n\t}\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"list can't be empty\")\n\t}\n\tlog.LogVf(\"Will use %v for percentiles\", res)\n\treturn res, nil\n}", "func getMemPercent(usage uint64, memLimit uint64) float64 {\n\tif memLimit == 0 {\n\t\treturn 0\n\t}\n\n\treturn float64(usage) / float64(memLimit) * 100\n}", "func NewPercentileTransform(levels int) *PercentileTransform {\n\tbase := math.Pow(0.1, float64(levels))\n\treturn &PercentileTransform{\n\t\tlevels: levels,\n\t\tbase: base,\n\t\tmulbase: 1 / math.Log(base),\n\t}\n}", "func (g *Graph) GetVertexPercentileAggregation(ctx context.Context, label string, field string, percents []float64) (*gripql.AggregationResult, error) {\n\treturn nil, errors.New(\"not implemented\")\n}", "func HandlePercentile(w http.ResponseWriter, req *http.Request) {\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar numbers Numbers\n\n\terr := decoder.Decode(&numbers)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prevent division by zero\n\tperc := Percentile(numbers)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tjsonRes, _ := json.Marshal(&Response{Result: perc})\n\n\tw.Write(jsonRes)\n}", "func (e *Estimator) Quantile(confidence float64) float64 {\n\n\t// Handle numerically impossible cases\n\tif confidence < 0. || confidence > 1. {\n\t\treturn math.NaN()\n\t}\n\n\t// Handle special, numerically unstable cases\n\tif e.NTrial == 0 || confidence < epsilon {\n\t\treturn 0.\n\t}\n\tif (1. - confidence) < epsilon {\n\t\treturn 1.\n\t}\n\n\t// Determine the initial result seed based on the mode of the distribution and\n\t// stabilize edge cases\n\tinitialEstimate := e.Mode\n\tif initialEstimate < epsilon {\n\t\tinitialEstimate = math.Min(0.1, 1./float64(e.NTrial))\n\t} else if initialEstimate == 1 {\n\t\tinitialEstimate = math.Max(0.9, 1.-(1./float64(e.NTrial)))\n\t}\n\n\t// For large values use a linear root finding method (as it is more stable)\n\tif e.NTrial > maxQuadraticRootFindingN {\n\t\treturn root.Bisect(func(x float64) float64 {\n\t\t\treturn numerics.BetaIncompleteRegular(x, 1.+float64(e.NSuccess), 1.-float64(e.NSuccess)+float64(e.NTrial)) - confidence\n\t\t}, 0., 1.)\n\t}\n\n\t// For smaller values use a quadratic root finding method (as it is faster and more precise)\n\treturn root.Find(func(x float64) float64 {\n\t\treturn numerics.BetaIncompleteRegular(x, 1.+float64(e.NSuccess), 1.-float64(e.NSuccess)+float64(e.NTrial)) - confidence\n\t}, func(x float64) float64 {\n\t\treturn numerics.Binomial(x, float64(e.NSuccess), float64(e.NTrial)) / numerics.Beta(1.+float64(e.NSuccess), 1.-float64(e.NSuccess)+float64(e.NTrial))\n\t}, initialEstimate, root.WithLimits(0., 1.), root.WithHeuristics())\n}", "func Percent(value int64, total int64) float64 {\n\tif total == 0 {\n\t\treturn 0\n\t}\n\treturn (float64(value) / float64(total)) * 100\n}", "func (fn *formulaFuncs) PERCENTILEdotINC(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"PERCENTILE.INC requires 2 arguments\")\n\t}\n\treturn fn.PERCENTILE(argsList)\n}", "func (fn *formulaFuncs) percentrank(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 && argsList.Len() != 3 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires 2 or 3 arguments\", name))\n\t}\n\tarray := argsList.Front().Value.(formulaArg).ToList()\n\tx := argsList.Front().Next().Value.(formulaArg).ToNumber()\n\tif x.Type != ArgNumber {\n\t\treturn x\n\t}\n\tvar numbers []float64\n\tfor _, arg := range array {\n\t\tif arg.Type == ArgError {\n\t\t\treturn newErrorFormulaArg(formulaErrorNA, formulaErrorNA)\n\t\t}\n\t\tif arg.Type == ArgNumber {\n\t\t\tnumbers = append(numbers, arg.Number)\n\t\t}\n\t}\n\tcnt := len(numbers)\n\tsort.Float64s(numbers)\n\tif x.Number < numbers[0] || x.Number > numbers[cnt-1] {\n\t\treturn newErrorFormulaArg(formulaErrorNA, formulaErrorNA)\n\t}\n\tpos, significance := float64(inFloat64Slice(numbers, x.Number)), newNumberFormulaArg(3)\n\tif argsList.Len() == 3 {\n\t\tif significance = argsList.Back().Value.(formulaArg).ToNumber(); significance.Type != ArgNumber {\n\t\t\treturn significance\n\t\t}\n\t\tif significance.Number < 1 {\n\t\t\treturn newErrorFormulaArg(formulaErrorNUM, fmt.Sprintf(\"%s arguments significance should be > 1\", name))\n\t\t}\n\t}\n\tif pos == -1 {\n\t\tpos = 0\n\t\tcmp := numbers[0]\n\t\tfor cmp < x.Number {\n\t\t\tpos++\n\t\t\tcmp = numbers[int(pos)]\n\t\t}\n\t\tpos--\n\t\tpos += (x.Number - numbers[int(pos)]) / (cmp - numbers[int(pos)])\n\t}\n\tpow := math.Pow(10, significance.Number)\n\tdigit := pow * pos / (float64(cnt) - 1)\n\tif name == \"PERCENTRANK.EXC\" {\n\t\tdigit = pow * (pos + 1) / (float64(cnt) + 1)\n\t}\n\treturn newNumberFormulaArg(math.Floor(digit) / pow)\n}", "func (o JobTemplateAbortCriteriaOutput) ThresholdPercentage() pulumi.Float64Output {\n\treturn o.ApplyT(func(v JobTemplateAbortCriteria) float64 { return v.ThresholdPercentage }).(pulumi.Float64Output)\n}", "func EstimateSlippagePercentage(maximumSlippageRate, minimumSlippageRate decimal.Decimal) decimal.Decimal {\n\tif minimumSlippageRate.LessThan(decimal.NewFromInt(1)) || minimumSlippageRate.GreaterThan(decimal.NewFromInt(100)) {\n\t\treturn decimal.NewFromInt(1)\n\t}\n\tif maximumSlippageRate.LessThan(decimal.NewFromInt(1)) || maximumSlippageRate.GreaterThan(decimal.NewFromInt(100)) {\n\t\treturn decimal.NewFromInt(1)\n\t}\n\n\t// the language here is confusing. The maximum slippage rate is the lower bounds of the number,\n\t// eg 80 means for every dollar, keep 80%\n\trandSeed := int(minimumSlippageRate.IntPart()) - int(maximumSlippageRate.IntPart())\n\tif randSeed > 0 {\n\t\tresult := int64(rand.Intn(randSeed)) //nolint:gosec // basic number generation required, no need for crypto/rand\n\n\t\treturn maximumSlippageRate.Add(decimal.NewFromInt(result)).Div(decimal.NewFromInt(100))\n\t}\n\treturn decimal.NewFromInt(1)\n}", "func PercentageChange(old, new int) float64 {\n\treturn (float64(new-old) / float64(old)) * 100\n}", "func PercentOfFloat(part float64, total float64) float64 {\n\treturn (float64(part) * float64(100.00)) / float64(total)\n}", "func SplitPercent(p int) SplitOption {\n\treturn splitOption(func(opts *options) error {\n\t\tif min, max := 0, 100; p <= min || p >= max {\n\t\t\treturn fmt.Errorf(\"invalid split percentage %d, must be in range %d < p < %d\", p, min, max)\n\t\t}\n\t\topts.splitPercent = p\n\t\treturn nil\n\t})\n}", "func PercentageChangeFloat(old, new float64) float64 {\n\treturn ((new - old) / old) * 100\n}", "func (r *PresampledResampler) Quantile(q float64) float64 {\n\treturn quantile(r.sampleAggregates, q)\n}", "func ProcessMetric(metric *Metric, flushDuration time.Duration, quantiles []int, logger Logger) {\n\tflushInterval := flushDuration / time.Second\n\n\tsort.Sort(metric.AllValues)\n\tswitch metric.MetricType {\n\tcase MetricTypeCounter:\n\t\tmetric.ValuesPerSecond = metric.LastValue / float64(flushInterval)\n\tcase MetricTypeGauge:\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\tcase MetricTypeSet:\n\t\tmetric.LastValue = float64(metric.AllValues.UniqueCount())\n\tcase MetricTypeTimer:\n\t\tmetric.MinValue, metric.MaxValue, _ = metric.AllValues.Minmax()\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\t\tmetric.ValuesPerSecond = metric.TotalHits / float64(flushInterval)\n\n\t\tmetric.Quantiles = make([]MetricQuantile, 0)\n\t\tfor _, q := range quantiles {\n\t\t\tpercentile := float64(q) / float64(100)\n\t\t\tquantile := new(MetricQuantile)\n\t\t\tquantile.Quantile = q\n\n\t\t\t// Make calculations based on the desired quantile.\n\t\t\tquantile.Boundary = metric.AllValues.Quantile(percentile)\n\t\t\tfor _, value := range metric.AllValues {\n\t\t\t\tif value > quantile.Boundary {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tquantile.AllValues = append(quantile.AllValues, value)\n\t\t\t}\n\t\t\t_, quantile.Max, _ = quantile.AllValues.Minmax()\n\t\t\tquantile.Mean = quantile.AllValues.Mean()\n\t\t\tquantile.Median = quantile.AllValues.Median()\n\t\t\tquantile.Sum = quantile.AllValues.Sum()\n\t\t\tmetric.Quantiles = append(metric.Quantiles, *quantile)\n\t\t}\n\t}\n}", "func ThirdQuartile(values []float64) float64 {\n\treturn Percentile(values, 75.0)\n}", "func (s Series) Quantile(p float64) (float64, error) {\n\tif s.Type() == String || s.Len() == 0 {\n\t\treturn math.NaN(), nil\n\t}\n\n\tordered, err := s.Subset(s.Order(false)).Float(false)\n\tif err != nil {\n\t\treturn math.NaN(), err\n\t}\n\n\treturn stat.Quantile(p, stat.Empirical, ordered, nil), nil\n}", "func (t *transfer) Percentage() int {\n\t// catch zero values\n\tif t.progress == 0 || t.size == 0 {\n\t\treturn 0\n\t}\n\t// calculate\n\treturn int(100.0 * (float32(t.progress) / float32(t.size)))\n}", "func computeCPUPercent(timeSpentA, timeSpentB time.Duration, sampleTimeA, sampleTimeB time.Time) float64 {\n\t// divide change in time spent in CPU over time between samples.\n\t// result is out of 100.\n\t//\n\t// don't worry about overflowing int64. it's like, 30 years.\n\treturn float64((timeSpentB-timeSpentA)*100) / float64(sampleTimeB.UnixNano()-sampleTimeA.UnixNano())\n}", "func (o DeliveryPipelineSerialPipelineStageStrategyCanaryCustomCanaryDeploymentPhaseConfigOutput) Percentage() pulumi.IntOutput {\n\treturn o.ApplyT(func(v DeliveryPipelineSerialPipelineStageStrategyCanaryCustomCanaryDeploymentPhaseConfig) int {\n\t\treturn v.Percentage\n\t}).(pulumi.IntOutput)\n}", "func (fn *formulaFuncs) PERCENTILEdotEXC(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"PERCENTILE.EXC requires 2 arguments\")\n\t}\n\tarray := argsList.Front().Value.(formulaArg).ToList()\n\tk := argsList.Back().Value.(formulaArg).ToNumber()\n\tif k.Type != ArgNumber {\n\t\treturn k\n\t}\n\tif k.Number <= 0 || k.Number >= 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)\n\t}\n\tvar numbers []float64\n\tfor _, arg := range array {\n\t\tif arg.Type == ArgError {\n\t\t\treturn newErrorFormulaArg(formulaErrorNUM, formulaErrorNUM)\n\t\t}\n\t\tif arg.Type == ArgNumber {\n\t\t\tnumbers = append(numbers, arg.Number)\n\t\t}\n\t}\n\tcnt := len(numbers)\n\tsort.Float64s(numbers)\n\tidx := k.Number * (float64(cnt) + 1)\n\tbase := math.Floor(idx)\n\tnext := base - 1\n\tproportion := math.Nextafter(idx, idx) - base\n\treturn newNumberFormulaArg(numbers[int(next)] + ((numbers[int(base)] - numbers[int(next)]) * proportion))\n}", "func percent(a int64, b int64, finish bool) string {\n\tif b == 0 {\n\t\tif finish {\n\t\t\treturn \"100.00 %\"\n\t\t}\n\t\treturn \"0.00 %\"\n\t}\n\treturn fmt.Sprintf(\"%.2f %%\", float64(a)/float64(b)*100)\n}", "func NewSummaryValueAtPercentileSlice() SummaryValueAtPercentileSlice {\n\torig := []*otlpmetrics.SummaryDataPoint_ValueAtPercentile(nil)\n\treturn SummaryValueAtPercentileSlice{&orig}\n}", "func calculatePercent(count int, totalRows int) (percent float64) {\n\treturn math.Round(float64(count) / float64(totalRows) * 100)\n}", "func NewPercentilesAxis() *Axis {\n\taxis := NewAxis()\n\taxis.Transform = NewPercentileTransform(5)\n\taxis.Ticks = ManualTicks{\n\t\t{Value: 0, Label: \"0\"},\n\t\t{Value: 0.25, Label: \"25\"},\n\t\t{Value: 0.5, Label: \"50\"},\n\t\t{Value: 0.75, Label: \"75\"},\n\t\t{Value: 0.9, Label: \"90\"},\n\t\t{Value: 0.99, Label: \"99\"},\n\t\t{Value: 0.999, Label: \"99.9\"},\n\t\t{Value: 0.9999, Label: \"99.99\"},\n\t\t{Value: 0.99999, Label: \"99.999\"}}\n\treturn axis\n}", "func (p *Percentiles) Flush() ([]processorResult, bool) {\n\n\tsize := len(p.values)\n\tif size == 0 {\n\t\treturn nil, false\n\t}\n\n\tvar results []processorResult\n\tsort.Float64s(p.values)\n\n\tfor fcnName, percent := range p.percents {\n\t\trank := (percent / 100) * (float64(size) + 1)\n\t\tfloor := int(rank)\n\n\t\tif rank < 1 {\n\t\t\tresults = append(results, processorResult{fcnName, p.values[0]})\n\t\t} else if floor >= size {\n\t\t\tresults = append(results, processorResult{fcnName, p.values[size-1]})\n\t\t} else {\n\t\t\tfrac := rank - float64(floor)\n\t\t\tupper := floor + 1\n\t\t\tpercentile := p.values[floor-1] + frac*(p.values[upper-1]-p.values[floor-1])\n\t\t\tresults = append(results, processorResult{fcnName, percentile})\n\t\t}\n\t}\n\n\treturn results, true\n}", "func (p *Process) Percent(interval time.Duration) (float64, error) {\n\treturn p.PercentWithContext(context.Background(), interval)\n}", "func (ms SummaryDataPoint) ValueAtPercentiles() SummaryValueAtPercentileSlice {\n\treturn newSummaryValueAtPercentileSlice(&(*ms.orig).PercentileValues)\n}", "func getPixelDiffPercent(numDiffPixels, totalPixels int) float32 {\n\treturn (float32(numDiffPixels) * 100) / float32(totalPixels)\n}", "func PercentageToCursorF(pct float64) RolloutBytes {\n\t// NB: convert the max value to a number, multiply by the percentage, convert back.\n\tvar maxInt, maskInt big.Int\n\tvar maxBytes RolloutBytes\n\tfor i := 0; i < len(maxBytes); i++ {\n\t\tmaxBytes[i] = 255\n\t}\n\tmaxInt.SetBytes(maxBytes[:])\n\tmaskInt.Mul(maskInt.Div(&maxInt, big.NewInt(100*10000)), big.NewInt(int64(pct*10000)))\n\tvar cursor RolloutBytes\n\tcopy(cursor[:], maskInt.Bytes())\n\n\treturn cursor\n}", "func CalculatePageRank(d float64, pages *map[string]*crawler.Page) {\n\tfor i := 0; i < 1000; i++ {\n\t\t// converge := make([]bool, 0)\n\t\t// for i := 0; i < len(*pages); i++ {\n\t\t// \tconverge[i] = false\n\t\t// }\n\t\tfor _, page := range *pages {\n\t\t\tvar myRank float64 = 1 - d // value for page rank\n\t\t\tvar runningSum float64 = 0 // running sum for probablity from its parents\n\t\t\tfor _, p := range page.GetParentURL() {\n\t\t\t\tparentPage, ok := (*pages)[p]\n\t\t\t\tif ok {\n\t\t\t\t\tvar parentPR float64 = parentPage.GetPageRank()\n\t\t\t\t\tparentTotalChild := float64(len(parentPage.GetChildrenURL()))\n\t\t\t\t\trunningSum += (parentPR / parentTotalChild)\n\t\t\t\t}\n\t\t\t}\n\t\t\tmyRank = myRank + d*runningSum\n\t\t\tdifference := myRank - page.GetPageRank()\n\t\t\tif math.Abs(difference) < 0.00000000000005 { // showing signs of converging\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpage.SetRank(myRank)\n\t\t}\n\t}\n}", "func Percent(current uint64, all uint64) float64 {\n\tpercent := (float64(current) * float64(100)) / float64(all)\n\treturn percent\n}", "func TestCpuPercent(t *testing.T) {\n\texpected := []float64{}\n\tactual, _ := cpuPercent((500 * time.Millisecond), false)\n\n\tassert.IsType(t, expected, actual, \"`cpuPercent()` should return a []float64 slice\")\n}", "func (o AppIngressTrafficWeightOutput) Percentage() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AppIngressTrafficWeight) int { return v.Percentage }).(pulumi.IntOutput)\n}", "func PartialRetention(amount float64, v RetValue) float64 {\n\tswitch {\n\tcase amount <= v.min:\n\t\treturn 0\n\tcase amount >= v.max:\n\t\treturn (v.max - v.min) * v.percentage\n\tdefault:\n\t\treturn (amount - v.min) * v.percentage\n\t}\n}", "func ppmFromPercentage(percentage float64) (uint64, error) {\n\tif percentage <= 0 || percentage >= 100 {\n\t\treturn 0, fmt.Errorf(\"fee percentage must be in (0;100)\")\n\t}\n\n\treturn uint64(percentage / 100 * liquidity.FeeBase), nil\n}", "func Percentage(wcc ...WC) Decorator {\n\treturn NewPercentage(\"% d\", wcc...)\n}", "func PercentageToCursor(pct int) RolloutBytes {\n\t// NB: convert the max value to a number, multiply by the percentage, convert back.\n\tvar maxInt, maskInt big.Int\n\tvar maxBytes RolloutBytes\n\tfor i := 0; i < len(maxBytes); i++ {\n\t\tmaxBytes[i] = 255\n\t}\n\tmaxInt.SetBytes(maxBytes[:])\n\tmaskInt.Div(maskInt.Mul(&maxInt, big.NewInt(int64(pct))), big.NewInt(100))\n\n\tvar cursor RolloutBytes\n\tcopy(cursor[:], maskInt.Bytes())\n\n\treturn cursor\n}", "func (filter *BloomFilter) CalculateFPP() float64 {\n\texp := float64(-filter.hashCount*filter.keySize) / float64(filter.capacity)\n\tbase := math.Pow(math.E, exp)\n\treturn math.Pow(float64(1-base), float64(filter.hashCount))\n}", "func (r *BasicResampler) Quantile(q float64) float64 {\n\treturn quantile(r.sampleAggregates, q)\n}" ]
[ "0.7380092", "0.7268161", "0.72424823", "0.72364116", "0.7197128", "0.7074464", "0.7061248", "0.7056118", "0.70472664", "0.70196384", "0.6993656", "0.69328964", "0.6865733", "0.6809692", "0.6740541", "0.67208064", "0.670653", "0.66812855", "0.6540653", "0.6528381", "0.63955534", "0.6320521", "0.63184875", "0.6279539", "0.6091051", "0.603855", "0.6025514", "0.59698224", "0.58977807", "0.5888072", "0.58634806", "0.584689", "0.5721187", "0.5716696", "0.56902266", "0.56117857", "0.56099343", "0.56083095", "0.5576816", "0.55171293", "0.5484698", "0.54821974", "0.5481406", "0.5458354", "0.5449908", "0.5409548", "0.5402538", "0.53349185", "0.53264344", "0.5262206", "0.51931894", "0.5187536", "0.517394", "0.51462346", "0.5146128", "0.51396453", "0.5128526", "0.5099879", "0.50450337", "0.4979121", "0.49590397", "0.49533454", "0.49513575", "0.49481726", "0.49014026", "0.48963708", "0.4879256", "0.48626024", "0.48447242", "0.48327082", "0.48311746", "0.48232523", "0.4798689", "0.4760107", "0.47495496", "0.4739668", "0.47394463", "0.47343096", "0.4727748", "0.47268608", "0.47236282", "0.4717676", "0.4705156", "0.46925214", "0.46820417", "0.4668809", "0.4649025", "0.4648147", "0.46410233", "0.46377203", "0.46275866", "0.46225983", "0.4616216", "0.45978197", "0.4578781", "0.45780486", "0.45562926", "0.45485014", "0.45481592", "0.45405173" ]
0.784947
0
Export translate the internal representation of the histogram data in an externally usable one. Calculates the request Percentiles.
func (h *Histogram) Export() *HistogramData { var res HistogramData res.Count = h.Counter.Count res.Min = h.Counter.Min res.Max = h.Counter.Max res.Sum = h.Counter.Sum res.Avg = h.Counter.Avg() res.StdDev = h.Counter.StdDev() multiplier := h.Divider offset := h.Offset // calculate the last bucket index lastIdx := -1 for i := numBuckets - 1; i >= 0; i-- { if h.Hdata[i] > 0 { lastIdx = i break } } if lastIdx == -1 { return &res } // previous bucket value: prev := histogramBucketValues[0] var total int64 ctrTotal := float64(h.Count) // export the data of each bucket of the histogram for i := 0; i <= lastIdx; i++ { if h.Hdata[i] == 0 { // empty bucket: skip it but update prev which is needed for next iter if i < numValues { prev = histogramBucketValues[i] } continue } var b Bucket total += int64(h.Hdata[i]) if len(res.Data) == 0 { // First entry, start is min b.Start = h.Min } else { b.Start = multiplier*float64(prev) + offset } b.Percent = 100. * float64(total) / ctrTotal if i < numValues { cur := histogramBucketValues[i] b.End = multiplier*float64(cur) + offset prev = cur } else { // Last Entry b.Start = multiplier*float64(prev) + offset b.End = h.Max } b.Count = int64(h.Hdata[i]) res.Data = append(res.Data, b) } res.Data[len(res.Data)-1].End = h.Max return &res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (te *TelemetryEmitter) emitHistogram(metric Metric, timestamp time.Time) error {\n\thist, ok := metric.value.(*dto.Histogram)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown histogram metric type for %q: %T\", metric.name, metric.value)\n\t}\n\n\tif m, ok := te.deltaCalculator.CountMetric(metric.name+\".sum\", metric.attributes, hist.GetSampleSum(), timestamp); ok {\n\t\tte.harvester.RecordMetric(m)\n\t}\n\n\tmetricName := metric.name + \".buckets\"\n\tbuckets := make(histogram.Buckets, 0, len(hist.Bucket))\n\tfor _, b := range hist.GetBucket() {\n\t\tupperBound := b.GetUpperBound()\n\t\tcount := float64(b.GetCumulativeCount())\n\t\tif !math.IsInf(upperBound, 1) {\n\t\t\tbucketAttrs := copyAttrs(metric.attributes)\n\t\t\tbucketAttrs[\"histogram.bucket.upperBound\"] = upperBound\n\t\t\tif m, ok := te.deltaCalculator.CountMetric(metricName, bucketAttrs, count, timestamp); ok {\n\t\t\t\tte.harvester.RecordMetric(m)\n\t\t\t}\n\t\t}\n\t\tbuckets = append(\n\t\t\tbuckets,\n\t\t\thistogram.Bucket{\n\t\t\t\tUpperBound: upperBound,\n\t\t\t\tCount: count,\n\t\t\t},\n\t\t)\n\t}\n\n\tvar results error\n\tmetricName = metric.name + \".percentiles\"\n\tfor _, p := range te.percentiles {\n\t\tv, err := histogram.Percentile(p, buckets)\n\t\tif err != nil {\n\t\t\tif results == nil {\n\t\t\t\tresults = err\n\t\t\t} else {\n\t\t\t\tresults = fmt.Errorf(\"%v: %w\", err, results)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpercentileAttrs := copyAttrs(metric.attributes)\n\t\tpercentileAttrs[\"percentile\"] = p\n\t\tte.harvester.RecordMetric(telemetry.Gauge{\n\t\t\tName: metricName,\n\t\t\tAttributes: percentileAttrs,\n\t\t\tValue: v,\n\t\t\tTimestamp: timestamp,\n\t\t})\n\t}\n\n\treturn results\n}", "func HandlePercentile(w http.ResponseWriter, req *http.Request) {\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar numbers Numbers\n\n\terr := decoder.Decode(&numbers)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prevent division by zero\n\tperc := Percentile(numbers)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tjsonRes, _ := json.Marshal(&Response{Result: perc})\n\n\tw.Write(jsonRes)\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}", "func (h *PCPHistogram) Percentile(p float64) int64 { return h.h.ValueAtQuantile(p) }", "func (e *HistogramData) CalcPercentiles(percentiles []float64) *HistogramData {\n\tif e.Count == 0 {\n\t\treturn e\n\t}\n\tfor _, p := range percentiles {\n\t\te.Percentiles = append(e.Percentiles, Percentile{p, e.CalcPercentile(p)})\n\t}\n\treturn e\n}", "func (s *UniformSample) Percentiles(ps []float64) []float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentiles(s.values, ps)\n}", "func (ms SummaryValueAtPercentile) Percentile() float64 {\n\treturn (*ms.orig).Percentile\n}", "func (t *StandardTimer) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func PublishHistogram(ctx context.Context, key string, value float64) {\n\n\t// Spans are not processed by the collector until the span ends, so to prevent any delay\n\t// in processing the stats when the current span is long-lived we create a new span for every call.\n\t// suffix the span name with SpannameSuffixDummy to denote that it is used only to hold a metric and isn't itself of any interest\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"histogram_metrics\"+SpannameSuffixDummy)\n\tdefer span.Finish()\n\n\t// The field name we use is the metric name prepended with FieldnamePrefixHistogram to designate that it is a Prometheus histogram metric\n\t// The collector will replace that prefix with \"fn_\" and use the result as the Prometheus metric name.\n\tfieldname := FieldnamePrefixHistogram + key\n\tspan.LogFields(log.Float64(fieldname, value))\n}", "func (p *Provider) Histogram(name string, value float64, tags map[string]string) error {\n\treturn p.client.Histogram(name, value, p.formatTags(tags), p.rate)\n}", "func (c *Client) Histogram(stat string, value int, rate float64) error {\n\treturn c.send(stat, rate, \"%d|ms\", value)\n}", "func (d TestSink) Histogram(c *telemetry.Context, stat string, value float64) {\n\td[stat] = TestMetric{\"Histogram\", value, c.Tags()}\n}", "func AnalyzeAllResponses(a *Analyzer, ar []*Response) {\n f, err := os.Create(\"swing-data.csv\")\n if err != nil { panic(err) }\n defer f.Close()\n w := csv.NewWriter(f)\n defer w.Flush()\n Range := histogram.Range(-1.0, 200, .01)\n h, err := histogram.NewHistogram(Range)\n if err != nil {\n panic(err)\n }\n for _, resp := range ar {\n for _, oi := range a.AnalyzeStock(resp) {\n var toWrite = []string{\n strconv.FormatFloat(oi.Swing, 'f', 4, 64),\n strconv.FormatFloat(oi.Ret, 'f', 4, 64),\n }\n w.Write(toWrite)\n h.Add(oi.Ret)\n }\n }\n fmt.Println(\"MEAN: \", h.Mean())\n fmt.Println(\"SIGMA \", h.Sigma())\n}", "func (t *TimerSnapshot) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func (e *Exporter) toMetric(v *view.View, row *view.Row, vd *view.Data) []client.Metric {\n\tswitch data := row.Data.(type) {\n\tcase *view.CountData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.SumData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.LastValueData:\n\t\treturn []client.Metric{e.formatTimeSeriesMetric(data.Value, row, vd)}\n\tcase *view.DistributionData:\n\t\t// Graphite does not support histogram. In order to emulate one,\n\t\t// we use the accumulative count of the bucket.\n\t\tindicesMap := make(map[float64]int)\n\t\tbuckets := make([]float64, 0, len(v.Aggregation.Buckets))\n\t\tfor i, b := range v.Aggregation.Buckets {\n\t\t\tif _, ok := indicesMap[b]; !ok {\n\t\t\t\tindicesMap[b] = i\n\t\t\t\tbuckets = append(buckets, b)\n\t\t\t}\n\t\t}\n\t\tsort.Float64s(buckets)\n\n\t\tvar metrics []client.Metric\n\n\t\t// Now that the buckets are sorted by magnitude\n\t\t// we can create cumulative indicesmap them back by reverse index\n\t\tcumCount := uint64(0)\n\t\tfor _, b := range buckets {\n\t\t\ti := indicesMap[b]\n\t\t\tcumCount += uint64(data.CountPerBucket[i])\n\t\t\tnames := []string{sanitize(e.opts.Namespace), sanitize(vd.View.Name), \"bucket\"}\n\t\t\ttags := tagValues(row.Tags) + fmt.Sprintf(\";le=%.2f\", b)\n\t\t\tmetric := client.Metric{\n\t\t\t\tName: buildPath(names, tags, e.tags),\n\t\t\t\tValue: float64(cumCount),\n\t\t\t\tTimestamp: vd.End,\n\t\t\t}\n\t\t\tmetrics = append(metrics, metric)\n\t\t}\n\t\tnames := []string{sanitize(e.opts.Namespace), sanitize(vd.View.Name), \"bucket\"}\n\t\ttags := tagValues(row.Tags) + \";le=+Inf\"\n\t\tmetric := client.Metric{\n\t\t\tName: buildPath(names, tags, e.tags),\n\t\t\tValue: float64(cumCount),\n\t\t\tTimestamp: vd.End,\n\t\t}\n\t\tmetrics = append(metrics, metric)\n\t\treturn metrics\n\tdefault:\n\t\te.opts.onError(fmt.Errorf(\"aggregation %T is not yet supported\", data))\n\t\treturn nil\n\t}\n}", "func (networkStats *NetworkStats) Export(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(networkBytesTotalDesc, prometheus.CounterValue, networkStats.BytesIn, \"in_bytes\")\n\tch <- prometheus.MustNewConstMetric(networkBytesTotalDesc, prometheus.CounterValue, networkStats.BytesOut, \"out_bytes\")\n\n\tch <- prometheus.MustNewConstMetric(networkMetricsNumRequestsTotalDesc, prometheus.CounterValue, networkStats.NumRequests)\n}", "func (s *UniformSample) Percentile(p float64) float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentile(s.values, p)\n}", "func (e errChunkIterator) AtHistogram() (int64, *histogram.Histogram) { panic(\"not implemented\") }", "func (t *TimerSnapshot) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func Percentile(by []string, percentile float64, input []*oproto.ValueStream) []*oproto.ValueStream {\n\toutput := []*oproto.ValueStream{{Variable: input[0].Variable}}\n\treturn output\n}", "func (c *StatsClient) Histogram(name string, value float64) {\n\tif err := c.client.Histogram(name, value, c.tags, Rate); err != nil {\n\t\tc.logger().Printf(\"datadog.StatsClient.Histogram error: %s\", err)\n\t}\n}", "func PublishHistograms(ctx context.Context, metrics map[string]float64) {\n\n\t// Spans are not processed by the collector until the span ends, so to prevent any delay\n\t// in processing the stats when the current span is long-lived we create a new span for every call.\n\t// suffix the span name with SpannameSuffixDummy to denote that it is used only to hold a metric and isn't itself of any interest\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"histogram_metrics\"+SpannameSuffixDummy)\n\tdefer span.Finish()\n\n\tfor key, value := range metrics {\n\t\t// The field name we use is the metric name prepended with FieldnamePrefixHistogram to designate that it is a Prometheus histogram metric\n\t\t// The collector will replace that prefix with \"fn_\" and use the result as the Prometheus metric name.\n\t\tfieldname := FieldnamePrefixHistogram + key\n\t\tspan.LogFields(log.Float64(fieldname, value))\n\t}\n}", "func Histogram(name string, requestTime float64, tags []string, rate float64) {\n\tif ddog == nil {\n\t\tlog.Error(\"datadog client is not initialized\")\n\t\treturn\n\t}\n\n\terr := ddog.Client.Histogram(name, requestTime, tags, rate)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"name\": name,\n\t\t}).Error(\"Failed to send histogram data to datadog\")\n\t}\n}", "func (t *StandardTimer) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func (collStatList *CollectionStatList) Export(ch chan<- prometheus.Metric) {\n\tfor _, member := range collStatList.Members {\n\t\tls := prometheus.Labels{\n\t\t\t\"db\": member.Database,\n\t\t\t\"coll\": member.Name,\n\t\t}\n\t\tcollectionSize.With(ls).Set(float64(member.Size))\n\t\tcollectionObjectCount.With(ls).Set(float64(member.Count))\n\t\tcollectionAvgObjSize.With(ls).Set(float64(member.AvgObjSize))\n\t\tcollectionStorageSize.With(ls).Set(float64(member.StorageSize))\n\t\tcollectionIndexes.With(ls).Set(float64(member.Indexes))\n\t\tcollectionIndexesSize.With(ls).Set(float64(member.IndexesSize))\n\t}\n\tcollectionSize.Collect(ch)\n\tcollectionObjectCount.Collect(ch)\n\tcollectionAvgObjSize.Collect(ch)\n\tcollectionStorageSize.Collect(ch)\n\tcollectionIndexes.Collect(ch)\n\tcollectionIndexesSize.Collect(ch)\n}", "func percentile(orderedObservations []float64, l int, p float64) float64 {\n\treturn orderedObservations[int(p*float64(l))]\n}", "func (_m *Reporter) Histogram(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 (h *Histogram) Print(out io.Writer, msg string, percentiles []float64) {\n\th.Export().CalcPercentiles(percentiles).Print(out, msg)\n}", "func (c *Client) Histogram(name string, value int) error {\n\treturn c.DataDog.Histogram(name, float64(value), nil, 1)\n}", "func (c *LoggerClient) Histogram(name string, value float64) {\n\tc.print(\"Histogram\", name, value, value)\n}", "func ProcessMetric(metric *Metric, flushDuration time.Duration, quantiles []int, logger Logger) {\n\tflushInterval := flushDuration / time.Second\n\n\tsort.Sort(metric.AllValues)\n\tswitch metric.MetricType {\n\tcase MetricTypeCounter:\n\t\tmetric.ValuesPerSecond = metric.LastValue / float64(flushInterval)\n\tcase MetricTypeGauge:\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\tcase MetricTypeSet:\n\t\tmetric.LastValue = float64(metric.AllValues.UniqueCount())\n\tcase MetricTypeTimer:\n\t\tmetric.MinValue, metric.MaxValue, _ = metric.AllValues.Minmax()\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\t\tmetric.ValuesPerSecond = metric.TotalHits / float64(flushInterval)\n\n\t\tmetric.Quantiles = make([]MetricQuantile, 0)\n\t\tfor _, q := range quantiles {\n\t\t\tpercentile := float64(q) / float64(100)\n\t\t\tquantile := new(MetricQuantile)\n\t\t\tquantile.Quantile = q\n\n\t\t\t// Make calculations based on the desired quantile.\n\t\t\tquantile.Boundary = metric.AllValues.Quantile(percentile)\n\t\t\tfor _, value := range metric.AllValues {\n\t\t\t\tif value > quantile.Boundary {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tquantile.AllValues = append(quantile.AllValues, value)\n\t\t\t}\n\t\t\t_, quantile.Max, _ = quantile.AllValues.Minmax()\n\t\t\tquantile.Mean = quantile.AllValues.Mean()\n\t\t\tquantile.Median = quantile.AllValues.Median()\n\t\t\tquantile.Sum = quantile.AllValues.Sum()\n\t\t\tmetric.Quantiles = append(metric.Quantiles, *quantile)\n\t\t}\n\t}\n}", "func (r *JobsService) Histogram(gethistogramrequest *GetHistogramRequest) *JobsHistogramCall {\n\tc := &JobsHistogramCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.gethistogramrequest = gethistogramrequest\n\treturn c\n}", "func PublishHistogramToSpan(span opentracing.Span, key string, value float64) {\n\n\t// The field name we use is the metric name prepended with FieldnamePrefixHistogram to designate that it is a Prometheus histogram metric\n\t// The collector will replace that prefix with \"fn_\" and use the result as the Prometheus metric name.\n\tfieldname := FieldnamePrefixHistogram + key\n\tspan.LogFields(log.Float64(fieldname, value))\n}", "func(c *HermesClient) ObserveSummary(metricName string, labels map[string]string, observation float64) {\n log.Debug(fmt.Sprintf(\"setting observation on histogram %s\", metricName))\n packet := HermesSummaryPacket{\n MetricName: metricName,\n Payload: HermesSummaryPayload{\n SummaryLabels: labels,\n SummaryObservation: observation,\n },\n }\n c.SendUDPPacket(packet)\n}", "func (preferences *ProductPreferences) GetPercentile(val float32) float32 {\r\n\t//TODO: change to bin search.\r\n\tfor i := len(preferences.Percentiles) - 1; i >= 0; i-- {\r\n\t\tif val > preferences.Percentiles[i] {\r\n\t\t\treturn float32(i+1) / float32(DistributionSize+1)\r\n\t\t}\r\n\t}\r\n\treturn 0\r\n}", "func Percentile(ts []Transaction, percent float64) float64 {\n\tSort(&ts)\n\ti := int(math.Floor(float64(len(ts)) * percent))\n\tvalue := ts[i].amount\n\treturn value\n}", "func (e *HistogramData) CalcPercentile(percentile float64) float64 {\n\tif len(e.Data) == 0 {\n\t\tlog.Errf(\"Unexpected call to CalcPercentile(%g) with no data\", percentile)\n\t\treturn 0\n\t}\n\tif percentile >= 100 {\n\t\treturn e.Max\n\t}\n\t// We assume Min is at least a single point so at least covers 1/Count %\n\tpp := 100. / float64(e.Count) // previous percentile\n\tif percentile <= pp {\n\t\treturn e.Min\n\t}\n\tfor _, cur := range e.Data {\n\t\tif percentile <= cur.Percent {\n\t\t\treturn cur.Start + (percentile-pp)/(cur.Percent-pp)*(cur.End-cur.Start)\n\t\t}\n\t\tpp = cur.Percent\n\t}\n\treturn e.Max // not reached\n}", "func (e *HistogramData) Print(out io.Writer, msg string) {\n\tif len(e.Data) == 0 {\n\t\t_, _ = fmt.Fprintf(out, \"%s : no data\\n\", msg) // nolint: gas\n\t\treturn\n\t}\n\t// the base counter part:\n\t_, _ = fmt.Fprintf(out, \"%s : count %d avg %.8g +/- %.4g min %g max %g sum %.9g\\n\",\n\t\tmsg, e.Count, e.Avg, e.StdDev, e.Min, e.Max, e.Sum)\n\t_, _ = fmt.Fprintln(out, \"# range, mid point, percentile, count\")\n\tsep := \">=\"\n\tfor i, b := range e.Data {\n\t\tif i > 0 {\n\t\t\tsep = \">\" // last interval is inclusive (of max value)\n\t\t}\n\t\t_, _ = fmt.Fprintf(out, \"%s %.6g <= %.6g , %.6g , %.2f, %d\\n\", sep, b.Start, b.End, (b.Start+b.End)/2., b.Percent, b.Count)\n\t}\n\n\t// print the information of target percentiles\n\tfor _, p := range e.Percentiles {\n\t\t_, _ = fmt.Fprintf(out, \"# target %g%% %.6g\\n\", p.Percentile, p.Value) // nolint: gas\n\t}\n}", "func UpdateHistogram(h *Histogram, feedback *QueryFeedback) *Histogram {\n\tbuckets, isNewBuckets, totalCount := splitBuckets(h, feedback)\n\tbuckets = mergeBuckets(buckets, isNewBuckets, float64(totalCount))\n\thist := buildNewHistogram(h, buckets)\n\t// Update the NDV of primary key column.\n\tif feedback.Tp == PkType {\n\t\thist.NDV = int64(hist.TotalRowCount())\n\t}\n\treturn hist\n}", "func (c *Collector) Percentile(percent float64) float64 {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttargetCount := int(percent * float64(c.Count) / 100)\n\n\tcount := 0\n\tfor _, b := range c.Buckets {\n\t\tcount += b.Count\n\t\tif count >= targetCount {\n\t\t\treturn b.Max\n\t\t}\n\t}\n\n\treturn c.Max\n}", "func PercentilesFilter(percentiles []float64) Filter {\n\ts := make([]string, 0, len(percentiles))\n\tfor _, v := range percentiles {\n\t\ts = append(s, fmt.Sprintf(\"%v\", v))\n\t}\n\tj := strings.Join(s, \",\")\n\treturn Param(\"percentiles\", j)\n}", "func (r *Recorder) Histogram(ctx context.Context, tconn *chrome.TestConn) ([]*Histogram, error) {\n\tnames := r.names()\n\n\ts, err := GetHistograms(ctx, tconn, names)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get snapshot\")\n\t}\n\n\treturn DiffHistograms(r.snapshot, s)\n}", "func ConvertSampleToHistogram(sample *model.Sample, h *Histogram) {\n\tlabels := make(map[string]string)\n\tfor k, v := range sample.Metric {\n\t\tif k != model.BucketLabel {\n\t\t\tlabels[string(k)] = string(v)\n\t\t}\n\t}\n\n\th.Labels = labels\n\th.Buckets[string(sample.Metric[model.BucketLabel])] += int(sample.Value)\n}", "func (*PUriHistogram) Descriptor() ([]byte, []int) {\n\treturn file_v1_Stat_proto_rawDescGZIP(), []int{24}\n}", "func (c *Aggregator) Histogram() (aggregation.Buckets, error) {\n\treturn aggregation.Buckets{\n\t\tBoundaries: c.boundaries,\n\t\tCounts: c.state.bucketCounts,\n\t}, nil\n}", "func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tlower := vals[0].(Vector)[0].F\n\tupper := vals[1].(Vector)[0].F\n\tinVec := vals[2].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramFraction(lower, upper, sample.H),\n\t\t})\n\t}\n\treturn enh.Out\n}", "func NewHistogram(nanoseconds []float64, opts *HistogramOptions) *Histogram {\n\tif opts.BinCount <= 0 {\n\t\tpanic(\"binCount must be larger than 0\")\n\t}\n\n\thist := &Histogram{}\n\thist.Width = 40\n\thist.Bins = make([]HistogramBin, opts.BinCount)\n\tif len(nanoseconds) == 0 {\n\t\treturn hist\n\t}\n\n\tnanoseconds = append(nanoseconds[:0:0], nanoseconds...)\n\tsort.Float64s(nanoseconds)\n\n\thist.Minimum = nanoseconds[0]\n\thist.Maximum = nanoseconds[len(nanoseconds)-1]\n\n\thist.Average = float64(0)\n\tfor _, x := range nanoseconds {\n\t\thist.Average += x\n\t}\n\thist.Average /= float64(len(nanoseconds))\n\n\tp := func(p float64) float64 {\n\t\ti := int(math.Round(p * float64(len(nanoseconds))))\n\t\tif i < 0 {\n\t\t\ti = 0\n\t\t}\n\t\tif i >= len(nanoseconds) {\n\t\t\ti = len(nanoseconds) - 1\n\t\t}\n\t\treturn nanoseconds[i]\n\t}\n\n\thist.P50, hist.P90, hist.P99, hist.P999, hist.P9999 = p(0.50), p(0.90), p(0.99), p(0.999), p(0.9999)\n\n\tclampMaximum := hist.Maximum\n\tif opts.ClampPercentile > 0 {\n\t\tclampMaximum = p(opts.ClampPercentile)\n\t}\n\tif opts.ClampMaximum > 0 {\n\t\tclampMaximum = opts.ClampMaximum\n\t}\n\n\tvar minimum, spacing float64\n\n\tif opts.NiceRange {\n\t\tminimum, spacing = calculateNiceSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t} else {\n\t\tminimum, spacing = calculateSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t}\n\n\tfor i := range hist.Bins {\n\t\thist.Bins[i].Start = spacing*float64(i) + minimum\n\t}\n\thist.Bins[0].Start = hist.Minimum\n\n\tfor _, x := range nanoseconds {\n\t\tk := int(float64(x-minimum) / spacing)\n\t\tif k < 0 {\n\t\t\tk = 0\n\t\t}\n\t\tif k >= opts.BinCount {\n\t\t\tk = opts.BinCount - 1\n\t\t\thist.Bins[k].andAbove = true\n\t\t}\n\t\thist.Bins[k].Count++\n\t}\n\n\tmaxBin := 0\n\tfor _, bin := range hist.Bins {\n\t\tif bin.Count > maxBin {\n\t\t\tmaxBin = bin.Count\n\t\t}\n\t}\n\n\tfor k := range hist.Bins {\n\t\tbin := &hist.Bins[k]\n\t\tbin.Width = float64(bin.Count) / float64(maxBin)\n\t}\n\n\treturn hist\n}", "func (NilTimer) Percentiles(ps []float64) []float64 {\n\treturn make([]float64, len(ps))\n}", "func (o *GetHistogramStatByParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\t// path param Id\n\tif err := r.SetPathParam(\"Id\", o.ID); err != nil {\n\t\treturn err\n\t}\n\n\t// path param Stat\n\tif err := r.SetPathParam(\"Stat\", o.Stat); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func createHistogram(data []float64, n int) {\n\tp, err := plot.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tp.Add(plotter.NewGrid())\n\thistdata := valuer{data}\n\tp.Add(plotter.NewHist(histdata, n))\n\tp.X.Label.Text = \"time / ps\"\n\tp.Y.Label.Text = \"frequency\"\n\tp.Title.Text = fmt.Sprintf(\"Frequency of lifetime data from lifetime.txt. %v bins.\", n)\n\n\tif err := p.Save(5, 5, fmt.Sprintf(\"out/Histogram with %v bins.png\", n)); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (NilTimer) Percentile(p float64) float64 { return 0.0 }", "func (a *LogsApiService) GetLogHistogramDataExecute(r ApiGetLogHistogramDataRequest) (AggregatedLog, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue AggregatedLog\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"LogsApiService.GetLogHistogramData\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/logs/aggregate\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.from != nil {\n\t\tlocalVarQueryParams.Add(\"from\", parameterToString(*r.from, \"\"))\n\t}\n\tif r.to != nil {\n\t\tlocalVarQueryParams.Add(\"to\", parameterToString(*r.to, \"\"))\n\t}\n\tif r.query != nil {\n\t\tlocalVarQueryParams.Add(\"query\", parameterToString(*r.query, \"\"))\n\t}\n\tif r.timeBuckets != nil {\n\t\tlocalVarQueryParams.Add(\"timeBuckets\", parameterToString(*r.timeBuckets, \"\"))\n\t}\n\tif r.maxGroupValues != nil {\n\t\tlocalVarQueryParams.Add(\"maxGroupValues\", parameterToString(*r.maxGroupValues, \"\"))\n\t}\n\tif r.groupBy != nil {\n\t\tt := *r.groupBy\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"groupBy\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"groupBy\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json; charset=utf-8\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Api-Token\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorEnvelope\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func newBatchHistogram(desc *Desc, buckets []float64, hasSum bool) *batchHistogram {\n\t// We need to remove -Inf values. runtime/metrics keeps them around.\n\t// But -Inf bucket should not be allowed for prometheus histograms.\n\tif buckets[0] == math.Inf(-1) {\n\t\tbuckets = buckets[1:]\n\t}\n\th := &batchHistogram{\n\t\tdesc: desc,\n\t\tbuckets: buckets,\n\t\t// Because buckets follows runtime/metrics conventions, there's\n\t\t// 1 more value in the buckets list than there are buckets represented,\n\t\t// because in runtime/metrics, the bucket values represent *boundaries*,\n\t\t// and non-Inf boundaries are inclusive lower bounds for that bucket.\n\t\tcounts: make([]uint64, len(buckets)-1),\n\t\thasSum: hasSum,\n\t}\n\th.init(h)\n\treturn h\n}", "func (m *MockHistogram) Percentile(percentile float64) float64 {\n\targs := m.Called(percentile)\n\treturn args.Get(0).(float64)\n}", "func (b BundledStates) Percentile(t time.Time, percentile int) time.Duration {\n\tif percentile > 100 || percentile <= 0 {\n\t\tpanic(fmt.Errorf(\"percentile %d is out of scope\", percentile))\n\t}\n\n\tages := []time.Duration{}\n\tfor _, age := range b.ages(t) {\n\t\tages = append(ages, age)\n\t}\n\n\tif len(ages) == 0 {\n\t\treturn 0\n\t}\n\n\tsort.Sort(ByDuration(ages))\n\n\tindex := int(math.Ceil(float64(percentile)*float64(len(ages))/100) - 1)\n\tif index >= len(ages) {\n\t\tpanic(fmt.Errorf(\"Index is out of range: %d/%d\", index, len(ages)))\n\t}\n\treturn ages[index]\n}", "func (datadog *Datadog) Histogram(name string, startTime time.Time, tags []string) error {\n\telapsedTime := time.Since(startTime).Seconds() * 1000\n\terr := datadog.client.Histogram(name, elapsedTime, tags, float64(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tresp, err := e.Pihole.GetMetrics()\n\tif err != nil {\n\t\tlog.Errorf(\"Pihole error: %s\", err.Error())\n\t\treturn\n\t}\n\tlog.Debugf(\"PiHole metrics: %#v\", resp)\n\tch <- prometheus.MustNewConstMetric(\n\t\tdomainsBeingBlocked, prometheus.CounterValue, float64(resp.DomainsBeingBlocked))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tdnsQueries, prometheus.CounterValue, float64(resp.DNSQueriesToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsBlocked, prometheus.CounterValue, float64(resp.AdsBlockedToday))\n\n\tch <- prometheus.MustNewConstMetric(\n\t\tadsPercentage, prometheus.CounterValue, float64(resp.AdsPercentageToday))\n\n\tfor k, v := range resp.Querytypes {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tqueryTypes, prometheus.CounterValue, v, k)\n\t}\n\tfor k, v := range resp.TopQueries {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopQueries, prometheus.CounterValue, float64(v), k)\n\t}\n\tfor k, v := range resp.TopAds {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopAds, prometheus.CounterValue, float64(v), k)\n\n\t}\n\tfor k, v := range resp.TopSources {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ttopSources, prometheus.CounterValue, float64(v), k)\n\t}\n}", "func Percentile(input []float64, percent float64) float64 {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\treturn PercentileOfSorted(SortCopy(input), percent)\n}", "func getHistogramSamples(name string,\n\tlabels []*prometheus_models.LabelPair,\n\ttimestampMs int64,\n\th *prometheus_models.Histogram,\n\tentity string,\n) []Sample {\n\tsamples := make([]Sample, len(h.GetBucket())*2+2)\n\tsamples[0] = Sample{\n\t\tname: name + \"_count\",\n\t\tlabels: labels,\n\t\ttimestampMs: timestampMs,\n\t\tvalue: strconv.FormatUint(h.GetSampleCount(), 10),\n\t\tentity: entity,\n\t}\n\tsamples[1] = Sample{\n\t\tname: name + \"_sum\",\n\t\tlabels: labels,\n\t\ttimestampMs: timestampMs,\n\t\tvalue: strconv.FormatFloat(h.GetSampleSum(), 'E', -1, 64),\n\t\tentity: entity,\n\t}\n\tfor i, b := range h.GetBucket() {\n\t\tsamples[i+2] = Sample{\n\t\t\tname: fmt.Sprintf(\"%s_bucket_%d_le\", name, i),\n\t\t\tlabels: labels,\n\t\t\ttimestampMs: timestampMs,\n\t\t\tvalue: strconv.FormatFloat(b.GetUpperBound(), 'E', -1, 64),\n\t\t\tentity: entity,\n\t\t}\n\t\tsamples[i+3] = Sample{\n\t\t\tname: fmt.Sprintf(\"%s_bucket_%d_count\", name, i),\n\t\t\tlabels: labels,\n\t\t\ttimestampMs: timestampMs,\n\t\t\tvalue: strconv.FormatUint(b.GetCumulativeCount(), 10),\n\t\t\tentity: entity,\n\t\t}\n\t}\n\treturn samples\n}", "func (hist *Histogram) WriteTo(w io.Writer) (int64, error) {\n\twritten, err := hist.WriteStatsTo(w)\n\tif err != nil {\n\t\treturn written, err\n\t}\n\n\t// TODO: use consistently single unit instead of multiple\n\tmaxCountLength := 3\n\tfor i := range hist.Bins {\n\t\tx := (int)(math.Ceil(math.Log10(float64(hist.Bins[i].Count + 1))))\n\t\tif x > maxCountLength {\n\t\t\tmaxCountLength = x\n\t\t}\n\t}\n\n\tvar n int\n\tfor _, bin := range hist.Bins {\n\t\tif bin.andAbove {\n\t\t\tn, err = fmt.Fprintf(w, \" %10v+[%[2]*[3]v] \", time.Duration(round(bin.Start, 3)), maxCountLength, bin.Count)\n\t\t} else {\n\t\t\tn, err = fmt.Fprintf(w, \" %10v [%[2]*[3]v] \", time.Duration(round(bin.Start, 3)), maxCountLength, bin.Count)\n\t\t}\n\n\t\twritten += int64(n)\n\t\tif err != nil {\n\t\t\treturn written, err\n\t\t}\n\n\t\twidth := float64(hist.Width) * bin.Width\n\t\tfrac := width - math.Trunc(width)\n\n\t\tn, err = io.WriteString(w, strings.Repeat(\"█\", int(width)))\n\t\twritten += int64(n)\n\t\tif err != nil {\n\t\t\treturn written, err\n\t\t}\n\n\t\tif frac > 0.5 {\n\t\t\tn, err = io.WriteString(w, `▌`)\n\t\t\twritten += int64(n)\n\t\t\tif err != nil {\n\t\t\t\treturn written, err\n\t\t\t}\n\t\t}\n\n\t\tn, err = fmt.Fprintf(w, \"\\n\")\n\t\twritten += int64(n)\n\t\tif err != nil {\n\t\t\treturn written, err\n\t\t}\n\t}\n\treturn written, nil\n}", "func (c *Context) Histogram(stat string, value float64) {\n\tfor _, sink := range c.sinks {\n\t\tsink.Histogram(c, stat, value)\n\t}\n}", "func histHelper(expFormat string, labels ...interface{}) *metrics.Histogram {\n\treturn metrics.GetOrCreateHistogram(fmt.Sprintf(expFormat, labels...))\n}", "func (r RetCalc) PercentilePath(percentile float64) Path {\n\tix := int(float64(r.N) * percentile)\n\treturn r.all_paths[ix]\n}", "func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: sample.H.Count,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func (collector *atlassianUPMCollector) Collect(ch chan<- prometheus.Metric) {\n\tstartTime := time.Now()\n\tlog.Debug(\"Collect start\")\n\n\tlog.Debug(\"create request object\")\n\treq, err := http.NewRequest(\"GET\", baseURL, nil)\n\tif err != nil {\n\t\tlog.Error(\"http.NewRequest returned an error:\", err)\n\t}\n\n\tlog.Debug(\"create Basic auth string from argument passed\")\n\tbearer = \"Basic \" + *token\n\n\tlog.Debug(\"add authorization header to the request\")\n\treq.Header.Add(\"Authorization\", bearer)\n\n\tlog.Debug(\"add content type to the request\")\n\treq.Header.Add(\"content-type\", \"application/json\")\n\n\tlog.Debug(\"make request... get back a response\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\t\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 0, *fqdn)\n\t\tlog.Warn(\"http.DefaultClient.Do returned an error:\", err, \" return from Collect\")\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\tlog.Debug(\"response status code: \", resp.StatusCode)\n\t}\n\n\tlog.Debug(\"set metric atlassian_upm_rest_url_up\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMUpMetric, prometheus.GaugeValue, 1, *fqdn)\n\n\tvar allPlugins restPlugins\n\tif resp.StatusCode == 200 {\n\t\tlog.Debug(\"get all plugins\")\n\t\tallPlugins = plugins(resp)\n\n\t\t// return user-installed plugins if argument passed\n\t\tif *userInstalled {\n\t\t\tlog.Debug(\"-user-installed found\")\n\t\t\tallPlugins = userInstalledPlugins(allPlugins)\n\t\t}\n\n\t\t// plugins have the ability to be installed, but disabled, this will remove them if disabled\n\t\tif *dropDisabled {\n\t\t\tlog.Debug(\"-drop-disabled found\")\n\t\t\tallPlugins = dropDisabledPlugins(allPlugins)\n\t\t}\n\n\t\t// Jira specific\n\t\t// some plugins maintained by Jira have an additional element, this gives the option to drop those plugins\n\t\tif *dropJiraSoftware {\n\t\t\tlog.Debug(\"-drop-jira-software found\")\n\t\t\tallPlugins = dropJiraSoftwarePlugins(allPlugins)\n\t\t}\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range allPlugins.Plugins {\n\n\t\t\tlog.Debug(\"creating plugin metric for: \" + plugin.Name)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMPlugins,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\t0,\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tif resp.StatusCode == 200 && *checkUpdates {\n\t\tlog.Debug(\"get remaining plugins available info\")\n\t\tavailablePluginsMap := getAvailablePluginInfo(allPlugins)\n\n\t\tlog.Debug(\"range over values in response, add each as metric with labels\")\n\t\tfor _, plugin := range availablePluginsMap {\n\t\t\tavailableUpdate := false\n\n\t\t\tverInstalled, err := version.NewVersion(plugin.InstalledVersion)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning plugin installed into version object\")\n\t\t\t}\n\n\t\t\tverAvailable, err := version.NewVersion(plugin.Version)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"error turning available plugin into version object\")\n\t\t\t}\n\n\t\t\tif verInstalled.LessThan(verAvailable) {\n\t\t\t\tlog.Debug(\"plugin: \", plugin.Name, \", is currently running: \", plugin.InstalledVersion, \", and can be upgraded to: \", plugin.Version)\n\t\t\t\tavailableUpdate = true\n\t\t\t}\n\n\t\t\tlog.Debug(\"creating plugin version metric for: \", plugin.Name, \", with Key: \", plugin.Key)\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tcollector.atlassianUPMVersionsMetric,\n\t\t\t\tprometheus.GaugeValue,\n\t\t\t\tboolToFloat(availableUpdate),\n\t\t\t\tstring(plugin.Name),\n\t\t\t\tstring(plugin.Key),\n\t\t\t\tstring(plugin.Version),\n\t\t\t\tstring(plugin.InstalledVersion),\n\t\t\t\tstrconv.FormatBool(plugin.Enabled), // convert bool to string for the 'enabled' value in the labels\n\t\t\t\tstrconv.FormatBool(plugin.UserInstalled),\n\t\t\t\t*fqdn,\n\t\t\t)\n\t\t}\n\t}\n\n\tfinishTime := time.Now()\n\telapsedTime := finishTime.Sub(startTime)\n\tlog.Debug(\"set the duration metric\")\n\tch <- prometheus.MustNewConstMetric(collector.atlassianUPMTimeMetric, prometheus.GaugeValue, elapsedTime.Seconds(), *fqdn)\n\n\tlog.Debug(\"Collect finished\")\n}", "func getHistogram(src [][3]int, size float64, pixels *[HistSize][3]float64, hist *[HistSize]float64) {\n\tvar ind, r, g, b, i int\n\tvar inr, ing, inb int\n\n\tfor i = range src {\n\t\tr = src[i][0]\n\t\tg = src[i][1]\n\t\tb = src[i][2]\n\n\t\tinr = r >> Shift\n\t\ting = g >> Shift\n\t\tinb = b >> Shift\n\n\t\tind = (inr << (2 * HistBits)) + (ing << HistBits) + inb\n\t\tpixels[ind][0], pixels[ind][1], pixels[ind][2] = float64(r), float64(g), float64(b)\n\t\thist[ind]++\n\t}\n\n\t// normalize weight by the number of pixels in the image\n\tfor i = 0; i < HistSize; i++ {\n\t\thist[i] /= size\n\t}\n}", "func ConvertOtelHistogramDataPoints(\n\tdataPoints pmetric.HistogramDataPointSlice,\n\tname string,\n\tunit string,\n\tscale float64,\n) []*aggregationDatum {\n\tdatums := make([]*aggregationDatum, 0, dataPoints.Len())\n\tfor i := 0; i < dataPoints.Len(); i++ {\n\t\tdp := dataPoints.At(i)\n\t\tattrs := dp.Attributes()\n\t\tstorageResolution := checkHighResolution(&attrs)\n\t\taggregationInterval := getAggregationInterval(&attrs)\n\t\tdimensions := ConvertOtelDimensions(attrs)\n\t\tad := aggregationDatum{\n\t\t\tMetricDatum: cloudwatch.MetricDatum{\n\t\t\t\tDimensions: dimensions,\n\t\t\t\tMetricName: aws.String(name),\n\t\t\t\tUnit: aws.String(unit),\n\t\t\t\tTimestamp: aws.Time(dp.Timestamp().AsTime()),\n\t\t\t\tStorageResolution: aws.Int64(storageResolution),\n\t\t\t},\n\t\t\taggregationInterval: aggregationInterval,\n\t\t}\n\t\t// Assume function pointer is valid.\n\t\tad.distribution = distribution.NewDistribution()\n\t\tad.distribution.ConvertFromOtel(dp, unit)\n\t\tdatums = append(datums, &ad)\n\t}\n\treturn datums\n}", "func (te *TelemetryEmitter) emitSummary(metric Metric, timestamp time.Time) error {\n\tsummary, ok := metric.value.(*dto.Summary)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown summary metric type for %q: %T\", metric.name, metric.value)\n\t}\n\n\tvar results error\n\tmetricName := metric.name + \".percentiles\"\n\tquantiles := summary.GetQuantile()\n\tfor _, q := range quantiles {\n\t\t// translate to percentiles\n\t\tp := q.GetQuantile() * 100.0\n\t\tif p < 0.0 || p > 100.0 {\n\t\t\terr := fmt.Errorf(\"invalid percentile `%g` for %s: must be in range [0.0, 100.0]\", p, metric.name)\n\t\t\tif results == nil {\n\t\t\t\tresults = err\n\t\t\t} else {\n\t\t\t\tresults = fmt.Errorf(\"%v: %w\", err, results)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpercentileAttrs := copyAttrs(metric.attributes)\n\t\tpercentileAttrs[\"percentile\"] = p\n\t\tte.harvester.RecordMetric(telemetry.Gauge{\n\t\t\tName: metricName,\n\t\t\tAttributes: percentileAttrs,\n\t\t\tValue: q.GetValue(),\n\t\t\tTimestamp: timestamp,\n\t\t})\n\t}\n\treturn results\n}", "func ParseHistogram(scale string, histo *dto.Histogram) (buckets HistogramBuckets, err error) {\n\tif histo == nil {\n\t\treturn nil, errors.New(\"nil Histogram\")\n\t}\n\n\ttotal := *histo.SampleCount\n\tn := len(histo.Bucket)\n\n\tbuckets = make(HistogramBuckets, n+1)\n\tbuckets[n] = HistogramBucket{\n\t\tScale: scale,\n\t\tUpperBound: math.MaxFloat64,\n\t\tCount: total,\n\t}\n\tfor idx, bv := range histo.Bucket {\n\t\tbuckets[idx] = HistogramBucket{\n\t\t\tScale: scale,\n\t\t\tUpperBound: *bv.UpperBound,\n\t\t\tCount: *bv.CumulativeCount,\n\t\t}\n\t}\n\tfor idx := n; idx > 0; idx-- { // start from last, end at second to last\n\t\t// convert cumulative count to per-bucket count\n\t\tbuckets[idx].Count = buckets[idx].Count - buckets[idx-1].Count\n\t\t// use previous bucket upper bound as lower bound\n\t\tbuckets[idx].LowerBound = buckets[idx-1].UpperBound\n\t}\n\n\tsort.Sort(HistogramBuckets(buckets))\n\treturn buckets, nil\n}", "func (it *emptyIterator) AtHistogram() (int64, *histogram.Histogram) { return 0, nil }", "func funcHistogramSum(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: sample.H.Sum,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func percentile(data []float64) (p25 float64, p75 float64) {\n\n\tN := float64(len(data))\n\tloc25 := int(.25 * N)\n\tloc75 := int(.75 * N)\n\tsafeData := make([]float64, len(data))\n\tcopy(safeData, data)\n\tsort.Float64s(safeData)\n\n\treturn safeData[loc25], safeData[loc75]\n}", "func (h *sizeHistogram) toMap() map[string]uint64 {\n\tres := make(map[string]uint64, dataUsageBucketLen)\n\tfor i, count := range h {\n\t\tres[ObjectsHistogramIntervals[i].name] = count\n\t}\n\treturn res\n}", "func TestPercentile(t *testing.T) {\n\ttables := []struct{\n\t\tvals []int // input slice\n\t\tpercentile float64 // percentile value\n\t}{\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t0},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t10},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t20},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t30},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t40},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t50},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t60},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t70},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t80},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t90},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t100},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t92},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t95},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t99},\n\t}\n\n\tfor _, tt := range tables {\n\t\tperc, _ := Percentile(tt.vals, tt.percentile)\n\t\tfmt.Println(perc)\n\t}\n}", "func (s *fseEncoder) Histogram() *[256]uint32 {\n\treturn &s.count\n}", "func Percentile(k float64, arrays ...float64) (float64, error) {\n\n\t// Check if k is a Non Numeric\n\tif math.IsNaN(k) {\n\t\treturn 0.0, errors.New(\"#VALUE!\t-\tOccurred because the supplied value of k is non-numeric\")\n\t}\n\n\tif len(arrays) == 0 || (k < 0 || k > 100) {\n\t\treturn 0.0, errors.New(\"#NUM!\t-\tOccurred because the supplied value of k is less than 0 or greater than 100 or the array is empty\")\n\t}\n\n\t// Reorder them from the smallest to the largest\n\tsort.Sort(SmallNums(arrays))\n\n\t// n = \\left \\lceil \\frac{P}{100} \\times N \\right \\rceil\n\n\tn := (k / 100) * float64(len(arrays))\n\n\tmathlib.Round(n, 0)\n\n\treturn arrays[int(n)], nil\n}", "func NewPercentilesAxis() *Axis {\n\taxis := NewAxis()\n\taxis.Transform = NewPercentileTransform(5)\n\taxis.Ticks = ManualTicks{\n\t\t{Value: 0, Label: \"0\"},\n\t\t{Value: 0.25, Label: \"25\"},\n\t\t{Value: 0.5, Label: \"50\"},\n\t\t{Value: 0.75, Label: \"75\"},\n\t\t{Value: 0.9, Label: \"90\"},\n\t\t{Value: 0.99, Label: \"99\"},\n\t\t{Value: 0.999, Label: \"99.9\"},\n\t\t{Value: 0.9999, Label: \"99.99\"},\n\t\t{Value: 0.99999, Label: \"99.999\"}}\n\treturn axis\n}", "func (it *pushdownSeriesIterator) AtHistogram() (int64, *histogram.Histogram) {\n\tpanic(\"not implemented\")\n}", "func getTabularMetric(c *gin.Context) {\n\tparams, err := parseMetricParams(c)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tparams.Start, _ = bi.GetRoundedTime(params.Start, params.Granularity)\n\n\tr, err := getRangeInGranularities(params.Start, params.End, params.Granularity)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tif r > 10000 {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": \"Too many results to tabulate\",\n\t\t})\n\t\treturn\n\t}\n\n\tinput, err := getDataOverRange(mongoSession, biModule.Rules[params.RuleIndex],\n\t\tparams.Granularity, params.Start, params.End, params.Value)\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tdataArray := make([]bson.M, 0)\n\tfor i := 0; i < len(input); i++ {\n\t\tvar ticks int\n\t\tinputStartTime, ok := input[i][\"start\"].(time.Time)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tswitch params.Granularity {\n\t\tcase bi.Monthly:\n\t\t\tticks = 12\n\t\tcase bi.Daily:\n\t\t\tswitch inputStartTime.Month() {\n\t\t\tcase time.April:\n\t\t\t\tfallthrough\n\t\t\tcase time.June:\n\t\t\t\tfallthrough\n\t\t\tcase time.September:\n\t\t\t\tfallthrough\n\t\t\tcase time.November:\n\t\t\t\tticks = 30\n\t\t\tcase time.February:\n\t\t\t\tticks = 28 // TODO: account for leap years\n\t\t\tdefault:\n\t\t\t\tticks = 31\n\t\t\t}\n\t\tcase bi.Hourly:\n\t\t\tticks = 24\n\t\tdefault:\n\t\t\tticks = 60\n\t\t}\n\n\t\tgranularityField, err := getGranularityField(params.Granularity)\n\t\tif err != nil {\n\t\t\tc.JSON(400, gin.H{\n\t\t\t\t\"error\": \"Not a valid time granularity\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tdataField, ok := input[i][granularityField].(bson.M)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor j := 0; j < ticks; j++ {\n\t\t\tindex := j\n\t\t\tif params.Granularity == bi.Monthly ||\n\t\t\t\tparams.Granularity == bi.Daily {\n\t\t\t\t// days and months start on 1, not 0\n\t\t\t\tindex = j + 1\n\t\t\t}\n\t\t\tval := convert.ToFloat64(dataField[strconv.Itoa(index)], 0)\n\t\t\tcTime, _ := addGranularitiesToTime(inputStartTime, params.Granularity, j)\n\n\t\t\tif cTime.Before(params.Start) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif cTime.After(params.End) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdataArray = append(dataArray, bson.M{\n\t\t\t\t\"value\": val,\n\t\t\t\t\"time\": cTime.Format(timeLayout),\n\t\t\t})\n\t\t}\n\t}\n\n\tc.IndentedJSON(200, gin.H{\n\t\t\"data\": dataArray,\n\t})\n\n}", "func (ms SummaryValueAtPercentile) Value() float64 {\n\treturn (*ms.orig).Value\n}", "func NewPercentiles(label string, values []float64) *Percentiles {\n\tvalues = append(values[:0:0], values...)\n\tsort.Float64s(values)\n\n\tpoints := make([]Point, 0, len(values))\n\n\tmultiplier := 1 / float64(len(values)+1)\n\tfor i, v := range values {\n\t\tvar p Point\n\t\tp.X = float64(i+1) * multiplier\n\t\tp.Y = v\n\t\tpoints = append(points, p)\n\t}\n\n\treturn &Percentiles{\n\t\tLabel: label,\n\t\tData: points,\n\t}\n}", "func (m *Metrics) Data() (*Data, error) {\n\tvar (\n\t\ttotalResponseTime float64\n\t\tmaxTime float64\n\t\tminTime = math.MaxFloat64\n\t\tbufsize = len(m.requests)\n\t\tpercentiledTime = make(percentiledTimeMap)\n\t)\n\tm.m.RLock()\n\tdefer m.m.RUnlock()\n\tfor _, v := range m.requests {\n\t\ttotalResponseTime += v\n\n\t\tif minTime > v {\n\t\t\tminTime = v\n\t\t}\n\t\tif maxTime < v {\n\t\t\tmaxTime = v\n\t\t}\n\t}\n\n\tfor _, p := range percents {\n\t\tvar err error\n\t\tpercentiledTime[p], err = m.requests.Percentile(float64(p))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstatusCount := make(statusCountMap)\n\tfor _, status := range httpStatuses {\n\t\tstatusCount[status] = atomic.LoadInt64(&m.statusCount[status])\n\t}\n\n\treturn &Data{\n\t\tRequest: RequestData{\n\t\t\tCount: atomic.LoadInt64(&m.count),\n\t\t\tStatusCount: statusCount,\n\t\t},\n\t\tResponse: ResponseData{\n\t\t\tMaxTime: maxTime,\n\t\t\tMinTime: minTime,\n\t\t\tAverageTime: totalResponseTime / float64(bufsize),\n\t\t\tPercentiledTime: percentiledTime,\n\t\t},\n\t}, nil\n}", "func (stats *ConnPoolStats) Export(ch chan<- prometheus.Metric) {\n\tch <- prometheus.MustNewConstMetric(syncClientConnectionsDesc, prometheus.GaugeValue, stats.SyncClientConnections)\n\tch <- prometheus.MustNewConstMetric(numAScopedConnectionsDesc, prometheus.GaugeValue, stats.ASScopedConnections)\n\tch <- prometheus.MustNewConstMetric(totalInUseDesc, prometheus.GaugeValue, stats.TotalInUse)\n\tch <- prometheus.MustNewConstMetric(totalAvailableDesc, prometheus.GaugeValue, stats.TotalAvailable)\n\tch <- prometheus.MustNewConstMetric(totalCreatedDesc, prometheus.CounterValue, stats.TotalCreated)\n}", "func (cm *customMetrics) AddHistogram(\n\tnamespace, subsystem, name, help, internalKey string,\n\tconstLabels prometheus.Labels, buckets []float64) {\n\n\tcm.histograms[internalKey] = promauto.NewHistogram(prometheus.HistogramOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t\tHelp: help,\n\t\tConstLabels: constLabels,\n\t\tBuckets: buckets,\n\t})\n}", "func handleHist(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tmessages, err := h.Hist(r.FormValue(\"from\"), r.FormValue(\"to\"))\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tjson.NewEncoder(w).Encode(map[string]interface{}{\"code\": http.StatusInternalServerError, \"message\": err.Error()})\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(messages)\n}", "func (m *ServerMetrics) histHelper(expFormat string, labels ...interface{}) *metrics.Histogram {\n\treturn histHelper(fmt.Sprintf(expFormat, labels...))\n}", "func (a *LogsApiService) GetLogHistogramData(ctx _context.Context) ApiGetLogHistogramDataRequest {\n\treturn ApiGetLogHistogramDataRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *Collector) Transform(allStats *NodeStatsResponse) (metrics []*exportertools.Metric) {\n for _, stats := range allStats.Nodes {\n // GC Stats\n for _, gcstats := range stats.JVM.GC.Collectors {\n metrics = append(metrics, c.ConvertToMetric(\"jvm_gc_collection_seconds_count\",\n float64(gcstats.CollectionCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_gc_collection_seconds_sum\",\n float64(gcstats.CollectionTime / 1000),\n \"COUNTER\",\n nil))\n }\n\n // Breaker stats\n for _, bstats := range stats.Breakers {\n metrics = append(metrics, c.ConvertToMetric(\"breakers_estimated_size_bytes\",\n float64(bstats.EstimatedSize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"breakers_limit_size_bytes\",\n float64(bstats.LimitSize),\n \"GAUGE\",\n nil))\n }\n\n // Thread Pool stats\n for pool, pstats := range stats.ThreadPool {\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_completed_count\",\n float64(pstats.Completed),\n \"COUNTER\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_rejected_count\",\n float64(pstats.Rejected),\n \"COUNTER\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_active_count\",\n float64(pstats.Active),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_threads_count\",\n float64(pstats.Threads),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_largest_count\",\n float64(pstats.Largest),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n\n metrics = append(metrics, c.ConvertToMetric(\"thread_pool_queue_count\",\n float64(pstats.Queue),\n \"GAUGE\",\n map[string]string{\"type\": pool}))\n }\n\n // JVM Memory Stats\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_committed_bytes\",\n float64(stats.JVM.Mem.HeapCommitted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_used_bytes\",\n float64(stats.JVM.Mem.HeapUsed),\n \"GAUGE\",\n nil))\n\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_max_bytes\",\n float64(stats.JVM.Mem.HeapMax),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_committed_bytes\",\n float64(stats.JVM.Mem.NonHeapCommitted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"jvm_memory_used_bytes\",\n float64(stats.JVM.Mem.NonHeapUsed),\n \"GAUGE\",\n nil))\n\n // Indices Stats)\n metrics = append(metrics, c.ConvertToMetric(\"indices_fielddata_memory_size_bytes\",\n float64(stats.Indices.FieldData.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_fielddata_evictions\",\n float64(stats.Indices.FieldData.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_filter_cache_memory_size_bytes\",\n float64(stats.Indices.FilterCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_filter_cache_evictions\",\n float64(stats.Indices.FilterCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_query_cache_memory_size_bytes\",\n float64(stats.Indices.QueryCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_query_cache_evictions\",\n float64(stats.Indices.QueryCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_request_cache_memory_size_bytes\",\n float64(stats.Indices.QueryCache.MemorySize),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_request_cache_evictions\",\n float64(stats.Indices.QueryCache.Evictions),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_docs\",\n float64(stats.Indices.Docs.Count),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_docs_deleted\",\n float64(stats.Indices.Docs.Deleted),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_segments_memory_bytes\",\n float64(stats.Indices.Segments.Memory),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_segments_count\",\n float64(stats.Indices.Segments.Count),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_store_size_bytes\",\n float64(stats.Indices.Store.Size),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_store_throttle_time_ms_total\",\n float64(stats.Indices.Store.ThrottleTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_flush_total\",\n float64(stats.Indices.Flush.Total),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_flush_time_ms_total\",\n float64(stats.Indices.Flush.Time),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_indexing_index_time_ms_total\",\n float64(stats.Indices.Indexing.IndexTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_indexing_index_total\",\n float64(stats.Indices.Indexing.IndexTotal),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total_time_ms_total\",\n float64(stats.Indices.Merges.TotalTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total_size_bytes_total\",\n float64(stats.Indices.Merges.TotalSize),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_merges_total\",\n float64(stats.Indices.Merges.Total),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_refresh_total_time_ms_total\",\n float64(stats.Indices.Refresh.TotalTime),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"indices_refresh_total\",\n float64(stats.Indices.Refresh.Total),\n \"COUNTER\",\n nil))\n\n // Transport Stats)\n metrics = append(metrics, c.ConvertToMetric(\"transport_rx_packets_total\",\n float64(stats.Transport.RxCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_rx_size_bytes_total\",\n float64(stats.Transport.RxSize),\n \"COUNTER\",\n nil))\n\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_tx_packets_total\",\n float64(stats.Transport.TxCount),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"transport_tx_size_bytes_total\",\n float64(stats.Transport.TxSize),\n \"COUNTER\",\n nil))\n\n // Process Stats)\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_percent\",\n float64(stats.Process.CPU.Percent),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_resident_size_bytes\",\n float64(stats.Process.Memory.Resident),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_share_size_bytes\",\n float64(stats.Process.Memory.Share),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_mem_virtual_size_bytes\",\n float64(stats.Process.Memory.TotalVirtual),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_open_files_count\",\n float64(stats.Process.OpenFD),\n \"GAUGE\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.Total / 1000),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.Sys / 1000),\n \"COUNTER\",\n nil))\n\n metrics = append(metrics, c.ConvertToMetric(\"process_cpu_time_seconds_sum\",\n float64(stats.Process.CPU.User / 1000),\n \"COUNTER\",\n nil))\n\n }\n\n return metrics\n}", "func CreateDescribeHistogramRequest() (request *DescribeHistogramRequest) {\n\trequest = &DescribeHistogramRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"aegis\", \"2016-11-11\", \"DescribeHistogram\", \"vipaegis\", \"openAPI\")\n\treturn\n}", "func (h *Histogram) Transfer(src *Histogram) {\n\tif src.Count == 0 {\n\t\treturn\n\t}\n\tif h.Count == 0 {\n\t\th.CopyFrom(src)\n\t\tsrc.Reset()\n\t\treturn\n\t}\n\th.copyHDataFrom(src)\n\th.Counter.Transfer(&src.Counter)\n\tsrc.Reset()\n}", "func (m *Metrics) Histogram(name, help string, buckets []float64) prometheus.Histogram {\n\thistogram := prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tNamespace: m.config.Namespace,\n\t\tName: name,\n\t\tHelp: help,\n\t\tBuckets: buckets,\n\t})\n\n\tprometheus.MustRegister(histogram)\n\n\treturn histogram\n}", "func (a *Client) HistogramAbsolute(params *HistogramAbsoluteParams, authInfo runtime.ClientAuthInfoWriter) (*HistogramAbsoluteOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewHistogramAbsoluteParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"histogramAbsolute\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/search/universal/absolute/histogram\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &HistogramAbsoluteReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*HistogramAbsoluteOK), nil\n\n}", "func ServeQuantiles(w http.ResponseWriter, r *http.Request) {\n\tvar data quantileReq\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tval, ok := registry[data.ID]\n\tif !ok {\n\t\tlog.Println(\"/quantiles \", data.ID, \" not found\")\n\t\tfmt.Fprintf(w, \"ID not found\")\n\t} else {\n\t\tsketch := (*val).Sketch(data.Kvs, data.Time)\n\t\tqs := Quantile(sketch, data.Quants)\n\t\tlog.Println(\"/quantiles\", data.ID, qs)\n\t\tfmt.Fprintf(w, \"%v\", qs)\n\t}\n\n}", "func HistogramSummary(scope *Scope, tag tf.Output, values tf.Output) (summary tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"HistogramSummary\",\n\t\tInput: []tf.Input{\n\t\t\ttag, values,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() // To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n if err := e.scrape(ch); err != nil {\n\t\tlog.Infof(\"Error scraping tinystats: %s\", err)\n\t}\n e.ipv4QueryA.Collect(ch)\n e.ipv4QueryNS.Collect(ch)\n e.ipv4QueryCNAME.Collect(ch)\n e.ipv4QuerySOA.Collect(ch)\n e.ipv4QueryPTR.Collect(ch)\n e.ipv4QueryHINFO.Collect(ch)\n e.ipv4QueryMX.Collect(ch)\n e.ipv4QueryTXT.Collect(ch)\n e.ipv4QueryRP.Collect(ch)\n e.ipv4QuerySIG.Collect(ch)\n e.ipv4QueryKEY.Collect(ch)\n e.ipv4QueryAAAA.Collect(ch)\n e.ipv4QueryAXFR.Collect(ch)\n e.ipv4QueryANY.Collect(ch)\n e.ipv4QueryTOTAL.Collect(ch)\n e.ipv4QueryOTHER.Collect(ch)\n e.ipv4QueryNOTAUTH.Collect(ch)\n e.ipv4QueryNOTIMPL.Collect(ch)\n e.ipv4QueryBADCLASS.Collect(ch)\n e.ipv4QueryNOQUERY.Collect(ch)\n\n e.ipv6QueryA.Collect(ch)\n e.ipv6QueryNS.Collect(ch)\n e.ipv6QueryCNAME.Collect(ch)\n e.ipv6QuerySOA.Collect(ch)\n e.ipv6QueryPTR.Collect(ch)\n e.ipv6QueryHINFO.Collect(ch)\n e.ipv6QueryMX.Collect(ch)\n e.ipv6QueryTXT.Collect(ch)\n e.ipv6QueryRP.Collect(ch)\n e.ipv6QuerySIG.Collect(ch)\n e.ipv6QueryKEY.Collect(ch)\n e.ipv6QueryAAAA.Collect(ch)\n e.ipv6QueryAXFR.Collect(ch)\n e.ipv6QueryANY.Collect(ch)\n e.ipv6QueryTOTAL.Collect(ch)\n e.ipv6QueryOTHER.Collect(ch)\n e.ipv6QueryNOTAUTH.Collect(ch)\n e.ipv6QueryNOTIMPL.Collect(ch)\n e.ipv6QueryBADCLASS.Collect(ch)\n e.ipv6QueryNOQUERY.Collect(ch)\n\n\treturn\n}", "func makeQuantiles(m *dto.Metric) map[string]interface{} {\n\tfields := make(map[string]interface{})\n\tfor _, q := range m.GetSummary().Quantile {\n\t\tif !math.IsNaN(q.GetValue()) {\n\t\t\t//nolint:unconvert // Conversion may be needed for float64 https://github.com/mdempsky/unconvert/issues/40\n\t\t\tfields[fmt.Sprint(q.GetQuantile())] = float64(q.GetValue())\n\t\t}\n\t}\n\treturn fields\n}", "func (a *DefaultApiService) ListHistograms(ctx _context.Context, localVarOptionals *ListHistogramsOpts) (Histograms, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Histograms\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/histograms\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Id.IsSet() {\n\t\tt:=localVarOptionals.Id.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotId.IsSet() {\n\t\tt:=localVarOptionals.NotId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Title.IsSet() {\n\t\tlocalVarQueryParams.Add(\"title\", parameterToString(localVarOptionals.Title.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Body.IsSet() {\n\t\tlocalVarQueryParams.Add(\"body\", parameterToString(localVarOptionals.Body.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Text.IsSet() {\n\t\tlocalVarQueryParams.Add(\"text\", parameterToString(localVarOptionals.Text.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.TranslationsEnTitle.IsSet() {\n\t\tlocalVarQueryParams.Add(\"translations.en.title\", parameterToString(localVarOptionals.TranslationsEnTitle.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.TranslationsEnBody.IsSet() {\n\t\tlocalVarQueryParams.Add(\"translations.en.body\", parameterToString(localVarOptionals.TranslationsEnBody.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.TranslationsEnText.IsSet() {\n\t\tlocalVarQueryParams.Add(\"translations.en.text\", parameterToString(localVarOptionals.TranslationsEnText.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.LinksPermalink.IsSet() {\n\t\tt:=localVarOptionals.LinksPermalink.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"links.permalink[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"links.permalink[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotLinksPermalink.IsSet() {\n\t\tt:=localVarOptionals.NotLinksPermalink.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!links.permalink[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!links.permalink[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Language.IsSet() {\n\t\tt:=localVarOptionals.Language.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"language[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"language[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotLanguage.IsSet() {\n\t\tt:=localVarOptionals.NotLanguage.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!language[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!language[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PublishedAtStart.IsSet() {\n\t\tlocalVarQueryParams.Add(\"published_at.start\", parameterToString(localVarOptionals.PublishedAtStart.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PublishedAtEnd.IsSet() {\n\t\tlocalVarQueryParams.Add(\"published_at.end\", parameterToString(localVarOptionals.PublishedAtEnd.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CategoriesTaxonomy.IsSet() {\n\t\tlocalVarQueryParams.Add(\"categories.taxonomy\", parameterToString(localVarOptionals.CategoriesTaxonomy.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CategoriesConfident.IsSet() {\n\t\tlocalVarQueryParams.Add(\"categories.confident\", parameterToString(localVarOptionals.CategoriesConfident.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CategoriesId.IsSet() {\n\t\tt:=localVarOptionals.CategoriesId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"categories.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"categories.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotCategoriesId.IsSet() {\n\t\tt:=localVarOptionals.NotCategoriesId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!categories.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!categories.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CategoriesLabel.IsSet() {\n\t\tt:=localVarOptionals.CategoriesLabel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"categories.label[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"categories.label[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotCategoriesLabel.IsSet() {\n\t\tt:=localVarOptionals.NotCategoriesLabel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!categories.label[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!categories.label[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.CategoriesLevel.IsSet() {\n\t\tt:=localVarOptionals.CategoriesLevel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"categories.level[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"categories.level[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotCategoriesLevel.IsSet() {\n\t\tt:=localVarOptionals.NotCategoriesLevel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!categories.level[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!categories.level[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesId.IsSet() {\n\t\tt:=localVarOptionals.EntitiesId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesId.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesLinksWikipedia.IsSet() {\n\t\tt:=localVarOptionals.EntitiesLinksWikipedia.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.links.wikipedia[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.links.wikipedia[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesLinksWikipedia.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesLinksWikipedia.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.links.wikipedia[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.links.wikipedia[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesLinksWikidata.IsSet() {\n\t\tt:=localVarOptionals.EntitiesLinksWikidata.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.links.wikidata[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.links.wikidata[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesLinksWikidata.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesLinksWikidata.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.links.wikidata[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.links.wikidata[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesTypes.IsSet() {\n\t\tt:=localVarOptionals.EntitiesTypes.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.types[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.types[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesTypes.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesTypes.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.types[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.types[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesStockTickers.IsSet() {\n\t\tt:=localVarOptionals.EntitiesStockTickers.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.stock_tickers[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.stock_tickers[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesBodyStockTickers.IsSet() {\n\t\tt:=localVarOptionals.EntitiesBodyStockTickers.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.body.stock_tickers[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.body.stock_tickers[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesSurfaceFormsText.IsSet() {\n\t\tt:=localVarOptionals.EntitiesSurfaceFormsText.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.surface_forms.text[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.surface_forms.text[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesSurfaceFormsText.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesSurfaceFormsText.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.surface_forms.text[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.surface_forms.text[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesTitleSurfaceFormsText.IsSet() {\n\t\tlocalVarQueryParams.Add(\"entities.title.surface_forms.text[]\", parameterToString(localVarOptionals.EntitiesTitleSurfaceFormsText.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesTitleSurfaceFormsText.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesTitleSurfaceFormsText.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.title.surface_forms.text[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.title.surface_forms.text[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EntitiesBodySurfaceFormsText.IsSet() {\n\t\tt:=localVarOptionals.EntitiesBodySurfaceFormsText.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"entities.body.surface_forms.text[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"entities.body.surface_forms.text[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotEntitiesBodySurfaceFormsText.IsSet() {\n\t\tt:=localVarOptionals.NotEntitiesBodySurfaceFormsText.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!entities.body.surface_forms.text[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!entities.body.surface_forms.text[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SentimentTitlePolarity.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sentiment.title.polarity\", parameterToString(localVarOptionals.SentimentTitlePolarity.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSentimentTitlePolarity.IsSet() {\n\t\tlocalVarQueryParams.Add(\"!sentiment.title.polarity\", parameterToString(localVarOptionals.NotSentimentTitlePolarity.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SentimentBodyPolarity.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sentiment.body.polarity\", parameterToString(localVarOptionals.SentimentBodyPolarity.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSentimentBodyPolarity.IsSet() {\n\t\tlocalVarQueryParams.Add(\"!sentiment.body.polarity\", parameterToString(localVarOptionals.NotSentimentBodyPolarity.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesCountMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.count.min\", parameterToString(localVarOptionals.MediaImagesCountMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesCountMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.count.max\", parameterToString(localVarOptionals.MediaImagesCountMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesWidthMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.width.min\", parameterToString(localVarOptionals.MediaImagesWidthMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesWidthMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.width.max\", parameterToString(localVarOptionals.MediaImagesWidthMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesHeightMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.height.min\", parameterToString(localVarOptionals.MediaImagesHeightMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesHeightMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.height.max\", parameterToString(localVarOptionals.MediaImagesHeightMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesContentLengthMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.content_length.min\", parameterToString(localVarOptionals.MediaImagesContentLengthMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesContentLengthMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.images.content_length.max\", parameterToString(localVarOptionals.MediaImagesContentLengthMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaImagesFormat.IsSet() {\n\t\tt:=localVarOptionals.MediaImagesFormat.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"media.images.format[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"media.images.format[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotMediaImagesFormat.IsSet() {\n\t\tt:=localVarOptionals.NotMediaImagesFormat.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!media.images.format[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!media.images.format[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaVideosCountMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.videos.count.min\", parameterToString(localVarOptionals.MediaVideosCountMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.MediaVideosCountMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"media.videos.count.max\", parameterToString(localVarOptionals.MediaVideosCountMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.AuthorId.IsSet() {\n\t\tt:=localVarOptionals.AuthorId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"author.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"author.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotAuthorId.IsSet() {\n\t\tt:=localVarOptionals.NotAuthorId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!author.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!author.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.AuthorName.IsSet() {\n\t\tlocalVarQueryParams.Add(\"author.name\", parameterToString(localVarOptionals.AuthorName.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotAuthorName.IsSet() {\n\t\tlocalVarQueryParams.Add(\"!author.name\", parameterToString(localVarOptionals.NotAuthorName.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceId.IsSet() {\n\t\tt:=localVarOptionals.SourceId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceId.IsSet() {\n\t\tt:=localVarOptionals.NotSourceId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceName.IsSet() {\n\t\tt:=localVarOptionals.SourceName.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.name[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.name[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceName.IsSet() {\n\t\tt:=localVarOptionals.NotSourceName.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.name[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.name[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceDomain.IsSet() {\n\t\tt:=localVarOptionals.SourceDomain.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.domain[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.domain[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceDomain.IsSet() {\n\t\tt:=localVarOptionals.NotSourceDomain.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.domain[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.domain[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceLocationsCountry.IsSet() {\n\t\tt:=localVarOptionals.SourceLocationsCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.locations.country[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.locations.country[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceLocationsCountry.IsSet() {\n\t\tt:=localVarOptionals.NotSourceLocationsCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.locations.country[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.locations.country[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceLocationsState.IsSet() {\n\t\tt:=localVarOptionals.SourceLocationsState.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.locations.state[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.locations.state[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceLocationsState.IsSet() {\n\t\tt:=localVarOptionals.NotSourceLocationsState.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.locations.state[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.locations.state[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceLocationsCity.IsSet() {\n\t\tt:=localVarOptionals.SourceLocationsCity.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.locations.city[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.locations.city[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceLocationsCity.IsSet() {\n\t\tt:=localVarOptionals.NotSourceLocationsCity.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.locations.city[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.locations.city[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceScopesCountry.IsSet() {\n\t\tt:=localVarOptionals.SourceScopesCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.scopes.country[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.scopes.country[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceScopesCountry.IsSet() {\n\t\tt:=localVarOptionals.NotSourceScopesCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.scopes.country[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.scopes.country[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceScopesState.IsSet() {\n\t\tt:=localVarOptionals.SourceScopesState.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.scopes.state[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.scopes.state[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceScopesState.IsSet() {\n\t\tt:=localVarOptionals.NotSourceScopesState.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.scopes.state[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.scopes.state[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceScopesCity.IsSet() {\n\t\tt:=localVarOptionals.SourceScopesCity.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.scopes.city[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.scopes.city[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceScopesCity.IsSet() {\n\t\tt:=localVarOptionals.NotSourceScopesCity.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.scopes.city[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.scopes.city[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceScopesLevel.IsSet() {\n\t\tt:=localVarOptionals.SourceScopesLevel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.scopes.level[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.scopes.level[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotSourceScopesLevel.IsSet() {\n\t\tt:=localVarOptionals.NotSourceScopesLevel.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!source.scopes.level[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!source.scopes.level[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceLinksInCountMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"source.links_in_count.min\", parameterToString(localVarOptionals.SourceLinksInCountMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceLinksInCountMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"source.links_in_count.max\", parameterToString(localVarOptionals.SourceLinksInCountMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceRankingsAlexaRankMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"source.rankings.alexa.rank.min\", parameterToString(localVarOptionals.SourceRankingsAlexaRankMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceRankingsAlexaRankMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"source.rankings.alexa.rank.max\", parameterToString(localVarOptionals.SourceRankingsAlexaRankMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SourceRankingsAlexaCountry.IsSet() {\n\t\tt:=localVarOptionals.SourceRankingsAlexaCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"source.rankings.alexa.country[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"source.rankings.alexa.country[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountFacebookMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.facebook.min\", parameterToString(localVarOptionals.SocialSharesCountFacebookMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountFacebookMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.facebook.max\", parameterToString(localVarOptionals.SocialSharesCountFacebookMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountGooglePlusMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.google_plus.min\", parameterToString(localVarOptionals.SocialSharesCountGooglePlusMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountGooglePlusMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.google_plus.max\", parameterToString(localVarOptionals.SocialSharesCountGooglePlusMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountLinkedinMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.linkedin.min\", parameterToString(localVarOptionals.SocialSharesCountLinkedinMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountLinkedinMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.linkedin.max\", parameterToString(localVarOptionals.SocialSharesCountLinkedinMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountRedditMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.reddit.min\", parameterToString(localVarOptionals.SocialSharesCountRedditMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SocialSharesCountRedditMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"social_shares_count.reddit.max\", parameterToString(localVarOptionals.SocialSharesCountRedditMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Clusters.IsSet() {\n\t\tt:=localVarOptionals.Clusters.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"clusters[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"clusters[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Aql.IsSet() {\n\t\tlocalVarQueryParams.Add(\"aql\", parameterToString(localVarOptionals.Aql.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.AqlDefaultField.IsSet() {\n\t\tlocalVarQueryParams.Add(\"aql_default_field\", parameterToString(localVarOptionals.AqlDefaultField.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Query.IsSet() {\n\t\tlocalVarQueryParams.Add(\"query\", parameterToString(localVarOptionals.Query.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.IntervalStart.IsSet() {\n\t\tlocalVarQueryParams.Add(\"interval.start\", parameterToString(localVarOptionals.IntervalStart.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.IntervalEnd.IsSet() {\n\t\tlocalVarQueryParams.Add(\"interval.end\", parameterToString(localVarOptionals.IntervalEnd.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.IntervalWidth.IsSet() {\n\t\tlocalVarQueryParams.Add(\"interval.width\", parameterToString(localVarOptionals.IntervalWidth.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Field.IsSet() {\n\t\tlocalVarQueryParams.Add(\"field\", parameterToString(localVarOptionals.Field.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/xml\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-AYLIEN-NewsAPI-Application-ID\"] = key\n\t\t}\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-AYLIEN-NewsAPI-Application-Key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 422 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func PercentilesPlot() {\n\tfmt.Println(\"Percentiles Plot (percentiles.svg)\")\n\n\tbench := hrtime.NewBenchmark(N)\n\tfor bench.Next() {\n\t\ttime.Sleep(5000 * time.Nanosecond)\n\t}\n\n\tseconds := plot.DurationToSeconds(bench.Laps())\n\n\tp := plot.New()\n\tp.Margin = plot.R(5, 0, 0, 5)\n\tp.X = plot.NewPercentilesAxis()\n\tp.AddGroup(\n\t\tplot.NewGrid(),\n\t\tplot.NewGizmo(),\n\t\tplot.NewPercentiles(\"\", seconds),\n\t\tplot.NewTickLabels(),\n\t)\n\n\tsvg := plot.NewSVG(800, 300)\n\tp.Draw(svg)\n\tioutil.WriteFile(\"percentiles.svg\", svg.Bytes(), 0755)\n}", "func mockStatsHistogram(id int64, values []types.Datum, repeat int64, tp *types.FieldType) *statistics.Histogram {\n\tndv := len(values)\n\thistogram := statistics.NewHistogram(id, int64(ndv), 0, 0, tp, ndv, 0)\n\tfor i := 0; i < ndv; i++ {\n\t\thistogram.AppendBucket(&values[i], &values[i], repeat*int64(i+1), repeat)\n\t}\n\treturn histogram\n}", "func (self *Metric) Export() X {\n\n\tvar x int\n\tlabels := make([]string, len(self.Labels))\n\tfor label, _ := range self.Labels {\n\t\tlabels[x] = label.Label\n\t\tx++\n\t}\n\n\treturn X{\n\t\tT: self.Time,\n\t\tL: labels,\n\t\tV: self.Value,\n\t\tC: self.Config.Name,\n\t}\n}" ]
[ "0.6288955", "0.6219894", "0.59967005", "0.5796037", "0.5748225", "0.55667174", "0.55348176", "0.55191565", "0.5503497", "0.54889184", "0.5461652", "0.54608554", "0.54565984", "0.5451762", "0.53931814", "0.53746253", "0.534492", "0.5307157", "0.52786535", "0.52745324", "0.52635944", "0.524569", "0.5242743", "0.5223241", "0.51965505", "0.51788193", "0.5164275", "0.5157791", "0.5152943", "0.51360077", "0.5127332", "0.50842404", "0.50724643", "0.5066026", "0.5065346", "0.5042155", "0.5031077", "0.5027104", "0.5004313", "0.49917057", "0.49666515", "0.4961929", "0.49549088", "0.4949388", "0.4920237", "0.49131212", "0.48877877", "0.48861545", "0.48840258", "0.48820087", "0.48724622", "0.48721865", "0.48595798", "0.4845694", "0.48324746", "0.48313546", "0.48197955", "0.48181304", "0.48096597", "0.4803938", "0.47754797", "0.4771073", "0.47684118", "0.47553584", "0.47526652", "0.47453612", "0.47438964", "0.47391888", "0.47382063", "0.47302803", "0.47251424", "0.47251385", "0.47232485", "0.47230047", "0.4721693", "0.4718236", "0.470958", "0.47061044", "0.46945515", "0.4680755", "0.46737725", "0.46679136", "0.46579495", "0.4655151", "0.4653355", "0.46514487", "0.4642906", "0.46399832", "0.4639383", "0.46379384", "0.4634571", "0.46118885", "0.46078846", "0.46023443", "0.45996496", "0.45904008", "0.45844707", "0.458219", "0.45801574", "0.4575645" ]
0.63686347
0
CalcPercentiles calculates the requested percentile and add them to the HistogramData. Potential TODO: sort or assume sorting and calculate all the percentiles in 1 pass (greater and greater values).
func (e *HistogramData) CalcPercentiles(percentiles []float64) *HistogramData { if e.Count == 0 { return e } for _, p := range percentiles { e.Percentiles = append(e.Percentiles, Percentile{p, e.CalcPercentile(p)}) } return e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *HistogramData) CalcPercentile(percentile float64) float64 {\n\tif len(e.Data) == 0 {\n\t\tlog.Errf(\"Unexpected call to CalcPercentile(%g) with no data\", percentile)\n\t\treturn 0\n\t}\n\tif percentile >= 100 {\n\t\treturn e.Max\n\t}\n\t// We assume Min is at least a single point so at least covers 1/Count %\n\tpp := 100. / float64(e.Count) // previous percentile\n\tif percentile <= pp {\n\t\treturn e.Min\n\t}\n\tfor _, cur := range e.Data {\n\t\tif percentile <= cur.Percent {\n\t\t\treturn cur.Start + (percentile-pp)/(cur.Percent-pp)*(cur.End-cur.Start)\n\t\t}\n\t\tpp = cur.Percent\n\t}\n\treturn e.Max // not reached\n}", "func (t *TimerSnapshot) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func (s *UniformSample) Percentiles(ps []float64) []float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentiles(s.values, ps)\n}", "func (t *StandardTimer) Percentiles(ps []float64) []float64 {\n\treturn t.histogram.Percentiles(ps)\n}", "func Percentile(input []float64, percent float64) float64 {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\treturn PercentileOfSorted(SortCopy(input), percent)\n}", "func (h *PCPHistogram) Percentile(p float64) int64 { return h.h.ValueAtQuantile(p) }", "func percentile(data []float64) (p25 float64, p75 float64) {\n\n\tN := float64(len(data))\n\tloc25 := int(.25 * N)\n\tloc75 := int(.75 * N)\n\tsafeData := make([]float64, len(data))\n\tcopy(safeData, data)\n\tsort.Float64s(safeData)\n\n\treturn safeData[loc25], safeData[loc75]\n}", "func (t *TimerSnapshot) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func (NilTimer) Percentiles(ps []float64) []float64 {\n\treturn make([]float64, len(ps))\n}", "func NewPercentiles(label string, values []float64) *Percentiles {\n\tvalues = append(values[:0:0], values...)\n\tsort.Float64s(values)\n\n\tpoints := make([]Point, 0, len(values))\n\n\tmultiplier := 1 / float64(len(values)+1)\n\tfor i, v := range values {\n\t\tvar p Point\n\t\tp.X = float64(i+1) * multiplier\n\t\tp.Y = v\n\t\tpoints = append(points, p)\n\t}\n\n\treturn &Percentiles{\n\t\tLabel: label,\n\t\tData: points,\n\t}\n}", "func (c *Collector) Percentile(percent float64) float64 {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttargetCount := int(percent * float64(c.Count) / 100)\n\n\tcount := 0\n\tfor _, b := range c.Buckets {\n\t\tcount += b.Count\n\t\tif count >= targetCount {\n\t\t\treturn b.Max\n\t\t}\n\t}\n\n\treturn c.Max\n}", "func percentile(orderedObservations []float64, l int, p float64) float64 {\n\treturn orderedObservations[int(p*float64(l))]\n}", "func PercentileOfSorted(sortedInput []float64, percent float64) float64 {\n\tindex := (percent / 100.0) * float64(len(sortedInput))\n\tpercentile := float64(0)\n\ti := int(math.RoundToEven(index))\n\tif index == float64(int64(index)) {\n\t\tpercentile = (sortedInput[i-1] + sortedInput[i]) / 2.0\n\t} else {\n\t\tpercentile = sortedInput[i-1]\n\t}\n\n\treturn percentile\n}", "func Percentile(ts []Transaction, percent float64) float64 {\n\tSort(&ts)\n\ti := int(math.Floor(float64(len(ts)) * percent))\n\tvalue := ts[i].amount\n\treturn value\n}", "func computePercentile(array []float64, targetPercentile int) float64 {\n\tif len(array) == 0 {\n\t\tpanic(\"Cannot compute the percentile of an empty array\")\n\t}\n\tsort.Float64s(array)\n\tif targetPercentile == 100 {\n\t\treturn array[len(array)-1]\n\t}\n\tindexAsFloat, fractional := math.Modf((float64(len(array)) - 1.0) * (0.01 * float64(targetPercentile)))\n\tindex := int(indexAsFloat)\n\tif len(array) == index+1 {\n\t\treturn array[index]\n\t}\n\treturn array[index]*(1-fractional) + array[index+1]*fractional\n}", "func Percentile(k float64, arrays ...float64) (float64, error) {\n\n\t// Check if k is a Non Numeric\n\tif math.IsNaN(k) {\n\t\treturn 0.0, errors.New(\"#VALUE!\t-\tOccurred because the supplied value of k is non-numeric\")\n\t}\n\n\tif len(arrays) == 0 || (k < 0 || k > 100) {\n\t\treturn 0.0, errors.New(\"#NUM!\t-\tOccurred because the supplied value of k is less than 0 or greater than 100 or the array is empty\")\n\t}\n\n\t// Reorder them from the smallest to the largest\n\tsort.Sort(SmallNums(arrays))\n\n\t// n = \\left \\lceil \\frac{P}{100} \\times N \\right \\rceil\n\n\tn := (k / 100) * float64(len(arrays))\n\n\tmathlib.Round(n, 0)\n\n\treturn arrays[int(n)], nil\n}", "func (ms SummaryValueAtPercentile) Percentile() float64 {\n\treturn (*ms.orig).Percentile\n}", "func (m *MockHistogram) Percentile(percentile float64) float64 {\n\targs := m.Called(percentile)\n\treturn args.Get(0).(float64)\n}", "func (t *StandardTimer) Percentile(p float64) float64 {\n\treturn t.histogram.Percentile(p)\n}", "func (s *UniformSample) Percentile(p float64) float64 {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn gometrics.SamplePercentile(s.values, p)\n}", "func TestPercentile(t *testing.T) {\n\ttables := []struct{\n\t\tvals []int // input slice\n\t\tpercentile float64 // percentile value\n\t}{\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t0},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t10},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t20},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t30},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t40},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t50},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t60},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t70},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t80},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t90},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t100},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t92},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t95},\n\t\t{[]int{10, 8, 7, 6, 9, 3, 4, 5, 1, 2},\n\t\t\t99},\n\t}\n\n\tfor _, tt := range tables {\n\t\tperc, _ := Percentile(tt.vals, tt.percentile)\n\t\tfmt.Println(perc)\n\t}\n}", "func (s Sample) Percentile(pctile float64) float64 {\n\tif len(s.Xs) == 0 {\n\t\treturn math.NaN()\n\t} else if pctile <= 0 {\n\t\tmin, _ := s.Bounds()\n\t\treturn min\n\t} else if pctile >= 1 {\n\t\t_, max := s.Bounds()\n\t\treturn max\n\t}\n\n\tif !s.Sorted {\n\t\ts = *s.Copy().Sort()\n\t}\n\n\tN := float64(len(s.Xs))\n\tn := 1/3.0 + pctile*(N+1/3.0) // R8\n\tkf, frac := math.Modf(n)\n\tk := int(kf)\n\tif k <= 0 {\n\t\treturn s.Xs[0]\n\t} else if k >= len(s.Xs) {\n\t\treturn s.Xs[len(s.Xs)-1]\n\t}\n\treturn s.Xs[k-1] + frac*(s.Xs[k]-s.Xs[k-1])\n}", "func (preferences *ProductPreferences) GetPercentile(val float32) float32 {\r\n\t//TODO: change to bin search.\r\n\tfor i := len(preferences.Percentiles) - 1; i >= 0; i-- {\r\n\t\tif val > preferences.Percentiles[i] {\r\n\t\t\treturn float32(i+1) / float32(DistributionSize+1)\r\n\t\t}\r\n\t}\r\n\treturn 0\r\n}", "func (NilTimer) Percentile(p float64) float64 { return 0.0 }", "func (b BundledStates) Percentile(t time.Time, percentile int) time.Duration {\n\tif percentile > 100 || percentile <= 0 {\n\t\tpanic(fmt.Errorf(\"percentile %d is out of scope\", percentile))\n\t}\n\n\tages := []time.Duration{}\n\tfor _, age := range b.ages(t) {\n\t\tages = append(ages, age)\n\t}\n\n\tif len(ages) == 0 {\n\t\treturn 0\n\t}\n\n\tsort.Sort(ByDuration(ages))\n\n\tindex := int(math.Ceil(float64(percentile)*float64(len(ages))/100) - 1)\n\tif index >= len(ages) {\n\t\tpanic(fmt.Errorf(\"Index is out of range: %d/%d\", index, len(ages)))\n\t}\n\treturn ages[index]\n}", "func percentile(dps Series, args ...float64) (a float64) {\n\tp := args[0]\n\tvar x []float64\n\tfor _, v := range dps {\n\t\tx = append(x, float64(v))\n\t}\n\tsort.Float64s(x)\n\tif p <= 0 {\n\t\treturn x[0]\n\t}\n\tif p >= 1 {\n\t\treturn x[len(x)-1]\n\t}\n\ti := p * float64(len(x)-1)\n\ti = math.Ceil(i)\n\treturn x[int(i)]\n}", "func Percentile(by []string, percentile float64, input []*oproto.ValueStream) []*oproto.ValueStream {\n\toutput := []*oproto.ValueStream{{Variable: input[0].Variable}}\n\treturn output\n}", "func PercentilesFilter(percentiles []float64) Filter {\n\ts := make([]string, 0, len(percentiles))\n\tfor _, v := range percentiles {\n\t\ts = append(s, fmt.Sprintf(\"%v\", v))\n\t}\n\tj := strings.Join(s, \",\")\n\treturn Param(\"percentiles\", j)\n}", "func ParsePercentiles(percentiles string) ([]float64, error) {\n\tpercs := strings.Split(percentiles, \",\") // will make a size 1 array for empty input!\n\tres := make([]float64, 0, len(percs))\n\tfor _, pStr := range percs {\n\t\tpStr = strings.TrimSpace(pStr)\n\t\tif len(pStr) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tp, err := strconv.ParseFloat(pStr, 64)\n\t\tif err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres = append(res, p)\n\t}\n\tif len(res) == 0 {\n\t\treturn res, errors.New(\"list can't be empty\")\n\t}\n\tlog.LogVf(\"Will use %v for percentiles\", res)\n\treturn res, nil\n}", "func ReducePercentile(percentile float64) ReduceFunc {\n\treturn func(values []interface{}) interface{} {\n\t\tvar allValues []float64\n\n\t\tfor _, v := range values {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvals := v.([]interface{})\n\t\t\tfor _, v := range vals {\n\t\t\t\tswitch v.(type) {\n\t\t\t\tcase int64:\n\t\t\t\t\tallValues = append(allValues, float64(v.(int64)))\n\t\t\t\tcase float64:\n\t\t\t\t\tallValues = append(allValues, v.(float64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsort.Float64s(allValues)\n\t\tlength := len(allValues)\n\t\tindex := int(math.Floor(float64(length)*percentile/100.0+0.5)) - 1\n\n\t\tif index < 0 || index >= len(allValues) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn allValues[index]\n\t}\n}", "func funcHistogramQuantile(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tinVec := vals[1].(Vector)\n\n\tif enh.signatureToMetricWithBuckets == nil {\n\t\tenh.signatureToMetricWithBuckets = map[string]*metricWithBuckets{}\n\t} else {\n\t\tfor _, v := range enh.signatureToMetricWithBuckets {\n\t\t\tv.buckets = v.buckets[:0]\n\t\t}\n\t}\n\n\tvar histogramSamples []Sample\n\n\tfor _, sample := range inVec {\n\t\t// We are only looking for conventional buckets here. Remember\n\t\t// the histograms for later treatment.\n\t\tif sample.H != nil {\n\t\t\thistogramSamples = append(histogramSamples, sample)\n\t\t\tcontinue\n\t\t}\n\n\t\tupperBound, err := strconv.ParseFloat(\n\t\t\tsample.Metric.Get(model.BucketLabel), 64,\n\t\t)\n\t\tif err != nil {\n\t\t\t// Oops, no bucket label or malformed label value. Skip.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tcontinue\n\t\t}\n\t\tenh.lblBuf = sample.Metric.BytesWithoutLabels(enh.lblBuf, labels.BucketLabel)\n\t\tmb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]\n\t\tif !ok {\n\t\t\tsample.Metric = labels.NewBuilder(sample.Metric).\n\t\t\t\tDel(excludedLabels...).\n\t\t\t\tLabels()\n\n\t\t\tmb = &metricWithBuckets{sample.Metric, nil}\n\t\t\tenh.signatureToMetricWithBuckets[string(enh.lblBuf)] = mb\n\t\t}\n\t\tmb.buckets = append(mb.buckets, bucket{upperBound, sample.F})\n\n\t}\n\n\t// Now deal with the histograms.\n\tfor _, sample := range histogramSamples {\n\t\t// We have to reconstruct the exact same signature as above for\n\t\t// a conventional histogram, just ignoring any le label.\n\t\tenh.lblBuf = sample.Metric.Bytes(enh.lblBuf)\n\t\tif mb, ok := enh.signatureToMetricWithBuckets[string(enh.lblBuf)]; ok && len(mb.buckets) > 0 {\n\t\t\t// At this data point, we have conventional histogram\n\t\t\t// buckets and a native histogram with the same name and\n\t\t\t// labels. Do not evaluate anything.\n\t\t\t// TODO(beorn7): Issue a warning somehow.\n\t\t\tdelete(enh.signatureToMetricWithBuckets, string(enh.lblBuf))\n\t\t\tcontinue\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramQuantile(q, sample.H),\n\t\t})\n\t}\n\n\tfor _, mb := range enh.signatureToMetricWithBuckets {\n\t\tif len(mb.buckets) > 0 {\n\t\t\tenh.Out = append(enh.Out, Sample{\n\t\t\t\tMetric: mb.metric,\n\t\t\t\tF: bucketQuantile(q, mb.buckets),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn enh.Out\n}", "func guessPercentile(curValue uint64, newValue, count uint64, perc float32) uint64 {\n\tinertness := float64(count) / iterationsRequiredPerSecond\n\n\trequireGreater := rand.Float32() > perc\n\n\tif newValue > curValue {\n\t\tif requireGreater {\n\t\t\treturn curValue\n\t\t}\n\t} else {\n\t\tif !requireGreater {\n\t\t\treturn curValue\n\t\t}\n\t}\n\n\tif requireGreater {\n\t\tinertness *= float64(perc)\n\t} else {\n\t\tinertness *= float64(1 - perc)\n\t}\n\tupdatedValue := uint64((float64(curValue)*inertness + float64(newValue)) / (inertness + 1))\n\treturn updatedValue\n}", "func (p *Percentiles) Flush() ([]processorResult, bool) {\n\n\tsize := len(p.values)\n\tif size == 0 {\n\t\treturn nil, false\n\t}\n\n\tvar results []processorResult\n\tsort.Float64s(p.values)\n\n\tfor fcnName, percent := range p.percents {\n\t\trank := (percent / 100) * (float64(size) + 1)\n\t\tfloor := int(rank)\n\n\t\tif rank < 1 {\n\t\t\tresults = append(results, processorResult{fcnName, p.values[0]})\n\t\t} else if floor >= size {\n\t\t\tresults = append(results, processorResult{fcnName, p.values[size-1]})\n\t\t} else {\n\t\t\tfrac := rank - float64(floor)\n\t\t\tupper := floor + 1\n\t\t\tpercentile := p.values[floor-1] + frac*(p.values[upper-1]-p.values[floor-1])\n\t\t\tresults = append(results, processorResult{fcnName, percentile})\n\t\t}\n\t}\n\n\treturn results, true\n}", "func (ms SummaryValueAtPercentile) SetPercentile(v float64) {\n\t(*ms.orig).Percentile = v\n}", "func QuartileRange(values []float64) (float64, float64) {\n\tsorted := sortFloat64s(values)\n\treturn percentile_(sorted, 25.0), percentile_(sorted, 75.0)\n}", "func ProcessMetric(metric *Metric, flushDuration time.Duration, quantiles []int, logger Logger) {\n\tflushInterval := flushDuration / time.Second\n\n\tsort.Sort(metric.AllValues)\n\tswitch metric.MetricType {\n\tcase MetricTypeCounter:\n\t\tmetric.ValuesPerSecond = metric.LastValue / float64(flushInterval)\n\tcase MetricTypeGauge:\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\tcase MetricTypeSet:\n\t\tmetric.LastValue = float64(metric.AllValues.UniqueCount())\n\tcase MetricTypeTimer:\n\t\tmetric.MinValue, metric.MaxValue, _ = metric.AllValues.Minmax()\n\t\tmetric.MedianValue = metric.AllValues.Median()\n\t\tmetric.MeanValue = metric.AllValues.Mean()\n\t\tmetric.ValuesPerSecond = metric.TotalHits / float64(flushInterval)\n\n\t\tmetric.Quantiles = make([]MetricQuantile, 0)\n\t\tfor _, q := range quantiles {\n\t\t\tpercentile := float64(q) / float64(100)\n\t\t\tquantile := new(MetricQuantile)\n\t\t\tquantile.Quantile = q\n\n\t\t\t// Make calculations based on the desired quantile.\n\t\t\tquantile.Boundary = metric.AllValues.Quantile(percentile)\n\t\t\tfor _, value := range metric.AllValues {\n\t\t\t\tif value > quantile.Boundary {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tquantile.AllValues = append(quantile.AllValues, value)\n\t\t\t}\n\t\t\t_, quantile.Max, _ = quantile.AllValues.Minmax()\n\t\t\tquantile.Mean = quantile.AllValues.Mean()\n\t\t\tquantile.Median = quantile.AllValues.Median()\n\t\t\tquantile.Sum = quantile.AllValues.Sum()\n\t\t\tmetric.Quantiles = append(metric.Quantiles, *quantile)\n\t\t}\n\t}\n}", "func (fn *formulaFuncs) PERCENTILE(argsList *list.List) formulaArg {\n\tif argsList.Len() != 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"PERCENTILE requires 2 arguments\")\n\t}\n\tarray := argsList.Front().Value.(formulaArg).ToList()\n\tk := argsList.Back().Value.(formulaArg).ToNumber()\n\tif k.Type != ArgNumber {\n\t\treturn k\n\t}\n\tif k.Number < 0 || k.Number > 1 {\n\t\treturn newErrorFormulaArg(formulaErrorNA, formulaErrorNA)\n\t}\n\tvar numbers []float64\n\tfor _, arg := range array {\n\t\tif arg.Type == ArgError {\n\t\t\treturn arg\n\t\t}\n\t\tif arg.Type == ArgNumber {\n\t\t\tnumbers = append(numbers, arg.Number)\n\t\t}\n\t}\n\tcnt := len(numbers)\n\tsort.Float64s(numbers)\n\tidx := k.Number * (float64(cnt) - 1)\n\tbase := math.Floor(idx)\n\tif idx == base {\n\t\treturn newNumberFormulaArg(numbers[int(idx)])\n\t}\n\tnext := base + 1\n\tproportion := math.Nextafter(idx, idx) - base\n\treturn newNumberFormulaArg(numbers[int(base)] + ((numbers[int(next)] - numbers[int(base)]) * proportion))\n}", "func PercentilesPlot() {\n\tfmt.Println(\"Percentiles Plot (percentiles.svg)\")\n\n\tbench := hrtime.NewBenchmark(N)\n\tfor bench.Next() {\n\t\ttime.Sleep(5000 * time.Nanosecond)\n\t}\n\n\tseconds := plot.DurationToSeconds(bench.Laps())\n\n\tp := plot.New()\n\tp.Margin = plot.R(5, 0, 0, 5)\n\tp.X = plot.NewPercentilesAxis()\n\tp.AddGroup(\n\t\tplot.NewGrid(),\n\t\tplot.NewGizmo(),\n\t\tplot.NewPercentiles(\"\", seconds),\n\t\tplot.NewTickLabels(),\n\t)\n\n\tsvg := plot.NewSVG(800, 300)\n\tp.Draw(svg)\n\tioutil.WriteFile(\"percentiles.svg\", svg.Bytes(), 0755)\n}", "func (te *TelemetryEmitter) emitHistogram(metric Metric, timestamp time.Time) error {\n\thist, ok := metric.value.(*dto.Histogram)\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown histogram metric type for %q: %T\", metric.name, metric.value)\n\t}\n\n\tif m, ok := te.deltaCalculator.CountMetric(metric.name+\".sum\", metric.attributes, hist.GetSampleSum(), timestamp); ok {\n\t\tte.harvester.RecordMetric(m)\n\t}\n\n\tmetricName := metric.name + \".buckets\"\n\tbuckets := make(histogram.Buckets, 0, len(hist.Bucket))\n\tfor _, b := range hist.GetBucket() {\n\t\tupperBound := b.GetUpperBound()\n\t\tcount := float64(b.GetCumulativeCount())\n\t\tif !math.IsInf(upperBound, 1) {\n\t\t\tbucketAttrs := copyAttrs(metric.attributes)\n\t\t\tbucketAttrs[\"histogram.bucket.upperBound\"] = upperBound\n\t\t\tif m, ok := te.deltaCalculator.CountMetric(metricName, bucketAttrs, count, timestamp); ok {\n\t\t\t\tte.harvester.RecordMetric(m)\n\t\t\t}\n\t\t}\n\t\tbuckets = append(\n\t\t\tbuckets,\n\t\t\thistogram.Bucket{\n\t\t\t\tUpperBound: upperBound,\n\t\t\t\tCount: count,\n\t\t\t},\n\t\t)\n\t}\n\n\tvar results error\n\tmetricName = metric.name + \".percentiles\"\n\tfor _, p := range te.percentiles {\n\t\tv, err := histogram.Percentile(p, buckets)\n\t\tif err != nil {\n\t\t\tif results == nil {\n\t\t\t\tresults = err\n\t\t\t} else {\n\t\t\t\tresults = fmt.Errorf(\"%v: %w\", err, results)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tpercentileAttrs := copyAttrs(metric.attributes)\n\t\tpercentileAttrs[\"percentile\"] = p\n\t\tte.harvester.RecordMetric(telemetry.Gauge{\n\t\t\tName: metricName,\n\t\t\tAttributes: percentileAttrs,\n\t\t\tValue: v,\n\t\t\tTimestamp: timestamp,\n\t\t})\n\t}\n\n\treturn results\n}", "func NewPercentilesAxis() *Axis {\n\taxis := NewAxis()\n\taxis.Transform = NewPercentileTransform(5)\n\taxis.Ticks = ManualTicks{\n\t\t{Value: 0, Label: \"0\"},\n\t\t{Value: 0.25, Label: \"25\"},\n\t\t{Value: 0.5, Label: \"50\"},\n\t\t{Value: 0.75, Label: \"75\"},\n\t\t{Value: 0.9, Label: \"90\"},\n\t\t{Value: 0.99, Label: \"99\"},\n\t\t{Value: 0.999, Label: \"99.9\"},\n\t\t{Value: 0.9999, Label: \"99.99\"},\n\t\t{Value: 0.99999, Label: \"99.999\"}}\n\treturn axis\n}", "func HandlePercentile(w http.ResponseWriter, req *http.Request) {\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar numbers Numbers\n\n\terr := decoder.Decode(&numbers)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prevent division by zero\n\tperc := Percentile(numbers)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\n\tjsonRes, _ := json.Marshal(&Response{Result: perc})\n\n\tw.Write(jsonRes)\n}", "func (h *Histogram) Quantile(q float64) (float64, error) {\n\thist := testutil.Histogram{\n\t\t&dto.Histogram{\n\t\t\tBucket: []*dto.Bucket{},\n\t\t},\n\t}\n\n\tfor k, v := range h.Buckets {\n\t\tupper, err := strconv.ParseFloat(k, 64)\n\t\tif err != nil {\n\t\t\treturn math.MaxFloat64, err\n\t\t}\n\n\t\tcumulativeCount := uint64(v)\n\t\thist.Bucket = append(hist.Bucket, &dto.Bucket{\n\t\t\tCumulativeCount: &cumulativeCount,\n\t\t\tUpperBound: &upper,\n\t\t})\n\t}\n\n\t// hist.Quantile expected a slice of Buckets ordered by UpperBound\n\tsort.Slice(hist.Bucket, func(i, j int) bool {\n\t\treturn *hist.Bucket[i].UpperBound < *hist.Bucket[j].UpperBound\n\t})\n\n\treturn hist.Quantile(q), nil\n}", "func (res *Results) CalculatePct(pct int) float64 {\n slice := res.copyTook()\n\n l := len(slice)\n switch l {\n case 0:\n return float64(0)\n case 1:\n return slice[0]\n case 2:\n return slice[1]\n }\n\n index := int(math.Floor(((float64(l)/100)*float64(pct))+0.5) - 1)\n return slice[index]\n}", "func (src *prometheusMetricsSource) buildQuantiles(name string, m *dto.Metric, now int64, tags map[string]string) []*MetricPoint {\n\tvar result []*MetricPoint\n\tfor _, q := range m.GetSummary().Quantile {\n\t\tif !math.IsNaN(q.GetValue()) {\n\t\t\tpoint := src.metricPoint(name+\".\"+fmt.Sprint(q.GetQuantile()), float64(q.GetValue()), now, src.source, tags)\n\t\t\tresult = src.filterAppend(result, point)\n\t\t}\n\t}\n\tpoint := src.metricPoint(name+\".count\", float64(m.GetSummary().GetSampleCount()), now, src.source, tags)\n\tresult = src.filterAppend(result, point)\n\tpoint = src.metricPoint(name+\".sum\", float64(m.GetSummary().GetSampleSum()), now, src.source, tags)\n\tresult = src.filterAppend(result, point)\n\n\treturn result\n}", "func NewHistogram(nanoseconds []float64, opts *HistogramOptions) *Histogram {\n\tif opts.BinCount <= 0 {\n\t\tpanic(\"binCount must be larger than 0\")\n\t}\n\n\thist := &Histogram{}\n\thist.Width = 40\n\thist.Bins = make([]HistogramBin, opts.BinCount)\n\tif len(nanoseconds) == 0 {\n\t\treturn hist\n\t}\n\n\tnanoseconds = append(nanoseconds[:0:0], nanoseconds...)\n\tsort.Float64s(nanoseconds)\n\n\thist.Minimum = nanoseconds[0]\n\thist.Maximum = nanoseconds[len(nanoseconds)-1]\n\n\thist.Average = float64(0)\n\tfor _, x := range nanoseconds {\n\t\thist.Average += x\n\t}\n\thist.Average /= float64(len(nanoseconds))\n\n\tp := func(p float64) float64 {\n\t\ti := int(math.Round(p * float64(len(nanoseconds))))\n\t\tif i < 0 {\n\t\t\ti = 0\n\t\t}\n\t\tif i >= len(nanoseconds) {\n\t\t\ti = len(nanoseconds) - 1\n\t\t}\n\t\treturn nanoseconds[i]\n\t}\n\n\thist.P50, hist.P90, hist.P99, hist.P999, hist.P9999 = p(0.50), p(0.90), p(0.99), p(0.999), p(0.9999)\n\n\tclampMaximum := hist.Maximum\n\tif opts.ClampPercentile > 0 {\n\t\tclampMaximum = p(opts.ClampPercentile)\n\t}\n\tif opts.ClampMaximum > 0 {\n\t\tclampMaximum = opts.ClampMaximum\n\t}\n\n\tvar minimum, spacing float64\n\n\tif opts.NiceRange {\n\t\tminimum, spacing = calculateNiceSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t} else {\n\t\tminimum, spacing = calculateSteps(hist.Minimum, clampMaximum, opts.BinCount)\n\t}\n\n\tfor i := range hist.Bins {\n\t\thist.Bins[i].Start = spacing*float64(i) + minimum\n\t}\n\thist.Bins[0].Start = hist.Minimum\n\n\tfor _, x := range nanoseconds {\n\t\tk := int(float64(x-minimum) / spacing)\n\t\tif k < 0 {\n\t\t\tk = 0\n\t\t}\n\t\tif k >= opts.BinCount {\n\t\t\tk = opts.BinCount - 1\n\t\t\thist.Bins[k].andAbove = true\n\t\t}\n\t\thist.Bins[k].Count++\n\t}\n\n\tmaxBin := 0\n\tfor _, bin := range hist.Bins {\n\t\tif bin.Count > maxBin {\n\t\t\tmaxBin = bin.Count\n\t\t}\n\t}\n\n\tfor k := range hist.Bins {\n\t\tbin := &hist.Bins[k]\n\t\tbin.Width = float64(bin.Count) / float64(maxBin)\n\t}\n\n\treturn hist\n}", "func (ms SummaryDataPoint) ValueAtPercentiles() SummaryValueAtPercentileSlice {\n\treturn newSummaryValueAtPercentileSlice(&(*ms.orig).PercentileValues)\n}", "func (s *ModelLatencyThreshold) SetPercentile(v string) *ModelLatencyThreshold {\n\ts.Percentile = &v\n\treturn s\n}", "func (stat *Benchstat) ComputeStats() {\n\t// Discard outliers.\n\tvalues := stats.Sample{Xs: stat.Values}\n\tq1, q3 := values.Percentile(0.25), values.Percentile(0.75)\n\tlo, hi := q1-1.5*(q3-q1), q3+1.5*(q3-q1)\n\tfor _, value := range stat.Values {\n\t\tif lo <= value && value <= hi {\n\t\t\tstat.RValues = append(stat.RValues, value)\n\t\t}\n\t}\n\n\t// Compute statistics of remaining data.\n\tstat.Min, stat.Max = stats.Bounds(stat.RValues)\n\tstat.Mean = stats.Mean(stat.RValues)\n}", "func quantile(q float64, values vector.HeapByMaxValue) float64 {\n\tif len(values) == 0 {\n\t\treturn math.NaN()\n\t}\n\tif q < 0 {\n\t\treturn math.Inf(-1)\n\t}\n\tif q > 1 {\n\t\treturn math.Inf(+1)\n\t}\n\tsort.Sort(values)\n\n\tn := float64(len(values))\n\t// When the quantile lies between two samples,\n\t// we use a weighted average of the two samples.\n\trank := q * (n - 1)\n\n\tlowerIndex := math.Max(0, math.Floor(rank))\n\tupperIndex := math.Min(n-1, lowerIndex+1)\n\n\tweight := rank - math.Floor(rank)\n\treturn values[int(lowerIndex)].V*(1-weight) + values[int(upperIndex)].V*weight\n}", "func (digest *MergingDigest) Quantile(q float64) float64 {\n\tdigest.Compress()\n\tif len(digest.summary) == 0 || q < 0.0 || q > 1.0 {\n\t\treturn math.NaN()\n\t} else if len(digest.summary) == 1 {\n\t\treturn digest.summary[0].Mean\n\t}\n\tindex := float64(digest.count) * q\n\tsum := int64(1)\n\taMean := digest.summary[0].Mean\n\taIndex := float64(0)\n\tbMean := digest.summary[0].Mean\n\tbIndex := float64(sum) + float64(digest.summary[0].Count-1)*0.5\n\tfor i := 1; i < len(digest.summary); i++ {\n\t\tif index <= bIndex {\n\t\t\tbreak\n\t\t}\n\t\tsum += digest.summary[i-1].Count\n\t\taMean = bMean\n\t\taIndex = bIndex\n\t\tbMean = digest.summary[i].Mean\n\t\tbIndex = float64(sum) + float64(digest.summary[i].Count-1)*0.5\n\t}\n\tp := (index - aIndex) / (bIndex - aIndex)\n\treturn aMean*(1.0-p) + bMean*p\n}", "func quantile(vals []float64, q float64) float64 {\n\tlength := len(vals)\n\tif length == 0 {\n\t\treturn math.NaN()\n\t}\n\tindex := int(q * float64(length-1))\n\treturn vals[index]\n}", "func (s *Stats) CalculateCPUTimes() []CPUPercentages {\n\n percentages := make([]CPUPercentages, len(s.CPUInfo.PerCPUTimes))\n\n if len(s.CPUInfo.PrevCPUTimes) == 0 || len(s.CPUInfo.PerCPUTimes) == 0 {\n return percentages\n }\n\n var diff float64\n var total float64\n var prevTotal float64\n var prevStat cpu.TimesStat\n var cpuStat *CPUPercentages\n\n for i, t := range s.CPUInfo.PerCPUTimes {\n cpuStat = &percentages[i]\n prevStat = s.CPUInfo.PrevCPUTimes[i]\n\n total = t.User + t.System + t.Idle + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Guest + t.GuestNice + t.Stolen\n prevTotal = prevStat.User + prevStat.System + prevStat.Idle + prevStat.Nice + prevStat.Iowait + prevStat.Irq + prevStat.Softirq + prevStat.Steal + prevStat.Guest + prevStat.GuestNice + prevStat.Stolen\n\n diff = total - prevTotal\n\n cpuStat.CPU = t.CPU\n cpuStat.User = (t.User - prevStat.User) / diff * 100\n cpuStat.System = (t.System - prevStat.System) / diff * 100\n cpuStat.Idle = (t.Idle - prevStat.Idle) / diff * 100\n cpuStat.Nice = (t.Nice - prevStat.Nice) / diff * 100\n cpuStat.IOWait = (t.Iowait - prevStat.Iowait) / diff * 100\n cpuStat.IRQ = (t.Irq - prevStat.Irq) / diff * 100\n cpuStat.SoftIRQ = (t.Softirq - prevStat.Softirq) / diff * 100\n cpuStat.Steal = (t.Steal - prevStat.Steal) / diff * 100\n cpuStat.Guest = (t.Guest - prevStat.Guest) / diff * 100\n cpuStat.GuestNice = (t.GuestNice - prevStat.GuestNice) / diff * 100\n cpuStat.Stolen = (t.Stolen - prevStat.Stolen) / diff * 100\n cpuStat.Total = 100 * (diff - (t.Idle - prevStat.Idle)) / diff\n }\n\n return percentages\n}", "func calcTraceStats(trace []float64) (float64, float64, float64, float64, float64) {\n\tv := cleanCopy(trace)\n\tsort.Float64s(v)\n\tmean, stddev, _ := vec.MeanAndStdDev(v)\n\tn := len(v)\n\tq1 := 0.0\n\tq2 := 0.0\n\tq3 := 0.0\n\t// Calculate the quartiles, using Method 1: https://en.wikipedia.org/wiki/Quartile#Method_1\n\tif n > 1 {\n\t\todd := false\n\t\tq2, odd = median(v)\n\t\tq1 = q2\n\t\tq3 = q2\n\t\tif n > 2 {\n\t\t\tq1, _ = median(v[0 : n/2])\n\t\t\tif odd {\n\t\t\t\tq3, _ = median(v[n/2+1:])\n\t\t\t} else {\n\t\t\t\tq3, _ = median(v[n/2:])\n\t\t\t}\n\t\t}\n\t}\n\treturn mean, stddev, q1, q2, q3\n}", "func Quantile(p float64, xs []float64) float64 {\n\tif len(xs) == 0 {\n\t\tpanic(\"Quantile() second argument may not be empty\")\n\t}\n\tif len(xs) == 1 {\n\t\treturn xs[0]\n\t}\n\n\t// log.Printf(\"xs = %#v\\n\", xs)\n\t// log.Printf(\"p = %.2f\\n\", p)\n\tn := float64(len(xs))\n\t// log.Printf(\"n = %.2f\\n\", n)\n\n\t// parameters for \"Definition 8\" (which the paper recommends)\n\tm := (p + 1) / 3\n\t// log.Printf(\"m = %.2f\\n\", m)\n\n\t// equations based on the parameters\n\tj := math.Floor(p*n + m)\n\tg := p*n + m - j\n\tgamma := g\n\t// log.Printf(\"j = %.2f\\n\", j)\n\t// log.Printf(\"g = %.2f\\n\", g)\n\n\t// j is 1-based but xs is 0-based, so lookups subtract 1\n\tquantile := (1-gamma)*xs[int(j)-1] + gamma*xs[int(j)]\n\t// log.Printf(\"quantile = %.2f\\n\\n\", quantile)\n\treturn quantile\n}", "func makeQuantiles(m *dto.Metric) map[string]interface{} {\n\tfields := make(map[string]interface{})\n\tfor _, q := range m.GetSummary().Quantile {\n\t\tif !math.IsNaN(q.GetValue()) {\n\t\t\t//nolint:unconvert // Conversion may be needed for float64 https://github.com/mdempsky/unconvert/issues/40\n\t\t\tfields[fmt.Sprint(q.GetQuantile())] = float64(q.GetValue())\n\t\t}\n\t}\n\treturn fields\n}", "func (r RetCalc) PercentileIncome(percentile float64) float64 {\n\tincomes := r.RunIncomes()\n\tix := int(percentile * float64(r.N))\n\treturn incomes[ix]\n}", "func NewPercentileTransform(levels int) *PercentileTransform {\n\tbase := math.Pow(0.1, float64(levels))\n\treturn &PercentileTransform{\n\t\tlevels: levels,\n\t\tbase: base,\n\t\tmulbase: 1 / math.Log(base),\n\t}\n}", "func (s *Stats) CalculateTotalCPUTimes() []CPUPercentages {\n\n percentages := make([]CPUPercentages, len(s.CPUInfo.TotalTimes))\n\n if len(s.CPUInfo.PrevTotalTimes) == 0 || len(s.CPUInfo.TotalTimes) == 0 {\n return percentages\n }\n\n var diff float64\n var total float64\n var prevTotal float64\n var prevStat cpu.TimesStat\n var cpuStat *CPUPercentages\n\n for i, t := range s.CPUInfo.TotalTimes {\n cpuStat = &percentages[i]\n prevStat = s.CPUInfo.PrevTotalTimes[i]\n\n total = t.User + t.System + t.Idle + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Guest + t.GuestNice + t.Stolen\n prevTotal = prevStat.User + prevStat.System + prevStat.Idle + prevStat.Nice + prevStat.Iowait + prevStat.Irq + prevStat.Softirq + prevStat.Steal + prevStat.Guest + prevStat.GuestNice + prevStat.Stolen\n\n diff = total - prevTotal\n\n cpuStat.CPU = t.CPU\n cpuStat.User = (t.User - prevStat.User) / diff * 100\n cpuStat.System = (t.System - prevStat.System) / diff * 100\n cpuStat.Idle = (t.Idle - prevStat.Idle) / diff * 100\n cpuStat.Nice = (t.Nice - prevStat.Nice) / diff * 100\n cpuStat.IOWait = (t.Iowait - prevStat.Iowait) / diff * 100\n cpuStat.IRQ = (t.Irq - prevStat.Irq) / diff * 100\n cpuStat.SoftIRQ = (t.Softirq - prevStat.Softirq) / diff * 100\n cpuStat.Steal = (t.Steal - prevStat.Steal) / diff * 100\n cpuStat.Guest = (t.Guest - prevStat.Guest) / diff * 100\n cpuStat.GuestNice = (t.GuestNice - prevStat.GuestNice) / diff * 100\n cpuStat.Stolen = (t.Stolen - prevStat.Stolen) / diff * 100\n cpuStat.Total = 100 * (diff - (t.Idle - prevStat.Idle)) / diff\n }\n\n return percentages\n}", "func (h *Histogram) Print(out io.Writer, msg string, percentiles []float64) {\n\th.Export().CalcPercentiles(percentiles).Print(out, msg)\n}", "func (r RetCalc) PercentilePath(percentile float64) Path {\n\tix := int(float64(r.N) * percentile)\n\treturn r.all_paths[ix]\n}", "func BuildColumn(ctx context.Context, numBuckets, id int64, ndv int64, count int64, samples []types.Datum) (*Histogram, error) {\n\tif count == 0 {\n\t\treturn &Histogram{ID: id}, nil\n\t}\n\tsc := ctx.GetSessionVars().StmtCtx\n\terr := types.SortDatums(sc, samples)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\thg := &Histogram{\n\t\tID: id,\n\t\tNDV: ndv,\n\t\tBuckets: make([]Bucket, 1, numBuckets),\n\t}\n\tvaluesPerBucket := float64(count)/float64(numBuckets) + 1\n\n\t// As we use samples to build the histogram, the bucket number and repeat should multiply a factor.\n\tsampleFactor := float64(count) / float64(len(samples))\n\tndvFactor := float64(count) / float64(ndv)\n\tif ndvFactor > sampleFactor {\n\t\tndvFactor = sampleFactor\n\t}\n\tbucketIdx := 0\n\tvar lastCount int64\n\tfor i := int64(0); i < int64(len(samples)); i++ {\n\t\tcmp, err := hg.Buckets[bucketIdx].Value.CompareDatum(sc, samples[i])\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\ttotalCount := float64(i+1) * sampleFactor\n\t\tif cmp == 0 {\n\t\t\t// The new item has the same value as current bucket value, to ensure that\n\t\t\t// a same value only stored in a single bucket, we do not increase bucketIdx even if it exceeds\n\t\t\t// valuesPerBucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\tif float64(hg.Buckets[bucketIdx].Repeats) == ndvFactor {\n\t\t\t\thg.Buckets[bucketIdx].Repeats = int64(2 * sampleFactor)\n\t\t\t} else {\n\t\t\t\thg.Buckets[bucketIdx].Repeats += int64(sampleFactor)\n\t\t\t}\n\t\t} else if totalCount-float64(lastCount) <= valuesPerBucket {\n\t\t\t// The bucket still have room to store a new item, update the bucket.\n\t\t\thg.Buckets[bucketIdx].Count = int64(totalCount)\n\t\t\thg.Buckets[bucketIdx].Value = samples[i]\n\t\t\thg.Buckets[bucketIdx].Repeats = int64(ndvFactor)\n\t\t} else {\n\t\t\tlastCount = hg.Buckets[bucketIdx].Count\n\t\t\t// The bucket is full, store the item in the next bucket.\n\t\t\tbucketIdx++\n\t\t\thg.Buckets = append(hg.Buckets, Bucket{\n\t\t\t\tCount: int64(totalCount),\n\t\t\t\tValue: samples[i],\n\t\t\t\tRepeats: int64(ndvFactor),\n\t\t\t})\n\t\t}\n\t}\n\treturn hg, nil\n}", "func aggregateValues(previousResults []*keptnv2.SLIEvaluationResult, comparison *keptn.SLOComparison) (float64, bool) {\n\n\tif len(previousResults) == 0 {\n\t\t// if no comparison values are available, the evaluation passes\n\t\treturn 0, true\n\t}\n\tvar previousValues []float64\n\tfor _, val := range previousResults {\n\t\tif val.Value.Success == true {\n\t\t\t// always include\n\t\t\tpreviousValues = append(previousValues, val.Value.Value)\n\t\t}\n\t}\n\n\tif len(previousValues) == 0 {\n\t\t// if no comparison values are available, the evaluation passes\n\t\treturn 0, true\n\t}\n\tvar aggregatedValue float64\n\t// aggregate the previous values based on the passed aggregation function\n\tswitch comparison.AggregateFunction {\n\tcase \"avg\":\n\t\taggregatedValue = calculateAverage(previousValues)\n\tcase \"p50\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.5)\n\tcase \"p90\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.9)\n\tcase \"p95\":\n\t\taggregatedValue = calculatePercentile(sort.Float64Slice(previousValues), 0.95)\n\tdefault:\n\t\tbreak\n\t}\n\treturn aggregatedValue, false\n}", "func (a QuantileAggregator) Aggregate(values []float64) float64 {\n\tsort.Float64s(values)\n\treturn quantile(values, a.quantile)\n}", "func (hist *Histogram) Divide(n int) {\n\thist.Minimum /= float64(n)\n\thist.Average /= float64(n)\n\thist.Maximum /= float64(n)\n\n\thist.P50 /= float64(n)\n\thist.P90 /= float64(n)\n\thist.P99 /= float64(n)\n\thist.P999 /= float64(n)\n\thist.P9999 /= float64(n)\n\n\tfor i := range hist.Bins {\n\t\thist.Bins[i].Start /= float64(n)\n\t}\n}", "func BenchmarkTdigest_Quantile(b *testing.B) {\n\tfor _, size := range sizes {\n\t\tb.Run(fmt.Sprintf(\"size=%d\", size), func(b *testing.B) {\n\t\t\tfor _, source := range sources {\n\t\t\t\tb.Run(fmt.Sprintf(\"source=%s\", source.name), func(b *testing.B) {\n\t\t\t\t\tnums := numberArrayFromSource(source.source(), size)\n\t\t\t\t\tfor _, td := range digests {\n\t\t\t\t\t\tb.Run(fmt.Sprintf(\"digest=%s\", td.name), func(b *testing.B) {\n\t\t\t\t\t\t\tdigestImpl := td.digest()\n\t\t\t\t\t\t\taddNumbersToQuantile(digestImpl, nums)\n\t\t\t\t\t\t\tb.ReportAllocs()\n\t\t\t\t\t\t\tb.ResetTimer()\n\t\t\t\t\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\t\t\t\t\tfor _, q := range quantiles {\n\t\t\t\t\t\t\t\t\tdigestImpl.Quantile(q)\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 PERCENTILEOPT(wrapped interface{}, percentile interface{}) Expr {\n\tvar expr Expr\n\tswitch t := wrapped.(type) {\n\tcase *ptileOptimized:\n\t\texpr = &t.ptile\n\tdefault:\n\t\texpr = wrapped.(*ptile)\n\t}\n\treturn &ptileOptimized{Wrapped: expr, ptile: *expr.(*ptile), Percentile: exprFor(percentile)}\n}", "func (h *Histogram) Export() *HistogramData {\n\tvar res HistogramData\n\tres.Count = h.Counter.Count\n\tres.Min = h.Counter.Min\n\tres.Max = h.Counter.Max\n\tres.Sum = h.Counter.Sum\n\tres.Avg = h.Counter.Avg()\n\tres.StdDev = h.Counter.StdDev()\n\tmultiplier := h.Divider\n\toffset := h.Offset\n\t// calculate the last bucket index\n\tlastIdx := -1\n\tfor i := numBuckets - 1; i >= 0; i-- {\n\t\tif h.Hdata[i] > 0 {\n\t\t\tlastIdx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif lastIdx == -1 {\n\t\treturn &res\n\t}\n\n\t// previous bucket value:\n\tprev := histogramBucketValues[0]\n\tvar total int64\n\tctrTotal := float64(h.Count)\n\t// export the data of each bucket of the histogram\n\tfor i := 0; i <= lastIdx; i++ {\n\t\tif h.Hdata[i] == 0 {\n\t\t\t// empty bucket: skip it but update prev which is needed for next iter\n\t\t\tif i < numValues {\n\t\t\t\tprev = histogramBucketValues[i]\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tvar b Bucket\n\t\ttotal += int64(h.Hdata[i])\n\t\tif len(res.Data) == 0 {\n\t\t\t// First entry, start is min\n\t\t\tb.Start = h.Min\n\t\t} else {\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t}\n\t\tb.Percent = 100. * float64(total) / ctrTotal\n\t\tif i < numValues {\n\t\t\tcur := histogramBucketValues[i]\n\t\t\tb.End = multiplier*float64(cur) + offset\n\t\t\tprev = cur\n\t\t} else {\n\t\t\t// Last Entry\n\t\t\tb.Start = multiplier*float64(prev) + offset\n\t\t\tb.End = h.Max\n\t\t}\n\t\tb.Count = int64(h.Hdata[i])\n\t\tres.Data = append(res.Data, b)\n\t}\n\tres.Data[len(res.Data)-1].End = h.Max\n\treturn &res\n}", "func (_m *Reporter) Histogram(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 PERCENTILEOPT(wrapped interface{}, percentile interface{}) Expr {\n\tvar expr Expr\n\tswitch t := wrapped.(type) {\n\tcase *ptileOptimized:\n\t\texpr = t.wrapped\n\tdefault:\n\t\texpr = wrapped.(*ptile)\n\t}\n\treturn &ptileOptimized{Wrapped: expr, wrapped: expr.(*ptile), Percentile: exprFor(percentile)}\n}", "func (bench *Stopwatch) HistogramClamp(binCount int, min, max time.Duration) *Histogram {\n\tbench.mustBeCompleted()\n\n\tdurations := make([]time.Duration, 0, len(bench.spans))\n\tfor _, span := range bench.spans {\n\t\tduration := span.Duration()\n\t\tif duration < min {\n\t\t\tdurations = append(durations, min)\n\t\t} else {\n\t\t\tdurations = append(durations, duration)\n\t\t}\n\t}\n\n\topts := defaultOptions\n\topts.BinCount = binCount\n\topts.ClampMaximum = float64(max.Nanoseconds())\n\topts.ClampPercentile = 0\n\n\treturn NewDurationHistogram(durations, &opts)\n}", "func funcHistogramFraction(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tlower := vals[0].(Vector)[0].F\n\tupper := vals[1].(Vector)[0].F\n\tinVec := vals[2].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: histogramFraction(lower, upper, sample.H),\n\t\t})\n\t}\n\treturn enh.Out\n}", "func NewSummaryValueAtPercentileSlice() SummaryValueAtPercentileSlice {\n\torig := []*otlpmetrics.SummaryDataPoint_ValueAtPercentile(nil)\n\treturn SummaryValueAtPercentileSlice{&orig}\n}", "func newBatchHistogram(desc *Desc, buckets []float64, hasSum bool) *batchHistogram {\n\t// We need to remove -Inf values. runtime/metrics keeps them around.\n\t// But -Inf bucket should not be allowed for prometheus histograms.\n\tif buckets[0] == math.Inf(-1) {\n\t\tbuckets = buckets[1:]\n\t}\n\th := &batchHistogram{\n\t\tdesc: desc,\n\t\tbuckets: buckets,\n\t\t// Because buckets follows runtime/metrics conventions, there's\n\t\t// 1 more value in the buckets list than there are buckets represented,\n\t\t// because in runtime/metrics, the bucket values represent *boundaries*,\n\t\t// and non-Inf boundaries are inclusive lower bounds for that bucket.\n\t\tcounts: make([]uint64, len(buckets)-1),\n\t\thasSum: hasSum,\n\t}\n\th.init(h)\n\treturn h\n}", "func FirstQuartile(values []float64) float64 {\n\treturn Percentile(values, 25.0)\n}", "func (block *Block) CalculateHistogram(x, y int) {\n\n\tblock.Histogram = make([]int, 256)\n\tblock.Histogram.Generate(block)\n\tblock.Histogram.Clip(block.Picture.ClipLimit)\n\tblock.Histogram.Map(int(block.Picture.ColorMin), int(block.Picture.ColorMax), block.Picture.BlockWidth, block.Picture.BlockHeight)\n\n\t// Notify SubBlocks waiting for this block that we're ready!\n\tfor _, subBlock := range block.Notify {\n\t\tsubBlock.WaitGroup.Done()\n\t}\n\n}", "func (g *Graph) GetVertexPercentileAggregation(ctx context.Context, label string, field string, percents []float64) (*gripql.AggregationResult, error) {\n\treturn nil, errors.New(\"not implemented\")\n}", "func (g GumbelRight) Quantile(p float64) float64 {\n\tif p < 0 || 1 < p {\n\t\tpanic(badPercentile)\n\t}\n\treturn g.Mu - g.Beta*math.Log(-math.Log(p))\n}", "func mockStatsHistogram(id int64, values []types.Datum, repeat int64, tp *types.FieldType) *statistics.Histogram {\n\tndv := len(values)\n\thistogram := statistics.NewHistogram(id, int64(ndv), 0, 0, tp, ndv, 0)\n\tfor i := 0; i < ndv; i++ {\n\t\thistogram.AppendBucket(&values[i], &values[i], repeat*int64(i+1), repeat)\n\t}\n\treturn histogram\n}", "func (r *PresampledResampler) Quantile(q float64) float64 {\n\treturn quantile(r.sampleAggregates, q)\n}", "func Median(values []float64) float64 {\n\treturn Percentile(values, 50.0)\n}", "func (c CategoryCountsPercentage) Transform(tileData []*GeoImage) ([]float64, error) {\n\t// compute the raw counts\n\tcounts, err := computeCounts(&c.CategoryCounts, tileData)\n\tif err != nil {\n\t\treturn counts, err\n\t}\n\n\t// compute percentage in place\n\ttotalPixels := float64(tileData[0].XSize * tileData[0].YSize)\n\tfor i, count := range counts {\n\t\tcounts[i] = count / totalPixels\n\t}\n\n\t// compute each as a percentage of the total\n\treturn counts, nil\n}", "func (h *Histogram) FilterHistogramGtOpGeOp(op tree.ComparisonOperator, val int64) *Histogram {\n\tif op != tree.GT && op != tree.GE {\n\t\tpanic(\"filterHistogramGtOpGeOp called with operator \" + op.String())\n\t}\n\n\tif len(h.Buckets) == 0 {\n\t\treturn h\n\t}\n\n\tupperBound := h.GetUpperBound()\n\tvar newBuckets []Bucket\n\n\tnewLowerBound := val\n\tif op == tree.GE {\n\t\tnewLowerBound -= 1\n\t}\n\n\t// Iterate backwards through the buckets to avoid scanning buckets\n\t// that don't satisfy the predicate.\n\tfor i := len(h.Buckets) - 1; i >= 0; i-- {\n\t\tb := h.Buckets[i]\n\t\tif val >= upperBound {\n\t\t\tif val == upperBound && op == tree.GE {\n\t\t\t\tbuc := b\n\t\t\t\tbuc.NumRange = 0\n\t\t\t\tnewBuckets = append(newBuckets, buc)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tvar lowerBound int64\n\t\tif i == 0 {\n\t\t\tlowerBound = upperBound - 1\n\t\t} else {\n\t\t\tlowerBound = (int64)(*h.Buckets[i-1].UpperBound.(*tree.DInt))\n\t\t}\n\n\t\tif val > lowerBound {\n\t\t\t_, buc := b.splitBucket(newLowerBound, lowerBound)\n\t\t\tnewBuckets = append(newBuckets, buc)\n\t\t\tbreak\n\t\t}\n\n\t\tnewBuckets = append(newBuckets, b)\n\t\tupperBound = lowerBound\n\t}\n\n\t// Add a dummy bucket for the lower bound if needed.\n\tif len(newBuckets) > 0 && newBuckets[len(newBuckets)-1].NumRange != 0 {\n\t\tbuc := Bucket{UpperBound: makeDatum(newLowerBound)}\n\t\tnewBuckets = append(newBuckets, buc)\n\t}\n\n\t// Reverse the buckets so they are sorted in ascending order.\n\tfor i, j := 0, len(newBuckets)-1; i < j; i, j = i+1, j-1 {\n\t\tnewBuckets[i], newBuckets[j] = newBuckets[j], newBuckets[i]\n\t}\n\n\treturn h.filterHistogram(newBuckets)\n}", "func GetThreshold(scores map[int]float64, percentile float64) float64 {\n\t// Sort the scores into numerical order\n\tvalues := SortMap(scores)\n\n\tthresholdIndex := math.Round(float64(len(values)) * percentile / 100)\n\n\treturn values[int(thresholdIndex)]\n}", "func funcQuantileOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tq := vals[0].(Vector)[0].F\n\tel := vals[1].(Matrix)[0]\n\tif len(el.Floats) == 0 {\n\t\t// TODO(beorn7): The passed values only contain\n\t\t// histograms. quantile_over_time ignores histograms for now. If\n\t\t// there are only histograms, we have to return without adding\n\t\t// anything to enh.Out.\n\t\treturn enh.Out\n\t}\n\n\tvalues := make(vectorByValueHeap, 0, len(el.Floats))\n\tfor _, f := range el.Floats {\n\t\tvalues = append(values, Sample{F: f.F})\n\t}\n\treturn append(enh.Out, Sample{F: quantile(q, values)})\n}", "func (t *TileStats) calcStats(tile *tiling.Tile) {\n\tfor id, tr := range tile.Traces {\n\t\tptr := tr.(*types.PerfTrace)\n\t\tmean, stddev, q1, q2, q3 := calcTraceStats(ptr.Values)\n\t\tt.mutex.Lock()\n\t\tif _, ok := t.stats[id]; !ok {\n\t\t\tt.stats[id] = &TraceStats{}\n\t\t}\n\t\tst := t.stats[id]\n\t\tst.Mean = mean\n\t\tst.StdDev = stddev\n\t\tst.Q1 = q1\n\t\tst.Q2 = q2\n\t\tst.Q3 = q3\n\t\tt.mutex.Unlock()\n\t}\n}", "func TestGetCPUPercent(t *testing.T) {\n\t// setup the faking of `cpu.Percent()`\n\toldcpuPercent := cpuPercent\n\tcpuPercent = func(interval time.Duration, percpu bool) ([]float64, error) {\n\t\tret := []float64{100}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := 100\n\tactual, err := getCPUPercent()\n\n\tassert.NoError(t, err, \"`getCPUPercent()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUPercent` should be equal to --> 100\")\n\n\t// teardown\n\tcpuPercent = oldcpuPercent\n}", "func ParseHistogram(scale string, histo *dto.Histogram) (buckets HistogramBuckets, err error) {\n\tif histo == nil {\n\t\treturn nil, errors.New(\"nil Histogram\")\n\t}\n\n\ttotal := *histo.SampleCount\n\tn := len(histo.Bucket)\n\n\tbuckets = make(HistogramBuckets, n+1)\n\tbuckets[n] = HistogramBucket{\n\t\tScale: scale,\n\t\tUpperBound: math.MaxFloat64,\n\t\tCount: total,\n\t}\n\tfor idx, bv := range histo.Bucket {\n\t\tbuckets[idx] = HistogramBucket{\n\t\t\tScale: scale,\n\t\t\tUpperBound: *bv.UpperBound,\n\t\t\tCount: *bv.CumulativeCount,\n\t\t}\n\t}\n\tfor idx := n; idx > 0; idx-- { // start from last, end at second to last\n\t\t// convert cumulative count to per-bucket count\n\t\tbuckets[idx].Count = buckets[idx].Count - buckets[idx-1].Count\n\t\t// use previous bucket upper bound as lower bound\n\t\tbuckets[idx].LowerBound = buckets[idx-1].UpperBound\n\t}\n\n\tsort.Sort(HistogramBuckets(buckets))\n\treturn buckets, nil\n}", "func (e *HistogramData) Print(out io.Writer, msg string) {\n\tif len(e.Data) == 0 {\n\t\t_, _ = fmt.Fprintf(out, \"%s : no data\\n\", msg) // nolint: gas\n\t\treturn\n\t}\n\t// the base counter part:\n\t_, _ = fmt.Fprintf(out, \"%s : count %d avg %.8g +/- %.4g min %g max %g sum %.9g\\n\",\n\t\tmsg, e.Count, e.Avg, e.StdDev, e.Min, e.Max, e.Sum)\n\t_, _ = fmt.Fprintln(out, \"# range, mid point, percentile, count\")\n\tsep := \">=\"\n\tfor i, b := range e.Data {\n\t\tif i > 0 {\n\t\t\tsep = \">\" // last interval is inclusive (of max value)\n\t\t}\n\t\t_, _ = fmt.Fprintf(out, \"%s %.6g <= %.6g , %.6g , %.2f, %d\\n\", sep, b.Start, b.End, (b.Start+b.End)/2., b.Percent, b.Count)\n\t}\n\n\t// print the information of target percentiles\n\tfor _, p := range e.Percentiles {\n\t\t_, _ = fmt.Fprintf(out, \"# target %g%% %.6g\\n\", p.Percentile, p.Value) // nolint: gas\n\t}\n}", "func estimateHistMinMax(dp pmetric.HistogramDataPoint) (float64, float64) {\n\tbounds := dp.MExplicitBounds()\n\tcounts := dp.MBucketCounts()\n\n\t// Because we do not know the actual min and max, we estimate them based on the min and max non-empty bucket\n\tminIdx, maxIdx := -1, -1\n\tfor y := 0; y < len(counts); y++ {\n\t\tif counts[y] > 0 {\n\t\t\tif minIdx == -1 {\n\t\t\t\tminIdx = y\n\t\t\t}\n\t\t\tmaxIdx = y\n\t\t}\n\t}\n\n\tif minIdx == -1 || maxIdx == -1 {\n\t\treturn 0, 0\n\t}\n\n\tvar min, max float64\n\n\t// Use lower bound for min unless it is the first bucket which has no lower bound, then use upper\n\tif minIdx == 0 {\n\t\tmin = bounds[minIdx]\n\t} else {\n\t\tmin = bounds[minIdx-1]\n\t}\n\n\t// Use upper bound for max unless it is the last bucket which has no upper bound, then use lower\n\tif maxIdx == len(counts)-1 {\n\t\tmax = bounds[maxIdx-1]\n\t} else {\n\t\tmax = bounds[maxIdx]\n\t}\n\n\treturn min, max\n}", "func PublishHistograms(ctx context.Context, metrics map[string]float64) {\n\n\t// Spans are not processed by the collector until the span ends, so to prevent any delay\n\t// in processing the stats when the current span is long-lived we create a new span for every call.\n\t// suffix the span name with SpannameSuffixDummy to denote that it is used only to hold a metric and isn't itself of any interest\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"histogram_metrics\"+SpannameSuffixDummy)\n\tdefer span.Finish()\n\n\tfor key, value := range metrics {\n\t\t// The field name we use is the metric name prepended with FieldnamePrefixHistogram to designate that it is a Prometheus histogram metric\n\t\t// The collector will replace that prefix with \"fn_\" and use the result as the Prometheus metric name.\n\t\tfieldname := FieldnamePrefixHistogram + key\n\t\tspan.LogFields(log.Float64(fieldname, value))\n\t}\n}", "func (f F) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\ty := mathext.InvRegIncBeta(0.5*f.D1, 0.5*f.D2, p)\n\treturn f.D2 * y / (f.D1 * (1 - y))\n}", "func (src *prometheusMetricsSource) buildHistos(name string, m *dto.Metric, now int64, tags map[string]string) []*MetricPoint {\n\tvar result []*MetricPoint\n\tfor _, b := range m.GetHistogram().Bucket {\n\t\tpoint := src.metricPoint(name+\".\"+fmt.Sprint(b.GetUpperBound()), float64(b.GetCumulativeCount()), now, src.source, tags)\n\t\tresult = src.filterAppend(result, point)\n\t}\n\tpoint := src.metricPoint(name+\".count\", float64(m.GetHistogram().GetSampleCount()), now, src.source, tags)\n\tresult = src.filterAppend(result, point)\n\tpoint = src.metricPoint(name+\".sum\", float64(m.GetHistogram().GetSampleSum()), now, src.source, tags)\n\tresult = src.filterAppend(result, point)\n\treturn result\n}", "func funcHistogramSum(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: sample.H.Sum,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func (r *BasicResampler) Quantile(q float64) float64 {\n\treturn quantile(r.sampleAggregates, q)\n}", "func (h *Histogram) filterHistogram(newBuckets []Bucket) *Histogram {\n\tcheckBucketsValid(newBuckets)\n\n\ttotal := int64(0)\n\tfor _, b := range newBuckets {\n\t\ttotal += b.NumEq + b.NumRange\n\t}\n\n\tif total == 0 {\n\t\treturn &Histogram{}\n\t}\n\n\tselectivity := float64(total) / float64(h.RowCount)\n\n\t// Estimate the new DistinctCount based on the selectivity of this filter.\n\t// todo(rytaft): this could be more precise if we take into account the\n\t// null count of the original histogram. This could also be more precise for\n\t// the operators =, !=, in, and not in, since we know how these operators\n\t// should affect the distinct count.\n\tdistinctCount := int64(float64(h.DistinctCount) * selectivity)\n\tif distinctCount == 0 {\n\t\t// There must be at least one distinct value since RowCount > 0.\n\t\tdistinctCount++\n\t}\n\n\treturn &Histogram{\n\t\tRowCount: total,\n\t\tDistinctCount: distinctCount,\n\n\t\t// All the returned rows will be non-null for this column.\n\t\tNullCount: 0,\n\t\tBuckets: newBuckets,\n\t}\n}", "func (line *Percentiles) Stats() Stats {\n\treturn PointsStats(line.Data)\n}", "func (c ChiSquared) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\treturn mathext.GammaIncRegInv(0.5*c.K, p) * 2\n}", "func getHistogram(src [][3]int, size float64, pixels *[HistSize][3]float64, hist *[HistSize]float64) {\n\tvar ind, r, g, b, i int\n\tvar inr, ing, inb int\n\n\tfor i = range src {\n\t\tr = src[i][0]\n\t\tg = src[i][1]\n\t\tb = src[i][2]\n\n\t\tinr = r >> Shift\n\t\ting = g >> Shift\n\t\tinb = b >> Shift\n\n\t\tind = (inr << (2 * HistBits)) + (ing << HistBits) + inb\n\t\tpixels[ind][0], pixels[ind][1], pixels[ind][2] = float64(r), float64(g), float64(b)\n\t\thist[ind]++\n\t}\n\n\t// normalize weight by the number of pixels in the image\n\tfor i = 0; i < HistSize; i++ {\n\t\thist[i] /= size\n\t}\n}", "func NewMetricAggregator(\n\tpercentThresholds []float64,\n\texpiryIntervalCounter time.Duration,\n\texpiryIntervalGauge time.Duration,\n\texpiryIntervalSet time.Duration,\n\texpiryIntervalTimer time.Duration,\n\tdisabled gostatsd.TimerSubtypes,\n\thistogramLimit uint32,\n) *MetricAggregator {\n\ta := MetricAggregator{\n\t\texpiryIntervalCounter: expiryIntervalCounter,\n\t\texpiryIntervalGauge: expiryIntervalGauge,\n\t\texpiryIntervalSet: expiryIntervalSet,\n\t\texpiryIntervalTimer: expiryIntervalTimer,\n\n\t\tpercentThresholds: make(map[float64]percentStruct, len(percentThresholds)),\n\t\tnow: time.Now,\n\t\tstatser: stats.NewNullStatser(), // Will probably be replaced via RunMetrics\n\t\tmetricMap: gostatsd.NewMetricMap(false),\n\t\tdisabledSubtypes: disabled,\n\t\thistogramLimit: histogramLimit,\n\t}\n\tfor _, pct := range percentThresholds {\n\t\tsPct := strconv.Itoa(int(pct))\n\t\ta.percentThresholds[pct] = percentStruct{\n\t\t\tcount: \"count_\" + sPct,\n\t\t\tmean: \"mean_\" + sPct,\n\t\t\tsum: \"sum_\" + sPct,\n\t\t\tsumSquares: \"sum_squares_\" + sPct,\n\t\t\tupper: \"upper_\" + sPct,\n\t\t\tlower: \"lower_\" + sPct,\n\t\t}\n\t}\n\treturn &a\n}", "func funcHistogramCount(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tinVec := vals[0].(Vector)\n\n\tfor _, sample := range inVec {\n\t\t// Skip non-histogram samples.\n\t\tif sample.H == nil {\n\t\t\tcontinue\n\t\t}\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: enh.DropMetricName(sample.Metric),\n\t\t\tF: sample.H.Count,\n\t\t})\n\t}\n\treturn enh.Out\n}" ]
[ "0.72478664", "0.68278915", "0.6655255", "0.6635397", "0.65988153", "0.64426327", "0.6399307", "0.6295519", "0.6277388", "0.62773055", "0.6276068", "0.62452686", "0.61789775", "0.6087219", "0.60864764", "0.6060348", "0.6037965", "0.6030283", "0.5975477", "0.59296983", "0.59140444", "0.5886086", "0.58504003", "0.58366483", "0.5836038", "0.5808512", "0.5754962", "0.5712795", "0.57104236", "0.5709702", "0.5642232", "0.5403474", "0.5396812", "0.53839153", "0.5337903", "0.53366077", "0.5324039", "0.53067464", "0.528578", "0.5280044", "0.5235157", "0.5157936", "0.5151969", "0.51136196", "0.50805265", "0.5066288", "0.49685797", "0.48930103", "0.48798", "0.4865598", "0.4848614", "0.48475996", "0.48063824", "0.47938806", "0.47730812", "0.47436267", "0.47255927", "0.46906525", "0.46694586", "0.4638903", "0.46144304", "0.46017388", "0.4573158", "0.45617214", "0.45597196", "0.45551333", "0.45405874", "0.4538799", "0.45326808", "0.45105907", "0.44712886", "0.44592303", "0.44590658", "0.44299525", "0.44063488", "0.43706664", "0.43612018", "0.4349071", "0.43472648", "0.43413273", "0.43408796", "0.43225393", "0.4276241", "0.42745048", "0.42625266", "0.4244613", "0.4242292", "0.4236049", "0.42355546", "0.42312592", "0.42227063", "0.42186007", "0.4201551", "0.41858426", "0.41770938", "0.416804", "0.41645005", "0.41616726", "0.41578043", "0.41368502" ]
0.8211825
0